1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.

Slides:



Advertisements
Similar presentations
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
Advertisements

Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
1 Chapter 7 Additional Control Structures. 2 Knowledge Goals Understand the role of the switch statement Understand the purpose of the break statement.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Multi-alternative Selection Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Introduction to Java and Software Design Dale Weems Headington Chapter 10 Additional Control Structures and Exceptions Slides by Sylvia Sorkin, The Community.
Chapter 4 Program Control Statements
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement(s); // optional.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 05 (Part III) Control Statements: Part II.
Control Structures Repetition or Iteration or Looping Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Control Structures RepetitionorIterationorLooping Part I.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Computer Programming -1-
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 2.2 Control Structures (Iteration)
Control Structures - Repetition
Additional Control Structures
Chapter 7 Additional Control Structures
Chapter 2.2 Control Structures (Iteration)
Alternate Version of STARTING OUT WITH C++ 4th Edition
2.6 The if/else Selection Structure
Control Statements Paritosh Srivastava.
Presentation transcript:

1 Additional Control Structures

2 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

3 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 }

4 float weightInPounds = ; 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 << * weightInPounds << “ grams “ << endl ; break ; default : cout << “That unit is not handled! “ << endl ; break ; }

5 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

6 Switch(letter) {case ‘X’ : Statement1; break; case ‘L’ : case ‘M’: Statement2; break; case ‘S’ : Statement3; break; default : Statement4; } Statement5;

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

8 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

9 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.” }

10  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.

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

12 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’ ) ) ; } Function Using Do-While

13 Do-While Loop vs. While Loop  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.

14 Example  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);

15  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. Example (Cont.)

16 Do-While Loop 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 Expression DO WHILE FALSE TRUE

17 A Count-Controlled Loop SYNTAX for ( initialization ; test expression ; update ) { 0 or more statements to repeat }

18 The for loop contains  an initialization  an expression to test for continuing  an update to execute after each iteration of the body

19 Example of Repetition int num; for ( num = 1 ; num <= 3 ; num++ ) { cout << num << “Potato” << endl; }

20 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT ?

21 Example of Repetition num OUTPUT 1 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;

22 Example of Repetition num OUTPUT 1 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; true

23 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT 1 1Potato

24 Example of Repetition num OUTPUT 2 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; 1Potato

25 Example of Repetition num OUTPUT 2 true 1Potato int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;

26 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT 2 1Potato 2Potato

27 Example of Repetition num OUTPUT 3 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; 1Potato 2Potato

28 Example of Repetition num OUTPUT 3 true 1Potato 2Potato int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;

29 Example of Repetition num int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; OUTPUT 3 1Potato 2Potato 3Potato

30 Example of Repetition num OUTPUT 4 int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl; 1Potato 2Potato 3Potato

31 Example of Repetition num OUTPUT 4 false 1Potato 2Potato 3Potato int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;

32 Example of Repetition num  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. 4 false int num; for ( num = 1 ; num <= 3 ; num++ ) cout << num << “Potato” << endl;

33 The output was: 1Potato 2Potato 3Potato

34 int count ; for ( count = 4 ; count > 0 ; count -- ) { cout << count << endl; } cout << “Done” << endl; Count-controlled Loop OUTPUT: Done

35 What is output? int count; for ( count = 0 ; count < 10 ; count++ ) { cout << “  ”  ; }

36 OUTPUT ********** NOTE: the 10 asterisks are all on one line. Why?

37 What output from this loop? int count; for (count = 0; count < 10; count++) ; { cout << “  ”  ; }

38  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 OUTPUT

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

40 Nested For Loops For( lastNum=1; lastNum<=7; lastNum++) { for(numToPrint=1; numToPrint<=lastNum; numToPrint++) cout << numToPrint; cout << endl; }

41 Output  It prints the following triangle of numbers

42 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

43 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

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

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

46 Imagine using...  a character, a length, and a width to draw a box, for example,  using the values ‘&’, 4, and 6 would display &&&&&&

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

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

49 #include 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; } THE DRIVER PROGRAM

50 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 = x 6 = 72