Presentation is loading. Please wait.

Presentation is loading. Please wait.

Engineering Problem Solving with C

Similar presentations


Presentation on theme: "Engineering Problem Solving with C"— Presentation transcript:

1 Engineering Problem Solving with C
CSCI-125/ENGR-144 Engineering Problem Solving with C Ch 3

2 3.1 Algorithm Development
So far, we considered very simple programs (read, compute, print) Top-down Design Start from the big picture Use a process called divide-and-conquer Keep dividing the problem until steps are detailed enough to convert to a program Refinement with Pseudo-code (English like statements) and Flowchart (diagram, graph)

3 Pseudo-code Notation and Flowchart Symbols

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

5 Sequence

6 Selection

7 Repetition

8 Extras Evaluation of alternative solution Error condition
A problem can be solved in many different ways Which is the best (e.g, faster, less 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

9 3.2 Conditional Expressions
Selection and repetition structures use conditions, so we will first discuss them A condition is an expression (e.g., x= a > b) 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

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

11 Examples A < B fabs(denum) < 0.0001 D = b > c; if (D) A=b+c;
4 2 -0.01 ? 6 1 10 A B denum D b c X Y K A < B fabs(denum) < D = b > c; if (D) A=b+c; Mixing with arithmetic op X+Y >= K/3

12 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

13 Examples A<B && C>=5 A+B * 2 < 5 && 4>=A/2
A<B || C<B && A-2 < 10 A < B < C ???? A<B<C is not the same as (A<B) && (B<C) 4 2 6 A B C

14 Precedence for Arithmetic, Relational, and Logical Operators

15 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

16 Exercise Assume that following variables are declared
x = 3.0 y = z = 2.0 flag = 0 Are the following true or false x > z && y > z x+ y/z <= 3.5 z > x || z > y !flag x == 1.0 || x == 3.0 z < x && x < y x <= z || x >= y !flag || y + z >= x – z !(flag || y + z >= x – z)

17 Exercise Assume that following variables are declared
a = 5 b = c = 15 flag =1 Are the following true or false C == a + b || !flag a != 7 && flag || c >=6 ! (b < = 12) && a%2 ==0 ! ( a > 5 || c < a +b )

18 3.3 Selection Statements if if else switch

19 if statement if(Boolean expression) statement; /* single statement */
/* more than one statement */ statement1; statement n; }

20 if statement - examples
if (x > 0) k++; if(x > 0) { y = sqrt(x); } if(x > 0) /* a common mistake */ Name Addr Content x 9 y 5 k 4

21 if else statement if(Boolean expression) statement; else
statement block } else { }

22 if else statement if (x > y) temp = x; else temp = y;
What does the following program do? Assume that x, y, temp are declared. if (x > y) temp = x; else temp = y; Name Addr Content x 9 y 5 temp ? if (x > y){ temp = x; } else { temp = y; }

23 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) { max = x; min = y; } else { max = y; min = x; } Name Addr Content x y max ? min 9 5 3 8 9 5 3 8 6 8 3 6

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

25 Flow chart for previous slide
if (x > y) temp = x; if (x <= y) temp = y; if (x > y) temp = x; else temp = y; x > y T temp=x x > y T x <= y T temp=y temp=x temp=y

26 if else statement (Exercise)
Give the final value of x if the initial value x is 1 if (x >= 0) x = x+1; Else if (x >=1) x = x+2; if (x >= 0) x = x+1; if (x >= 1) x= x+2;

27 nested if-else if(x > y) if(y < z) k++; else m++; j++;
} j++; F x > y T T y < z j++ F k++ m++

28 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?

29 Exercise: Find the value of a
a =a+3 a < 500 a =a*2 a =a*10 T int a = 750; if (a>0) if (a >= 1000) a = 0; else if (a <500) a =a*2; a =a*10; a =a+3;

30 Exercise: Find the value of a
int a = 750; if (a>0) { if (a >= 1000) { a = 0; } else { if (a <500) { a =a*2; a =a*10; } a =a*3; a > 0 a >= 1000 a = 0 a =a+3 a < 500 a=a*2 a =a*10 T

31 Indentation int a = 750; if (a>0) if (a >= 1000) a = 0; else
Good Not good

32 Nested if What is the difference, if any? if( expression1 )
statement1; else statement2; if( expression1 ) if( expression2 ) statement1; else statement2; No difference! Spacing is only important to us to make the program readable, not to the compiler.

33 Indentation (cont’d) What is the output of the following programs
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); Not good 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); Good

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

