Docsity

Problem Solving and Structured Programming, Slides of Advanced Computer Programming

Partial preview of the text

Download Problem Solving and Structured Programming and more Slides Advanced Computer Programming in PDF only on Docsity!

Chapter 9

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

4

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

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 statement

Do-While Statement

Do-While is a looping control structure in which the loop condition is tested after each iteration of the loop

SYNTAX

do { Statement

} while ( Expression );

Loop body statement can be a single statement or a block

8

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 whitespace if ((response != „y‟) && (response != „n‟)) cout << “Please type y or n : “; } while ((response != „y‟) && (response != „n‟)); }

Example of Do-While

8

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 (^) 10

Statement

Expression

DO
WHILE
FALSE
TRUE

For Loop

SYNTAX

for ( initialization; test expression; update )

Zero or more statements to repeat

Example of For Loop

int num;

for (num = 1; num <= 3; num++)

{

cout << num << “Potato” << endl;

}

Example of Repetition

int num;

for (num = 1; num <= 3; num++) cout << num << “Potato” << endl;

14

num

OUTPUT

Example of Repetition

int num;

for(num = 1; num <= 3; num++)

cout << num << “Potato” << endl;

16

num

OUTPUT

true

Example of Repetition

int num;

for (num = 1; num <= 3; num++)

cout << num << “Potato” << endl;

17

num

OUTPUT

1Potato

Example of Repetition

int num;

for(num = 1; num <= 3; num++)

cout << num << “Potato” << endl;

19

num

OUTPUT

true

1Potato

Example of Repetition

int num;

for (num = 1; num <= 3; num++)

cout << num << “Potato” << endl;

20

num

OUTPUT

1Potato

2Potato