Flowchart & Control Structures Introduction to Programming course 40 -143 c آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 1
At a glance l l Control Structures Control Statements • If • for • while • Switch • do…while • … آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 2
IF and IF…ELSE structure 1. 2. 3. 4. 5. 6. 7. int x = … ; if ( x%3 == 0 ){ … /* x = 3 k */ }else if ( x%3 == 1 ){ … /* x = 3 k + 1 */ }else { … /* x = آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 3 k +2 */ 3
FOR structure 1. 2. 3. 4. 5. 6. 7. 8. int i , j; for (i=1 ; i<=size-1 ; i++){ for(j=1 ; j<size-1 ; j++){ if(a[j] > a[j+1]) swap(&a[j], & a[j+1]); } } /* this is a main code of آﺒﺎﻥ 85 bubble-sort */ (C) Nemat. Allah Ahmadyan 4
WHILE & DO…WHILE structure 1. 2. 3. 4. 5. 6. int input = 0; int sum = 0 ; while ( input!=-1 ){ scanf(“%d”, &input ); sum += input ; } آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 5
WHILE & DO…WHILE structure 1. 2. 3. 4. 5. 6. int number, digit, number_r ; do { digit = number % 10 ; number /= 10 ; number_r += digit * pow(10, num_digiti); آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan ++i ; 6
BREAK structure 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. for ( i = 3 ; ; i += 2 ) { term = _sign * (pow(x, i) / fact(i)) ; _sign = -1 * _sign ; abs = term>0 ? term : -term ; if ( abs < 0. 0001 ) break; sine = sine + term ; } /* calculate sin(x) from x - x^3 / 3! + x^5/5!. . . */ آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 7
SWITCH structure 1. 2. 3. 4. 5. 6. 7. 8. switch(j){ case 0: k=1; break; case 1: k=2; break; case 2: k=0; break; default: { printf(“ER ROR"); exit(1); } آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 8
…Finally Commenting l Clear code Tricky code l Avoid labels: and goto l Versus آﺒﺎﻥ 85 (C) Nemat. Allah Ahmadyan 9