35 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”); default: printf(“Error\n”); }

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

37 /* determine average life expectancy of a standard light bulb */
switch (watts) { case 25: life = 2500; break; case 40: case 60: life = 1000; break; case 75: case 100: life = 750; break; default: life =0; }

38 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"); } 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 \n"); }

39 with this section of code?
char a, b, c, d, f, grade; int actr, bctr, cctr, dctr, fctr, ictr; printf(“Enter letter grade: “); scanf(“%c”, &grade); switch (grade) { case a: ++actr; break; case b: ++bctr; case c: ++cctr; case d: ++dctr; case f: ++fctr; default: ++ictr; } /* given these declarations */ What’s wrong with this section of code? Answer: counters not initialized case needs constants, not variables Not using constants for each case will cause compiler error Not initializing counter variables is logical error, but will NOT cause compiler error

40 More selection examples

41 Exercise: Assign Letter Grade
Given a score and the following grading scale write a program to find the corresponding grade. A B C D 0-59 F

42 Solution-1 grade = 'A'; else if ((score >= 80) && (score <= 89))
grade = 'B'; else if ((score >= 70) && (score <= 79)) grade = 'C'; else if ((score >= 60) && (score <= 69)) grade = ‘D'; else if ((score >= 0) && (score <= 59)) grade = ‘F'; else printf("Invalide Score\n");

43 Solution-2 if ((score >= 0) && (score <= 100)) grade = 'A';
else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = ‘D'; else grade = ‘F'; printf("Invalide Score\n");

44 Exercise: Region in a plane
Write a program that reads a point (x, y) from user and prints its region For example Enter x y: This point is in Region 4 Enter x y: -1 -5 This point is in region 3 Enter x y: 0 5 ??????? Region 1 Region 2 Region 4 Region 3

45 Exercise: The Roots Write a program to ask users to input the coefficients (a, b, c) of a quadratic equation ax^2+bx+c=0, then compute its roots. Example: a = 1, b = -5, c = 6 a=1, b=2, c=2 a = 0, b = 2, c = 4 a=0, b=0, c=0

46 Exercise: which task takes more time
Suppose we have two tasks A and B A takes x hours, y minutes, and z seconds B takes X hours, Y minutes, and Z seconds User enters x, y, z and X, Y, Z Write if-else statements to print out which task takes more time?

47 Triangle inequality Suppose we want to check if we can make a triangle using a, b, c |a-b| <= c |a-c| <= b |b-c| <= a a+b >= c a+c >= b b+c >= a c a b

48 Max, Min, Median Write a program that reads 3 numbers a, b and c from user and computes minimum, median and maximum 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

49 Charge for money transfer
Suppose you transfer $N and bank’s charge occurs as follows. Write a program that reads N and computes cost

50 Compute Queuing Delay Write C program that computes and prints out average delay in a queuing system, where the average delay is given as follows

51 Spell out a number in text using if-else and switch
Write a program that reads a number between 1 and 999 from user and spells out it in English. For example: 453  Four hundred fifty three 37  Thirty seven 204  Two hundred four

52 Loop (Repetition) Structures

53 Problem: Conversion table degrees  radians
Degrees to Radians radians = degrees * PI / 180;

54 Sequential Solution #include <stdio.h> #define PI 3.141593
int main(void) { int degrees=0; double radians; printf("Degrees to Radians \n"); degrees = 0; radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees = 10; degrees = 20; degrees = 360; } degrees = ??? radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); Not a good solution

55 Loop Solution #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; } degrees = ??? radians = degrees*PI/180; printf("%6i %9.6f \n", degrees, radians); degrees+=10 means degrees= degrees+10

56 Loop (Repetition) Structures
while statement do while statement for statement Two new statements used with loops break and continue

57 while statement while(expression) statement; while(expression) { }

58 Example #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;

59 while() Scanf(“%d”, &n); ev=0; while (ev < n) {
printf(“%3d\n”, ev); ev +=2; } printf(“\n”); what is displayed by this program for an input of 10? while() i = 0; while ( i <= 5 ) { printf(“%3d%3d\n”, i, 10-i); i +=1; } Predict the output? Printf(“Enter an integer>”); scanf(“%d”, &x); product=x; count =0; while (count < 4) { printf(“%d\n”, product); product *=x; count +=1; } Output values if a data value 5? 6? 7? No, the results are different. Step through the code and see.

