1 chapter 9 additional control structures dale/weems/headington

59
1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Upload: merilyn-skinner

Post on 31-Dec-2015

249 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

1

Chapter 9

Additional Control Structures

Dale/Weems/Headington

Page 2: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

2

Chapter 9 Topics

Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using break and continue Statements

Page 3: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

3

switch Statement

Page 4: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

4

Switch Statement

Is a selection control structure for multi-way branching.

SYNTAXswitch ( IntegralExpression )

{

case Constant1 :

Statement(s); // optional

case Constant2 :

Statement(s); // optional . . .

default : // optional

Statement(s); // optional

}

Page 5: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

5

float weightInPounds = 165.8 ;char weightUnit ;

. . . // user enters letter for desired weightUnitswitch ( 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 ;

}

Page 6: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Case LabelCase Label

an integral expression operands must be literal or named constants value is compared to switch expression

case 'X' :

Page 7: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

switch Observationsswitch Observations

break is required after statement(s)(if omitted all following statements execute)

{ } not required around multiple statements

default clause is a GPP

break after last statement is optional– See switch.cpp

Page 8: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

8

do-while Statement

Page 9: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

9

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 ( Expression ) ;

Loop body statement can be a single statement or a block.

Page 10: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

10

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’ ) ) ;}

Function Using Do-While

Page 11: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

11

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.

Page 12: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

12

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

Page 13: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

while v. do-while Sentinel while v. do-while Sentinel

// skip to period

datafile >> inputChar;

while (inputChar != '.')

datafile >> inputChar;

// skip to period7

do

datafile >> inputChar;

while (inputChar != '.')

No priming readneeded in this case

(Still needed in many cases)

Page 14: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

while v. do-while Sentinel while v. do-while Sentinel

cout << "Enter your age: ";

cin >> age;

while (age <= 0)

{

cout << "Your age must be "

<< "positive." <<endl;

cout << "Enter your age: ";

cin >> age;

}

Requires 2 tests ==>

do

{

cout << "Enter your age: ";

cin >> age;

if (age <=0)

{

cout << "Your age must"

<< " be positive."

<< endl;

}

} while (age <= 0)

Page 15: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

while v. do-while CCL while v. do-while CCL

sum = 0;

counter = 1;

while (counter <= n)

{

sum = sum + counter;

counter++;

}

Pretest Loop

sum = 0;

counter = 1;

do

{

sum = sum + counter;

counter++;

} while (counter <= n)

// Note Sum=1 if n=0

Posttest Loop Loop always executes at

least once

Page 16: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

16

for Statement

Page 17: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

17

A Count-Controlled Loop

SYNTAX

for ( initialization ; test expression ; update )

{

0 or more statements to repeat

}

Page 18: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

18

The for loop contains

an initialization

an expression to test for continuing

an update to execute after each iteration of the body

Page 19: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

19

Example of Repetition

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

{

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

}

Page 20: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

20

Example of Repetition num

int num;

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

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

OUTPUT

?

Page 21: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

21

Example of Repetition num

OUTPUT

1

int num;

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

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

Page 22: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

22

Example of Repetition num

OUTPUT

1

int num;

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

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

true

Page 23: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

23

Example of Repetition num

int num;

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

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

OUTPUT

1

1Potato

Page 24: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

24

Example of Repetition num

OUTPUT

2

int num;

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

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

1Potato

Page 25: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

25

Example of Repetition num

OUTPUT

2

true

1Potato

int num;

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

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

Page 26: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

26

Example of Repetition num

int num;

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

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

OUTPUT

2

1Potato

2Potato

Page 27: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

27

Example of Repetition num

OUTPUT

3

int num;

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

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

1Potato

2Potato

Page 28: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

28

Example of Repetition num

OUTPUT

3

true

1Potato

2Potato

int num;

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

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

Page 29: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

29

Example of Repetition num

int num;

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

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

OUTPUT

3

1Potato

2Potato

3Potato

Page 30: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

30

Example of Repetition num

OUTPUT

4

int num;

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

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

1Potato

2Potato

3Potato

Page 31: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

31

Example of Repetition num

OUTPUT

4

false

1Potato

2Potato

3Potato

int num;

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

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

Page 32: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

32

Example of Repetition num

When the loop control condition is evaluated and has value false, theloop is said to be “satisfied” and control passes to the statementfollowing the For statement.

4

falseint num;

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

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

Page 33: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

33

The output was:

1Potato2Potato3Potato

