lecture05-controlstmts2

Lecture05-controlstm - Announcements For today Finish control statements(Chapters 5 and 6 For next week Types(Chapter 7 Arrays(Chapter 8 1 EE312

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Announcements For today: Finish control statements (Chapters 5 and 6) For next week Types (Chapter 7) Arrays (Chapter 8) 1 EE312: SOFTWARE DESIGN AND IMPLEMENTATION I LECTURE 6 (CONT'D): CONTROL STATEMENTS Spring 2012 Professor Suzanne Barber [email protected] ACES 5.440 Office Hours: MW 11 am Noon, or by appointment Conditional Constructs Algorithm level if (shampoo bottle is empty) go out and buy some more else continue with washing hair endif Code level int i = 3, j = 4, k = 8, flag; . . . if (i + j < k - 1) flag = 1; else flag = 0; 3 condition T F If Statements The if statement has two forms: if ( expression ) statement if ( expression ) statement else statement If the value of the expression is nonzero, the first statement is executed; if the value is zero, the else statement (if present) is executed. If statements can be nested. condiJon T F Warning: Don t confuse = (assignment) with == (equality): if (i = 0) ... /* assigns i the value 0 */ if (i == 0) ... /* tests whether i is equal to 0 */ 4 If Statements Examples int i, j, max; /* assume they get values */ Simple if switch if (i > j) max = i; i> j 2 way decision if (i > j) max = i; else max = j; T max = i i>j T max = i F max = j F 5 If Statements Examples 3 way decision if (i < 0) prinV("Less than zero"); else if (i == 0) prinV("Equal to zero"); else prinV("Greater than zero"); i<0? How many cases ? if (i > j) if (i > k) max = i; else max = k; else if (j > k) max = j; else max = k - 1; T F i==0 ? F i > j >0 T F T F T <0 T ==0 i > k j > k F max=i max=k max=j max=k-1 6 Blocks A block (aka compound statement) has the form { statements } A block is used when C requires a single statement, but we want to include more than one statement blocks are not followed by a semicolon. Example: if (i < j) { /* swap the values */ temp = i; i = j; j = temp; } 7 The Dangling else Problem Warning: Watch out for the dangling else problem: if (y != 0) To which if does if (x != 0) result = x / y; else that else belong? prinV("Error: y is equal to 0\n"); Use the block to fix it: if (y != 0) { if (x != 0) result = x / y; } else prinV("Error: y is equal to 0\n"); 8 CondiJonal Operator These are unnecessary and will be avoided Like an if statement (embedded in an assignment) that produces a value from 2 choices. CondiJonal operators have the form n expr1 ? expr2 : expr3 n if expr1 (evaluated first) is true (non-zero), then expr2 is evaluated. Its value is the value of the enJre expression. If expr1 is false, then the value of expr3 is the value of the expression. SemanJcally equivalent to: Examples: n n n n n int i, j, k; i = 1; j = 2; k = i > j ? i : j; /* k is now 2 */ k = (i >= 0 ? i : 0) + j; /* k is now 3 */ if (expr1) expr2; else expr3; 9 switch Statements Allows a mulJway branch to one of several acJons, depending on the value of an expression Only integers and characters may be tested in a switch statement (expression must be one of those) The switch statement has the form switch ( expression ) { case constant-expression : statements ... case constant-expression : statements default : statements } Example: int grade; /* assume grade gets a value */ switch (grade) { case 4: prinV("Excellent"); break; case 3: prinV("Good"); break; case 2: prinV("Average"); break; case 1: prinV("Poor"); break; case 0: prinV("Failing"); break; default: prinV("Illegal grade"); } 10 The break statement is used to break out of the switch construct switch Statements (ConJnued) Each occurrence of the word case must be followed by a single constant expression; several case prefixes may be combined: switch (grade) { case 4: case 3: case 2: case 1: prinV("Passing"); break; case 0: prinV("Failing"); break; default: prinV("Illegal grade"); } Normally, the last statement in each case is break, but this is not required. Forgelng to include break is a common error: switch (grade) { case 4: case 3: case 2: case 1: prinV("Passing"); break; case 0: prinV("Failing"); break; default: prinV("Illegal grade"); break; The default clause is not required } If the value of the switch expression does not match any of the case labels, control passes to the next statement aEer the switch block 11 switch Flowchart (with breaks) selector value? Mutually exclusive cases case1 case2 case3 case4 . . . (default case) 12 switch Flowchart (without breaks) selector value? case1 case2 case3 case4 . . . (default case) 13 Area codes for TX major ciJes int areaCode; prinV ( input your 3 digit area code: ); scanf ( %d , &areaCode); switch (areaCode) { case 512: prinV( AusJn"); break; case 281: case 713: case 409: prinV( Houston"); break; case 210: prinV( San Antonio"); break; case 214: case 972: prinV( Dallas"); break; default: prinV("Area code not recognized"); } 14 Loops -- two basic pauerns Count-controlled loop: Event-controlled loop: 15 Loops -- Count controlled Loop Count-controlled loop: Number of iteraJons is determined before the loop starts Counts each iteraJon using a counter variable Stop when the desired number of iteraJons has been performed: for (i = 1; i < 100; i++ ) {prinV ( the value of i is: %d ,i }; 16 Loops -- Event Controlled Loop Event-controlled loop: Before each iteraJon, check whether some event has occurred ConJnue unJl that event occurs n Number of iteraJons not known beforehand The event signal is in the condiJon; may change during an iteraJon. Boolean variable owen used to flag the signal: while (condiJon) /* loop while the condiJon is true */ { /* do other stuff */ } 17 while Statement while statement has the form while ( condiJon ) statement The body is executed repeatedly as long as the condiJon is true (has a nonzero value) condiJon is tested before each execuJon of the body F condiJon T 18 while Statement Example: i = 10; /* count down from 10 */ while (i > 0) { prinV ("T minus %d and counJng\n", i); i--; } condiJon T F Using a nonzero constant as the controlling condiJon creates an infinite loop: while (1) { ... } 19 Summing a Series of Numbers I want to sum a series of integer values entered by the user. I don t know how many. How do I do that? To begin, represent the program as a closed, black-box system. IdenJfy the inputs and outputs before you begin to describe and outline (plan) the steps inside Inputs Series of numbers Sen$nel* Program Outputs Sum 20 High Level Algorithm start IniJalize sum to 0 Input a value 1. IniJalize sum to 0 2. Repeat the following unJl the senJnel is read: a) Input a value b) Add it to the sum 3. Output the sum Y Is it the SenJnel? Output the Total sum N Add the value into The running sum stop 21 Summing a Series of Numbers /* sum up a series of integers entered by the user */ #include <stdio.h> int main(void) { int n, sum = 0; prinV("This program sums a series of numbers.\n"); prinH("Enter numbers (-999 to terminate): "); scanf("%d", &n); while (n != -999) { sum = sum + n; prinH("Enter a number (-999 to terminate): "); scanf("%d", &n); } What could go wrong? prinV("The sum is: %d\n", sum); return 0; } 22 Input senJnel controlled loop 23 int input; const int SENTINEL = -999; scanf ("%d", &input); /* get first input */ while(input != SENTINEL) { /* do repeated computaJons */ . . . scanf ("%d", &input); /* get next input */ } /* conJnue with post loop computaJons */ 23 For loop 24 The for statement has the form for ( expression1 ; expression2 ; expression3 ) statement The following code has the equivalent semanJcs of the above for statement: expression1; while (expression2) { statement expression3; } 24 For loop 25 For example for (i = 10; i > 0; i-- ) prinV("T minus %d and counJng\n", i); Any or all of the three expressions may be omiued Omilng the middle expression creates an infinite loop. Used for counter controlled loops 25 for Loop SemanJcs expr1 IniJalize counter variable expr2 check the condiJon T Perform the statement(s) in the loop body loop exit F expr3 Adjust the counter variable 26 for Loop examples /* print out the even numbers from 2 to 100 */ int i; for (i = 2; i<=100; i = i + 2) { prinV ( i is = %d\n ,i); } /* print out the squares and sum them all up */ int i, sum=0; for (i = 1; i<=100; i++) { prinV ("i squared is = %d\n", i * i); sum = sum + i * i; } prinV ("sum of squares is = %d\n",sum); 27 for Loop SemanJcs for (i = 1; i<=100; i++) { /* loop body in here */ } i++ Adjust the counter variable IniJalize counter variable i = 1; i <= 100; check the condiJon T Perform the statement(s) in the loop body F loop exit What if we need the body of this loop to contain another loop inside of it ? 28 Nested Loops What is the output of the following code? Can you trace its execuJon? Outer loop int i, num; for (i = 1; i <= 5; i++){ for (num = 0; num < i; num++){ prinV ( %d , num * 2 + 1); } prinV ( \n ); } Inner loop 29 Tracing the Code Outer loop Inner loop Values output i num 0,1 0,1, 2 0,1, 2, 3 0,1, 2, 3, 4 0,1, 2, 3, 4, 5 1 2 3 4 5 num * 2 + 1 1 1 3 1 3 5 1 3 5 7 1 3 5 7 9 30 What it does Terminal Window Options 1 1 3 1 3 5 1 3 5 7 1 3 5 7 9 - x 31 The break; Statement Used to prematurely break out of a loop (or jump out of a switch block) false condition? true Statement(s) break ; Statement(s) 32 break; Statement Example What does this do? for( ; ; ) { prinV( Enter a number (enter 0 to stop): ); scanf( %d , &n); if (n == 0) break; prinV( %d cubed is %d\n , n, n*n*n); } Missing the 1st statement variable needs to be declared before the for statement Missing the 3rd statement variable must be changed in the loop body Missing the 2nd statement no condiJon for "exiJng" exists 33 Another example What does this do? for(d = 2; d<n; d++) { if(n % d == 0) break; } if(d < n) prinV( %d is divisible by %d\n , n, d); else prinV( %d is prime\n ); 34 The continue; Statement used as a short cut to the bouom of the loop or other block (skip the rest of body for that iteraJon) false condition? true Statement(s) continue ; Statement(s) 35 continue; Statement Example What does this do? n = 0; sum = 0; while (n < 10) { scanf( %d , &i); if (i == 0) conJnue; sum = sum + i; n++; } How might we rewrite it to be clearer? n = 0; sum = 0; while (n < 10) { scanf( %d , &i); if(i != 0){ sum = sum + i; n++; } } 36 do-while Statement The do-while statement has the form do statement while ( expression ) ; The do statement works like the while statement, except that the expression is evaluated awer each execuJon of the loop. And the loop body is always done at least once. 37 do-while Statement Example: Countdown from 10 i = 10; do { prinV("T minus %d and counJng\n", i); i--; } while (i > 0); This statement can be done with a while loop Generally avoid using 38 Comma Operator The for statement normally has three expressions. The comma operator allows us to have more than three: for (sum = 0, i = 1; i <= N; i++) sum = sum + i; In general, a comma expression has the form expr1 , expr2 The comma operator is handy whenever C requires a single expression, but we d like to have two or more expressions. In pracJce, it appears primarily in for statements and macros. 39 Null Statement The null statement is just a semicolon: i = 0; ; j = 1; The null statement is primarily good for one thing: wriJng loops whose bodies are empty. For example, the statement for (div = 2; div < n; div++) if (n % div == 0) break; Could be rewriuen as a loop with an empty body: for (div = 2; div < n && n % div != 0; div++); /* why? */ Accidentally pulng a semicolon awer the parentheses in an if, while, or for will be detected by the compiler as a null statement. if (i < 0); /*logic error */ prinV ("Error: i is less than zero\n"); Pulng in an extra semicolon creates a common logic error 40 How about this nested loop ? int i, j, k; for (i = 1; i<=10; i++) { for (j = 1; j<=10; j++) { for (k = 1; k<=10; k++) { prinV ( the value is: %d\n , i*j*k); } } } How many Jmes is the prinV statement executed? What does the output look like? 41 Pop Quiz Design a program that prompts the user to enter 5 digit integers. The program should recognize when the user enters one of the following numbers. Your favorite 5 digit number Your favorite zip code, and the Unique Number for your section of EE312. The program can print anything you wish in response to the favorite 5 digit number and favorite zip code entries. The program should print "Hoorah!" when the user enters the correct Unique Number for your section of EE312. The user is not allowed to enter more than 10 numbers. Provide your design in pseudocode or a flowchart. Make sure that your choice of control statement(s) is clear. 42 ...
View Full Document

This note was uploaded on 02/03/2012 for the course E E 312 taught by Professor Krasner during the Spring '09 term at University of Texas at Austin.

Ask a homework question - tutors are online