60 Sample C Code scanf in while
while(( vals = scanf( “%lf%c%lf”, &op1, &action, &op2)) == 3 ) scanf statement result stored here; optional this value compared to A scanf() is done, accepting a double (long float), a char, and a double. The scanf() function returns the number of successful scans completed, which may be stored in a variable for later examination (rarely) or simply tested directly (e.g., remove the 'vals ='). Regardless, the expression is tested for its value, which in this case is the value returned by scanf(), which is also the value assigned to vals. That value is compared to the value 3, and if equal (that is, the expression value is equal to 3), the while() loop continues. Otherwise, the loop is exited. If the inputs are 35.6c9.3 and 34.7bb, what are output for vals = scanf( “%lf%c%lf”, &op1, &action, &op2)

61 do while do statement; while(expression); do { statement1; statement2;
... } while(expression); note - the expression is tested after the statement(s) are executed, so statements are executed at least once.

62 Example #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; }

63 while() vs do while() int x = 10, y = 1; while ( x < 10 ) {
if( x == 10 ) y = x; ++x; } printf(“x = %d\n”, x); printf(“y = %d\n”, y); int x = 10, y = 1; do { if( x == 10 ) y = x; ++x; } while ( x < 10 ); printf(“x = %d\n”, x); printf(“y = %d\n”, y); No, the results are different. Step through the code and see. Do these produce the same result?

64 for statement for(initialization ; test ; increment or decrement )
{ }

65 Example #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;

66 for statement initialize test Increment or decrement true statement(s)

67 Difference? for(i=0; i<5; i++) printf("%d", i);
int i = 0; while(i < 5) { printf("%d", i); i++; } ++i; int i = 0; int j = i; while(j < 5) { printf("%d", i); j = ++i; } int i = 0;int j = i; j = i++;

68 Increment and Decrement Operators
Increment Operator ++ post increment x++; pre increment ++x; Decrement Operator -- post decrement x--; pre decrement --x; } x=x+1; } x=x-1; But, the difference is in the following example. Suppose x=10; A = x++ - 5; means A=x-5; x=x+1; so, A= 5 and x=11 B =++x - 5; means x=x+1; B=x-5; so, B=6 and x=11

