Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures and Data Files

Similar presentations


Presentation on theme: "Control Structures and Data Files"— Presentation transcript:

1 Control Structures and Data Files

2 Structured Programming
Use simple control structures to organize the solution to a problem Sequence Selection Repetition yes no yes no

3 Sequence

4 Selection

5 Repetition

6 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

7 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

8 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 !!!

9 Examples a < b x+y >= k/m fabs(denum) < 0.0001 d= b > c
if (d) a=b+c; a < b < c ???

10 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

11 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

12 Precedence for Arithmetic, Relational, and Logical Operators

13 Exercise Assume that following variables are declared
a = 5.5 b = k = -3 Are the following true or false a < k a + b >= 6.5 k != a-b !(a == 3*b) a<10 && a>5 fabs(k)>3 || k<b-a

14 Selection Statements

15 Selection Statements if if else switch

16 If statement if(Boolean expression) statement; //single statement
{ //more than one statement statement1; . statement n; }

17 Examples if (x>0) { x=sqrt(x); } k++; 4 2 x k -2 2 x k 4 2 x k -2 2

18 if - else statement if (boolean expression) statement1; else
{ statement block1 } statement block2 x=y; x=y; k=3;

19 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

20 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;

21 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;

22 nested if-else if(x > y) if(y < z) k++; if (y<z) k++; else
m++; j++; if (y<z) k++; else m++;

23 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

24 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

25 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);

26 Exercise Given a score and the following grading scale write a program to find the corresponding grade. A B C 0-39 D

27 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");

28 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");

29 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;

30 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

31 Minimum if ((a<b) && (a<c)) min = a;
else if ((b<a) && (b<c)) min = b; else if ((c<a) && (c<b)) min = c;

32 Maximum if ((a>b) && (a>c)) max = a;
else if ((b>a) && (b>c)) max = b; else if ((c>a) && (c>b)) max = c;

33 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))

34 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;

35 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

36 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

37 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");

38 Alternate Solution if (x>0) if (y>0) printf("Region1\n"); else

39 Switch Statement switch(expression) { case constant: statement(s);
break; /* default is optional*/ default: }

40 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”); }

41 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”);

42 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"); }

43 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"); }

44 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.

45 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"); }

46 Loop (Repetition) Structures

47 Loop (repetition) statements
while statement do while statement for statement

48 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); }

49 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;

50 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);

51 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; }

52 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); }

53 for statement initalize test increment/ decrement true statement(s)

54 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

55 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;

56 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++)

57 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

58 Exercise Write program to compute the following using a for loop
Result = 55 Result = 45

59 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++;

60 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

61 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);

62 Exercise Write a program to compute the following ln2=0;
for (i=1; i<=n; i++) if ( i % 2 == 0) ln2 = ln / i; else ln2 = ln / i;

63 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 ****

64 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 * ** *** **** *****

65 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 ***** **** *** ** *

66 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"); }

67 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

68 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


Download ppt "Control Structures and Data Files"

Similar presentations


Ads by Google