Page 34: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

34

for (int count = 4 ; count > 0 ; count-- )

{

cout << count << endl;

}

cout << “Done” << endl;

Count-controlled Loop

OUTPUT: 4321Done

Page 35: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

35

What is output?

for ( int count = 0 ; count < 10 ; count++ )

{

cout << “”;

}

Page 36: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

36

OUTPUT

**********

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

Page 37: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Count Control Loop Example

Display integers and their squares from 1 through 10.

for (int i = 1; i <= 10; i++) cout << i << " " << i * i << endl;

Page 38: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

For example

Display even integers and their squares from 1 through 10.

for (int i = 2; i <= 10; i = i+2) cout << i << " " << i * i << endl;

Page 39: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

For example

Display integers and their squares from 10 down to 1.

for (int i = 10; i >= 1; i--) cout << i << “ “ << i * i << endl;

Page 40: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

For example

Find square roots of 1.1, 1.2, 1.3, ..., 2.0

for (double x = 1.1; x <= 2.0; x =x+0.1)

cout << x << " " << sqrt(x) << endl;

Page 41: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Compute and return n! = 1 2 3 ... n.

int product = 1;

for (int i = 2; i <= n; i++)

product = product * i;

For example

Page 42: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

42

What output from this loop?

for (int count = 0; count < 10; count++) ;

{

cout << “”;

}

Page 43: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

43

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

Page 44: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Display all divisors of each integer from 1

through 50

for (int num = 1; num <= 50; num++)

{

cout << num << " has divisors:\n\t'';

for (int div = 1; div <= num/2; div++)

if (num % div == 0)

cout << div << ", '';

cout << num << endl;

} // See divisors.cpp

Page 45: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Table of 2nTable of 2n

const int tableSize = 20;

long valueSquared = 1;

cout << "n" << " " << "2**n" << endl;

for (int n = 0; n <= tableSize; ++n) {

cout << n << " " << valueSquared << endl;valueSquared = valueSquared * 2;

}

Page 46: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

46

Several Statements in Body Block

const int MONTHS = 12 ;

float bill ;

float sum = 0.0 ;

for (int count = 1; count <= MONTHS; count++ )

{

cout << “Enter bill: “ ;

cin >> bill ;

sum = sum + bill ;

}

cout << “Your total bill is : “ << sum << endl ;

Page 47: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Converting while to forConverting while to for

Any while loop may be written as a for Note InitStmt and PostExpr are optional

while (inputVal != 999)

cin >> inputVal;

for ( ; inputVal != 999; )

cin >> inputVal;

Page 48: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Eliminating WhileExpressionEliminating WhileExpression

The while condition is also optional If omitted the value defaults to true

for ( ; ; )

cout << “Hi” << endl;

while (1)

cout << “Hi” << endl;

Page 49: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

For FlexibilityFor Flexibility

cin >> ch;

while (ch != ‘.’)

cin >> ch;

for (cin >> ch; ch != ‘.’; cin >> ch)

;

Warning! Keep it simple. The trickier the code, the harder to follow.

Page 50: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Changing the values of any variables involved in the loop condition inside the body of the loop may change the number of repetitions & may result in an infinite loop

for (i = 1; i <= 10; i++)

{

cout << i << endl;

i++;

}

Monkeying with LCVs: PPPMonkeying with LCVs: PPP

Page 51: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

51

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

Page 52: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Forever LoopForever Loop

loopCount = 1;while (1) // OR for ( ; ; ){ cin >> num1; if (!cin || num1 >= 100) break; cin >> num2; if (!cin || num2 >= 100) break; cout << sqrt(float(num1 + num2)) << endl; loopCount++; if (loopCount > 10) break;}

Page 53: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

Use break As a Last ResortUse break As a Last Resort

It can become a crutch Think carefully about loop design for loop on right is better

i = 1;

while (1) for (i = 1; i <= 5; i++)

{ cout << i;

cout << i;

if (i == 5)

break;

i++;

}

Page 54: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

54

Continue Statement

continue 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

Page 55: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

55

Imagine using . . .

a character, a length, and a width to draw a box, for example,

using the values ‘&’, 4, and 6 would display

&&&&&&

&&&&&&

&&&&&&

&&&&&&

Page 56: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

56

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

Page 57: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

57

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;

}

Page 58: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

58

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

THE DRIVER PROGRAM

Page 59: 1 Chapter 9 Additional Control Structures Dale/Weems/Headington

59

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