69 Examples ? 5 1 3 1 5 7 i sum n fact 1 4 9 int sum =0, i;
for( i=1 ; i < 7;i=i+2 ){ sum = sum+i; } int fact=1, n; for( n=5 ; n>1 ; n--){ fact = fact * n; ? 5 1 3 1 5 7 i sum n fact 1 4 9 n--; means n=n-1; n++; means n=n+1;

70 Example What will be the output of the following program, also show how values of variables change in the memory. int sum1, sum2, k; sum1 = 0; sum2 = 0; for( k = 1; k < 5; k++) { if( k % 2 == 0) sum1 =sum1 + k; else sum2 = sum2 + k; } printf(“sum1 is %d\n”, sum1); printf(“sum2 is %d\n”, sum2); sum1 sum2 k sum1 is 6 sum2 is 4

71 Exercise for (k=3; k<=10; k++) { statements; }
Determine the number of times that each of the following for loops are executed. for (k=3; k<=10; k++) { statements; } for (k=5; k<=83; k+=4) { for (count=20; count>=0; count=count-2) {

72 for() loop example How many times does the body loop?
For (count =0; count <=n; ++ count) { sum +=count; } if want to execute the loop body n times, how to change code? sum=0; k=1; for (i = -n; i < n-k; ++i) sum +=i*i;

73 for() loop example Trace the following program segment: j=10;
for (i=1; i<=5; ++i) { printf(“%d %d \n”, i, j); j -=2; } Rewrite the previous program segment so that it produced the same output but uses 0 as the initial value of i ?

74 for() Logic of for() is like that of while() Compare the code:
int ctr; for( ctr = 1; ctr < 10; ++ctr ) printf(“Ctr = %d\n”, ctr); int ctr; ctr = 1; while ( ctr < 10 ) { printf(“Ctr = %d\n”, ctr); ++ctr; } Both segments of code do the same thing in the same order. Always think of the test in the middle expression of a for() as the same as a while(), because it works the same way.

75 For vs. while loop (Exercise)
Convert the following for loop to while loop for( i=5; i<10; i++) { pritntf(“ i = %d \n”, i); } i=5; while(i<10){ i++;

76 More loop examples

77 /* Counting down to blast-off */ #include <stdio.h>
int main(void) { int time, start; printf("Enter starting time (an integer) in seconds> "); scanf("%d", &start); printf("\nBegin countdown\n"); for (time = start; time > 0; time -= 1) { printf("T - %d\n", time); } printf("Blast-off!\n"); return (0); Enter starting time (an integer) in seconds> 5 Begin countdown T - 5 T - 4 T - 3 T - 2 T - 1 Blast-off!

78 for() loop example Trace the execution of the loop that follows for n=8. Show the values of odd and sum after the update of the loop counter for each iteration? sum=0; for (odd = 1; odd < n; odd += 2) sum +=odd; printf(“Sum of positive odd numbers less than %d is %d.\n”, n,sum)

79 Example Write a program that prints in two columns n even numbers starting from 2, and a running sum of those values. For example suppose user enters 5 for n, then the program should generate the following table: Enter n (the number of even numbers): 5 Value Sum

80 #include <stdio.h>
int main(void) { /* Declare variables. */ int n; int sum, i; printf("Enter n "); scanf("%d",&n); printf("Value \t Sum\n"); sum = 0; for(i=1; i <=n; i++){ sum = sum + 2*i; printf("%d \t %d\n", 2*i, sum); } return 0;

81 Nested loop examples

82 a for() loop initialize variables i, j, and k each to 1
test to end loop when i > 10 or j > 3 * k increment i by 1, j by 2, and k by 2 * i print i, j, and k in the body of the loop expression 1 expression 2 expression 3 for ( i = 1, k = 1, j = 1; i <= 10 && j <= 3 * k ; ++i, j += 2, k += 2 * i ) printf(“i = %d, j = %d, k = %d\n”, i, j, k); initialize variables the first section of the for() statement is done only once, so variable initialization is typically done here. Note the use of the comma operator! i = 1, j = 1, k = 1; sets each to 1 could also have done i=j=k=1; without using the comma operator. test to end loop but the for() loop test for a non-zero result to continue the loop! So the logic must be inverted. Ending the loop when i > 10 means the same as continuing the loop while i <= 10; ending the loop when j > 3*k means the same as continuing the loop while j <= 3*k. Ending the loop when condition-1 or condition-2 occurs means the same as continuing the loop while condition-1 and condition-2 are both true. Do not use comma operator here; use only single or compound expressions. incrementing the counters ++i adds 1 to i j+=2 adds to to k (same as j = j + 2) k+=2*i adds 2*i to k (as in k = k + 2*i) note the use of the comma operator; order here is important, for k gets the value of the incremented i*2; if k+=2*i were placed before the ++i, then the old value of i would have been used! print the results in the body of the for() loop Note the use of the comma operator in expression 1 and expression 3. Do not use comma operator in expression 2.

83 Exercise What is the output of the following program?
for (i=1; i<=5; i++) { for (j=1; j<=4; j++){ printf(“*”); } printf(“\n”); Output ****

84 for() loop example How many lines of asterisks are displayed?
for (i= 0; i < 10; ++i) for (j=0; j < 5; ++j) printf(“**********\n”); for (row= 1; row <=10; row++) { for (col=1; col<= 10; col++) { printf(“%4d\n”, row*col); }

85 Exercise What is the output of the following program?
for (i=1; i<=5; i++) { for (j=1; j<=i; j++){ printf(“*”); } printf(“\n”); Output * ** *** **** *****

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

87 for() loop example How many times for the first printf? How many times for the second printf? What is the last value displayed? For (i = 0; i < 7; ++i ) { for ( j =0; j < i; ++j ) printf(%4d”, i*j); printf(“\n”); }

88 Example: nested loops to generate the following output
int i, j; for(i=1; i <= 5; i++){ printf("i=%d ", i); for(j=1; j <= i; j++) { if (i % 2 == 0) printf("+ "); else printf("* "); } printf("\n"); int i, j; for(i=1; i <= 5; i++){ printf("i=%d ", i); for(j=1; j <= i; j++) { if (i % 2 == 0) printf("+ "); else printf("* "); } printf("\n"); What/how do you need to change in th following program? for (i=1; i<=5; i++) { for (j=1; j<=i; j++){ printf(“*”); } printf(“\n”);

89 Exercise Write a program using loop statements to produce the following output. Output * ** *** **** *****

90 Compute xy when y is integer
Suppose we don’t have pow(x,y) and y is integer, write a loop to compute xy printf(“Enter x, y :”); scanf(“%d %d”, &x, &y); res=1; for(i=1; i<=y; i++){ res = res * x; }

91 Exercise: sum Write a program to compute the following Enter n Enter n
total=0; for(i=1; i<=n; i++) total = total + 2 * i ; print total Enter n total=0; for(i=1; i<=n; i++) total = total + i ; print total

92 Exercise: sum Write a program to compute the following Enter x and m
total=0; sofarx=1; for(i=0; i<=m; i++) { total = total +sofarx; sofarx = sofarx * x; } print total Enter x and m total=0; for(i=0; i<=m; i++) total = total + pow(x, i); print total

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

94 Exercise: ex Write C program that reads the value of x and n from the keyboard and then approximately computes the value of ex using the following formula: Then compare your approximate result to the one returned by exp(x) in C library, and print out whether your approximation is higher or lower.

95 int i, n; double x, ex; double powx, fact; printf("Enter the value of x and n : "); scanf("%lf %d",&x, &n); /* Write a loop to compute e^x using the above formula */ ex=1.0; fact=1.0; powx=1.0; for(i=1; i<=n; i++){ powx = powx * x; fact = fact * i; ex = ex + powx / fact; } printf("Approx value of e^x is %lf when n=%d\n",ex, n);

96 Exercise: sin x Compute sin x using
printf(“Enter x n :”); scanf(“%lf %d”, &x, &n); total=0; powx=x; factx=1; for(i=0; i <= n; i++){ k= 2*n+1; if (i%2==0) total= total - powx/factx; else total= total + powx/factx; powx= powx * x * x; factx = factx * k * (k-1); } printf( “sin(%lf) is %lf\n”,x, total);

97 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); sum = 0; k=1; while (k<=5) { scanf(“%lf”,&x); if (x > 10.0) break; sum +=x; k++; } printf(“Sum = %f \n”,sum);

98 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); sum = 0; k=1; while (k<=5) { scanf(“%lf”,&x); if (x > 10.0){ k++; continue; } sum +=x; printf(“Sum = %f \n”,sum); sum = 0; k=1; while (k<=5) { scanf(“%lf”,&x); if (x > 10.0) continue; sum +=x; k++; } printf(“Sum = %f \n”,sum);

99 Example: what will be the output
int main() { int a, b, c; a=5; while(a > 2) { for (b = a ; b < 2 * a ; b++ ) { c = a + b; if (c < 8) continue; if (c > 11) break; printf( “a = %d b = %d c = %d \n”, a, b, c); } /* end of for-loop */ a--; } /* end of while loop */ } a = 5 b = 5 c = 10 a = 5 b = 6 c = 11 a = 4 b = 4 c = 8 a = 4 b = 5 c = 9 a = 4 b = 6 c = 10 a = 4 b = 7 c = 11 a = 3 b = 5 c = 8

100 Example: break and continue
int ctr = 0; while( ctr < 6 ) { if( ctr < 3 ) ctr += 2; printf(“%d\n”, ctr); continue; } else printf(“%d\n”, ++ctr); break; printf(“Bottom of loop\n”); What is printed? 2 4 5 Why is "bottom of loop" skipped? Prints 2 4 5 Does NOT print “Bottom of loop”. That code is unreachable!

101 For vs. while loop : Convert the following for loop to while loop
for( i=5; i<10; i++) { printf(“AAA %d \n”, i); if (i % 2==0) continue; pritntf(“BBB %d \n”, i); } i=5; while(i<10) { printf(“AAA %d \n”, i); if (i % 2==0) { i++; continue; } pritntf(“BBB %d \n”, i);

102 Example: A man walks Suppose a man (say, A) stands at (0, 0) and waits for user to give him the direction and distance to go. User may enter N E W S for north, east, west, south, and any value for distance. When user enters 0 as direction, stop and print out the location where the man stopped N E S W

103 float x=0, y=0; char direction; float distance; while (1) {
printf("Please input the direction as N,S,E,W (0 to exit): "); scanf("%c", &direction); fflush(stdin); if (direction=='0'){ /*stop input, get out of the loop */ break; } if (direction!='N' && direction!='S' && direction!='E' && direction!='W') { printf("Invalid direction, re-enter \n"); continue; printf("Please input the mile in %c direction: ", direction); scanf ("%f", &distance); fflush(stdin); if (direction == 'N'){ /*in north, compute the y*/ y = y + distance; } else if (direction == 'E'){ /*in east, compute the x*/ x = x + distance; } else if (direction == 'W'){ /*in west, compute the x*/ x= x - distance; } else if (direction == 'S'){ /*in south, compute the y*/ y = y- distance; printf("\nCurrent position of A: (%4.2f, %4.2f)\n", x, y); /* output A's location */


Download ppt "Engineering Problem Solving with C"

Similar presentations


Ads by Google