Upload
elwin-harrington
View
222
Download
1
Embed Size (px)
Citation preview
آبان 85 (C) NematAllah Ahmadyan 1
Flowchart & Control Structures
Introduction to Programming course
40-143c
آبان 85 (C) NematAllah Ahmadyan 2
At a glance
Control Structures Control Statements
• If
• for
• while
• Switch
• do…while
• …
آبان 85 (C) NematAllah Ahmadyan 3
IF and IF…ELSE structure
1. int x = … ;2. if ( x%3 == 0 ){ 3. … /* x = 3k */4. }else if ( x%3 ==
1 ){ 5. … /* x = 3k + 1 */6. }else {7. … /* x = 3k +2 */8. }
آبان 85 (C) NematAllah Ahmadyan 4
FOR structure
1. int i , j;2. for (i=1 ; i<=size-1 ; i++)
{3. for(j=1 ; j<size-1 ; j++){4. if(a[j] > a[j+1])5. swap(&a[j],&a[j+1]);6. }7. }8. /* this is a main code of
bubble-sort */
آبان 85 (C) NematAllah Ahmadyan 5
WHILE & DO…WHILE structure
1. int input = 0;2. int sum = 0 ;3. while ( input!=-1 )
{4. scanf(“%d”,
&input );5. sum += input ;6. }
آبان 85 (C) NematAllah Ahmadyan 6
WHILE & DO…WHILE structure
1. int number, digit, number_r ;
2. do {3. digit = number % 10 ;4. number /= 10 ;5. number_r += digit *
pow(10,num_digit-i);
6. ++i ;7. }while(number >
0);
آبان 85 (C) NematAllah Ahmadyan 7
BREAK structure1. for ( i = 3 ; ; i += 2 ) {2. term =3. _sign * (pow(x,i) / fact(i)) ;4. _sign = -1 * _sign ;5. abs = term>0 ? term :
-term ;6. if ( abs < 0.0001 )
break;7. sine = sine + term ;8. }9. /* calculate sin(x) from 10. x - x^3 / 3! + x^5/5! ... */11. /* while(1){} can be used
too. */
آبان 85 (C) NematAllah Ahmadyan 8
SWITCH structure
1. switch(j){2. case 0: k=1; break;3. case 1: k=2; break;4. case 2: k=0; break;5. default: {6. printf(“ERROR");7. exit(1);8. }9. }
آبان 85 (C) NematAllah Ahmadyan 9
Finally…
CommentingClear code Versus Tricky codeAvoid labels: and goto