Control Structures and Data Files
Structured Programming Use simple control structures to organize the solution to a problem Sequence Selection Repetition yes no yes no
Sequence
Selection
Repetition
Extras Evaluation of alternative solution Error condition A problem can be solved in many different ways Which is the best (e.g, faster, memory req) Error condition Do not trust user! Check the data. A=b/c; Be clear about specifications Generation of Test Data Test each of the error conditions Program validation and Verification Program walkthrough
Conditional Expressions Selection and repetition structures use conditions, so we will first discuss them A condition is an expression that can be evaluated to be TRUE (any value > 0) or FALSE (value of 0) Conditional Expression is composed of expressions combined with relational and/or logical operators
Relational Operators == equality (x == 3) != non equality (y != 0) < less than (x<y) > greater than (y>10) <= less than equal to (x<=0) >= greater than equal to (x>=y) !!! a==b vs. a=b !!!
Examples a < b x+y >= k/m fabs(denum) < 0.0001 d= b > c if (d) a=b+c; a < b < c ???
Logical Operators ! not !(x==0) && and (x>=0) && (x<=10) || or (x>0) || (x<0) A B A && B A || B !A !B False True
Examples a<b<c is not the same as (a<b) && (b<c) a+b * 2 < 5 && 4>=a/2 || t-2 < 10 a=3, b=5, t=4
Precedence for Arithmetic, Relational, and Logical Operators
Exercise Assume that following variables are declared a = 5.5 b = 1.5 k = -3 Are the following true or false a < 10.0 + k a + b >= 6.5 k != a-b !(a == 3*b) a<10 && a>5 fabs(k)>3 || k<b-a
Selection Statements
Selection Statements if if else switch
If statement if(Boolean expression) statement; //single statement { //more than one statement statement1; . statement n; }
Examples if (x>0) { x=sqrt(x); } k++; 4 2 x k -2 2 x k 4 2 x k -2 2
if - else statement if (boolean expression) statement1; else { statement block1 } statement block2 x=y; x=y; k=3;
If-else statement What does the following program do? Assume that x, y, temp are declared. if (x>y) temp = x; else temp = y; 1 3 ? x y temp 3 1 ? x y temp
If-else statement Split the following statement into two separate if if (x>y) temp = x; else temp = y; if (x>y) temp = x; if (x<=y) temp = y;
Exercise Write an if-else statement to find both the maximum and minimum of two numbers. Assume that x,y, min, max are declared. if (x>y) Ex: x = 10, y = 5 { y = 3, y = 4 max = x; x = 6, y = 6 min = y; } else { max = y; min = x;
nested if-else if(x > y) if(y < z) k++; if (y<z) k++; else m++; j++; if (y<z) k++; else m++;
Exercise int x=9, y=7, z=2, k=0, m=0, j=0; if (x > y) if(y < z) else m++; j++; What are the values of j, k and m after execution of if statement? 9 7 x y 2 z k m j
Exercise int x=3, y=7, z=2, k=0, m=0, j=0; if (x > y) if(y < z) else m++; j++; What are the values of j, k and m after execution of if statement? 3 7 x y 2 z k m j
Exercise What is the output of the following program int a = 5, b = 3; if (a>10) { a = 50; b = 20; } printf(" a = %d, b = %d\n",a, b); if (a>10) a = 50; b = 20; printf(" a = %d, b = %d\n",a, b); if (a>10) { a = 50; b = 20; } printf(" a = %d, b = %d\n",a, b); if (a>10) a = 50; b = 20; printf(" a = %d, b = %d\n",a, b);
Exercise Given a score and the following grading scale write a program to find the corresponding grade. 80-100 A 60-79 B 40-59 C 0-39 D
Solution if ((score >= 80) && (score <=100)) grade = 'A'; else if ((score >= 60) && (score <= 79)) grade = 'B'; else if ((score >= 40) && (score <= 59)) grade = 'C'; else if ((score >= 0) && (score <= 39)) grade = 'D'; else printf("Invalide Score\n");
Alternate Solution printf(“Invalid Score\n”); else if (score >= 80) grade = 'A'; else if (score >= 60) grade = 'B'; else if (score >= 40) grade = 'C'; else if (score >= 0) grade = 'D'; else printf("Invalide Score\n");
Exercise What is the value of a at the end of the following if-else statement (chapter3e2.c) int a = 750; if (a>0) if (a >= 1000) a = 0; else if (a <500) a *= 2; a *= 10; a += 3; if (a>=1000) a = 0; else if (a<500) a *= 2; a *= 10; if (a<500) a *= 2; else a *= 10;
Exercise Write a program that reads 3 numbers a, b and c from user and computes minimum, maximum and median of the numbers. Example: a = 2, b = 5, c = 3 minimum = 2, maximum = 5, median = 3 a = 2, b = 2, c = 3 minimum = 2, maximum = 3, median = 2
Minimum if ((a<b) && (a<c)) min = a; else if ((b<a) && (b<c)) min = b; else if ((c<a) && (c<b)) min = c;
Maximum if ((a>b) && (a>c)) max = a; else if ((b>a) && (b>c)) max = b; else if ((c>a) && (c>b)) max = c;
Median median = b; else if ((c<b) && (b<a)) if ((a<b) && (b<c)) median = b; else if ((c<b) && (b<a)) else if ((b<a) && (a<c)) median = a; else if ((c<a) && (a<b)) else if ((b<c) && (c<a)) median = c; else if ((a<c) && (c<b))
Alternate Solution for Median if (((a<b) && (b<c)) || ((c<b) && (b<a))) median = b; else if (((b<a) && (a<c)) || ((c<a) && (a<b))) median = a; else if (((b<c) && (c<a)) || ((a<c) && (c<b))) median = c;
Exercise continued Find minimum of 3 numbers Write an if statement to check if minimum is a if (condition) what should min = a; be condition? Write an if statement to check if minimum is b Write an if statement to check if minimum is c Combine 1-3 into a single nested if-else statement Similarly find maximum of 3 numbers Find median of 3 numbers
Exercise Write a program that reads a point (x, y) from user and prints the region it resides in. For example Enter x, y: 3 -1 Point in Region 4 Enter x, y: -1 -5 Point in Region 3 Region 2 Region 1 Region 3 Region 4
Solution if ((x>0) && (y>0)) printf("Region 1\n"); else if ((x<0) && (y>0)) printf("Region 2\n"); else if ((x<0) && (y<0)) printf("Region 3\n"); else if ((x>0) && (y<0)) printf("Region 4\n");
Alternate Solution if (x>0) if (y>0) printf("Region1\n"); else
Switch Statement switch(expression) { case constant: statement(s); break; /* default is optional*/ default: }
Switch Statement switch (op_code) Expression must be of type integer or character The keyword case must be followed by a constant break statement is required unless you want all subsequent statements to be executed. switch (op_code) { case ‘N’: printf(“Normal\n”); break; case ‘M’: printf(“Maintenance Needed\n”); break’ default: printf(“Error\n”); }
Exercise Convert the switch statement into if statement. switch (op_code) { case ‘N’: printf(“Normal\n”); break; case ‘M’: printf(“Maintenance Needed\n”); default: printf(“Error\n”); } if (op_code == ‘N’) printf(“Normal\n”); else if (op_code == ‘M’) printf(“Maintenance Needed\n”); else printf(“Error\n”);
Exercise Convert the following nested if/else statements to a switch statement if (rank==1 || rank==2) printf("Lower division \n"); else { if (rank==3 || rank==4) printf("Upper division \n"); { if (rank==5) printf("Graduate student \n"); printf("Invalid rank \n"); }
Solution { case 1: case 2: printf("Lower Division\n"); break; case 3: switch(rank) { case 1: case 2: printf("Lower Division\n"); break; case 3: case 4: printf("Upper Division\n"); case 5: printf("Graduate Student\n"); default: printf("Invalid Rank"); }
Exercise Write a switch statement that prints the number of days in the month given an integer corresponding to month int month; switch (month) 1-12 represents months January – December. February has 28 days. April, June, September, November has 30 days January, March, May, July, August, October, December has 31 days.
Solution { case 2: printf("28 Days\n"); break; switch(month) { case 2: printf("28 Days\n"); break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: printf("31 days\n"); case 4: case 6: case 9: case 11: printf("30 days\n"); default: printf("Invalid month"); }
Loop (Repetition) Structures
Loop (repetition) statements while statement do while statement for statement
while statement while(expression) statement; { . } x=1; while (x<5) x = x + 1; while(expression) statement; { . } x = 1; while (x<5) { x = x+1; printf(“X=“%d”,x); }
Example: lecture2e4.c #include <stdio.h> #define PI 3.141593 int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); while (degrees <= 360) radians = degrees*PI/180; printf("%6i %9.6f \n",degrees,radians); degrees += 10; } return 0;
do while do statement; while(expression); { statement1; statement2; . note - the expression is tested after the statement(s) are executed, so statements are executed at least once. x=1; do x = x + 1; while (x<5); x = 1; do { x = x+1; printf(“X=“%d”,x); } while (x<5);
Example: lecture2e5.c #include <stdio.h> #define PI 3.141593 int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); do radians = degrees*PI/180; printf("%6i %9.6f \n",degrees,radians); degrees += 10; } while (degrees <= 360); return 0; }
for statement for(initialization; test; increment/decrement) { . } for (x=1; x<5; x++) printf(“x=%d\n”,x); for (x=1; x<5; x++) { printf(“X=“%d\n”,x); printf(“X^2 = %d\n”,x*x); }
for statement initalize test increment/ decrement true statement(s)
Examples ? 5 1 3 1 5 7 i sum n fact 1 4 9 int sum =0; for( i=1 ; i < 7 ; i+=2 ) sum = sum + i; int fact =1; for ( n=5;n>1;n--) fact = fact * n; ? 5 1 3 1 5 7 i sum n fact 1 4 9
Example: lecture2e6.c #include <stdio.h> #define PI 3.141593 int main(void) { int degrees; double radians; printf("Degrees to Radians \n"); for (degrees=0; degrees<=360; degrees+=10) radians = degrees*PI/180; printf("%6i %9.6f \n",degrees,radians); } return 0;
Exercise { statements; } for (count=-2; count<=5; count++) Determine the number of times that each of the following for loops are executed. for (k=3; k<=10; k++) { statements; } for (count=-2; count<=5; count++)
Exercise Write a loop to print Hello 10 times for (i=1; i<=10; i++) { printf(“Hello\n”); } Change it to print Hello 20 times Change it to print the count besides each hello Hello 1 Hello 2
Exercise Write program to compute the following using a for loop Result = 55 Result = 45
Exercise Convert the following for loop to while loop for (i=5; i<10; i++) { printf(“ i = %d \n”, i); } i=5; while (i<10) i++;
Exercise Write a loop to compute xy for y integer without using pow(x,y) res=1; for (i=1; i<=y; i++) { res = res * x; } 20 = 1 21 = 2 22 = 2*2 23 = 2*2*2
Exercise Write a program to compute the following total=0; sofarx=1; for (i=0; i<=m; i++) { total = total +sofarx; sofarx = sofarx * x; } total=0; for (i=0; i<=m; i++) total = total + pow(x, i);
Exercise Write a program to compute the following ln2=0; for (i=1; i<=n; i++) if ( i % 2 == 0) ln2 = ln2 - 1.0 / i; else ln2 = ln2 + 1.0 / i;
Exercise What is the output of the following program? for (i=1; i<=5; i++) { for (j=1; j<=4; j++) printf(“*”); printf(“\n”); } Available on class webpage: lecture2e7.c Output ****
Exercise What is the output of the following program? for (i=1; i<=5; i++) { for (j=1; j<=i; j++) printf(“*”); printf(“\n”); } Available on class webpage: lecture2e8.c Output * ** *** **** *****
Exercise Modify the following program to produce the output. for (i=A; i<=B; i++) { for (j=C; j<=D; j++) printf(“*”); printf(“\n”); } Output ***** **** *** ** *
Exercise Write a program using loop statements to produce the output. * ** *** **** ***** for (i=1; i<=5; i++) { for (j=1; j<=5-i; j++) printf(" "); for (k=1; k<=i; k++) printf("*"); printf("\n"); }
break statement break; terminates loop execution continues with the first statement following the loop sum = 0; for (k=1; k<=5; k++) { scanf(“%lf”,&x); if (x > 10.0) sum +=x; } printf(“Sum = %f \n”,sum); Available on class webpage: lecture2e9.c
continue statement continue; forces next iteration of the loop, skipping any remaining statements in the loop sum = 0; for (k=1; k<=5; k++) { scanf(“%lf”,&x); if (x > 10.0) sum +=x; } printf(“Sum = %f \n”,sum); Available on class webpage: lecture2e10.c