500 likes | 628 Views
Additional Control Structures. Chapter 9 Topics. Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements To be able to choose the most appropriate looping statement for a given problem. Switch Statement.
E N D
Chapter 9 Topics • Switch Statement for Multi-way Branching • Do-While Statement for Looping • For Statement for Looping • Using break and continue Statements • To be able to choose the most appropriate looping statement for a given problem
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression) { case Constant1 : Statement 1; // optional case Constant2 : Statement 2; // optional . . . default : // optional Statement n; // optional }
float weightInPounds = 165.8 ; char weightUnit ; . . .// user enters letter for desired weightUnit switch ( weightUnit ) { case ‘P’ : case ‘p’ : cout << weightInPounds << “ pounds “ << endl ; break ; case ‘O’ : case ‘o’ : cout << 16.0 * weightInPounds << “ ounces “ << endl ; break ; case ‘K’ : case ‘k’ : cout << weightInPounds / 2.2 << “ kilos “ << endl ; break ; case ‘G’ : case ‘g’ : cout << 454.0 * weightInPounds << “ grams “ << endl ; break ; default : cout << “That unit is not handled! “ << endl ; break ; }
Switch Statement • the value of IntegralExpression(of char, short, int, long or enum type ) determines which branch is executed • case labels are constant ( possibly named ) integral expressions. Several case labels can precede a same statement
Switch(letter) {case ‘X’ : Statement1; break; case ‘L’ : case ‘M’: Statement2; break; case ‘S’ : Statement3; break; default : Statement4; } Statement5;
In this example, letter is the switch expression. • The statement means • If letter is ‘X’,execute Statement1 and continue with Statement5. • If letter is ‘L’ or ‘M’, execute Statement2 and continue with Statement5. • If letter is ‘S’, execute Statement3 and continue with Statement5. • If letter is none of the characters mentioned, execute Statement4 and continue with Statement5. • The Break statement causes an immediate exit from the Switch statement.
Control in Switch Statement • control branches to the statement following the case label that matches the value of IntegralExpression. Control proceeds through all remaining statements, including the default, unless redirected with break • if no case label matches the value of IntegralExpression, control branches to the default label(if present)——otherwise control passes to the statement following the entire switch statement • forgetting to use break can cause logical errors
Switch (grade) // Wrong Version { case ‘A’ : case ‘B’ : cout <<“Good Work”; case ‘C’ : cout <<“Average Work”; case ‘D’ : case ‘F’: cout <<“Poor Work”; numberInTrouble++; default : cout << grade <<“is not a valid letter grade.” }
If grade is ‘A’, the resulting output is this: • Good WorkAverage WorkPoor WorkA is not a valid letter grade. • Remember: • After a branch is taken to a specific case label, control proceeds sequentially until either a Break statement or the end of the Switch statement occurs.
Do-While Statement Is a looping control structure in which the loop condition is tested at the end(bottom) of the loop. SYNTAX do { Statement } while (Expression) ; Loop body statement can be a single statement or a block. Note that the Do-While statement ends with a semicolon.
Function Using Do-While void GetYesOrNo ( /* out */ char& response ) // Inputs a character from the user // Postcondition: response has been input // && response == ‘y’ or ‘n’ { do { cin >> response ; // skips leading whilespace if ( ( response != ‘y’ ) && ( response != ‘n’ ) ) cout << “Please type y or n : ”; } while ( ( response != ‘y’ ) && ( response != ‘n’ ) ) ; }
POST-TEST loop (exit-condition) The looping condition is tested after executing the loop body. Loop body is always executed at least once. PRE-TEST loop (entry-condition) The looping condition is tested before executing the loop body. Loop body may not be executed at all. Do-While Loop vs. While Loop
While Solution sum=0; counter=1; while(counter<=n) { sum=sum+counter; counter++; } Do-While Solution sum=0; counter=1; do { sum=sum+counter; counter++; } while(counter<=n); Example
Example (Cont.) • If n is a positive number, both of these versions are equivalent. • But if n is 0 or negative, the two loops give different results. • In the While version, the final value of sum is 0 because the loop body is never entered. • In the Do-While version, the final value of sum is 1 because the body executes once and then the loop test is made.
Do-While Loop DO When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the do-while statement. Statement WHILE Expression TRUE FALSE
A Count-Controlled Loop SYNTAX for ( initialization ; test expression; update ) { 0 or more statements to repeat }
The for loop contains • an initialization • an expression to test for continuing • an update to execute after each iteration of the body
Example of Repetition int num; for ( num = 1 ; num <= 3; num++) { cout << num << “Potato” << endl; }
Example of Repetition ? num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
Example of Repetition 1 num int num; for (num = 1 ;num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
Example of Repetition 1 num true int num; for ( num = 1 ; num <= 3;num++) cout << num << “Potato” << endl; OUTPUT
1Potato Example of Repetition 1 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato Example of Repetition 2 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato Example of Repetition 2 num true int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato Example of Repetition 2 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato Example of Repetition 3 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato Example of Repetition 3 num true int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato 3Potato Example of Repetition 3 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato 3Potato Example of Repetition 4 num int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
1Potato 2Potato 3Potato Example of Repetition 4 num false int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; OUTPUT
Example of Repetition 4 num false int num; for ( num = 1 ; num <= 3; num++) cout << num << “Potato” << endl; • When the loop control condition is evaluated and has value false, the loop is said to be “satisfied” and control passes to the statement following the For statement.
The output was: 1Potato 2Potato 3Potato
Count-controlled Loop int count ; for ( count = 4 ; count > 0 ; count-- ) { cout << count << endl; } cout << “Done” << endl; OUTPUT: 4 3 2 1 Done
What is output? int count; for (count = 0 ; count < 10;count++) { cout << “*”; }
OUTPUT ********** NOTE: the 10 asterisks are all on one line. Why?
What output from this loop? int count; for (count = 0; count < 10; count++) ; { cout << “*”; }
OUTPUT • no output from the for loop! Why? • the ; right after the ( ) means that the body statement is a null statement • in general, the Body of the for loop is whatever statement immediately follows the ( ) • that statement can be a single statement, a block, or a null statement • actually, the code outputs one * after the loop completes its counting to 10
Several Statements in Body Block const int MONTHS = 12 ; int count ; float bill ; float sum = 0.0 ; for (count = 1; count <= MONTHS; count++ ) { cout << “Enter bill: ” ; cin >> bill ; sum = sum + bill ; } cout << “Your total bill is : ” << sum << endl ;
Nested For Loops for( lastNum=1; lastNum<=7; lastNum++) { for(numToPrint=1; numToPrint<=lastNum; numToPrint++) cout << numToPrint; cout << endl; }
Output • It prints the following triangle of numbers. • 1 • 12 • 123 • 1234 • 12345 • 123456 • 1234567
Break Statement • break statement can be used with Switch or any of the 3 looping structures • it causes an immediate exit from the Switch, While, Do-While, or For statement in which it appears • if the break is inside nested structures, control exits only the innermost structure containing it
Continue Statement • is valid only within loops • terminates the current loop iteration, but not the entire loop • in a For or While, continue causes the rest of the body statement to be skipped--in a For statement, the update is done • in a Do-While, the exit condition is tested, and if true, the next loop iteration is begun
Be sure to note the difference between continue and break. • The Continue statement means “Abandon the current iteration of the loop, and go on to the next iteration.” • The Break statement means “Exit the entire loop immediately.”
Guidelines for Choosing a Looping Statement • If the loop is a simple count-controlled loop, the For statement is natural. • If the loop is an event-controlled loop whose body should execute at least once, a Do-While statement is appropriate. • If the loop is an event-controlled loop and nothing is known about the first execution, use a While statement. • When in doubt, use a While statement. • Using Break statement and Continue statement only after careful consideration.
Imagine using . . . • a character, a length, and a width to draw a box, for example, • using the values ‘&’, 4, and 6 would display &&&&&& &&&&&& &&&&&& &&&&&&
Write prototype for void function called DrawBox ( ) with 3 parameters. The first is type char, the other 2 are type int. void DrawBox( char, int , int ); NOTE: Some C++ books include identifiers in prototypes. Any valid C++ identifiers, as long as each is different, can be used. void DrawBox( char letter, int num1, int num2);
void DrawBox(char what, int down, int across) // 3 function parameters { int row, col; // 2 local variables for ( row = 0; row < down; row++ ) { for (col = 0; col < across; col++ ) { cout << what; } cout << endl; } return; }
THE DRIVER PROGRAM #include <iostream> void DrawBox (char, int, int); // prototype int main ( ) { char letter = ‘&’; DrawBox(letter, 4, 2*3); // arguments DrawBox(‘V’, 9, 3); // appear in call return 0; }
Write a function using prototype void DisplayTable ( int ) ; // prototype The function displays a specified multiplication table. For example, the call DisplayTable(6) displays this table: 1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 . . . 12 x 6 = 72