53
Chapter 4 Chapter 4 Program Control Program Control Statements Statements C Programming C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Embed Size (px)

Citation preview

Page 1: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Chapter 4Chapter 4Program Control Program Control

StatementsStatementsC ProgrammingC Programming

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Page 2: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

2

In this chapter we will learn about the statements In this chapter we will learn about the statements that control a program’s flow of execution. that control a program’s flow of execution.

There are three specific categories of program There are three specific categories of program control statements:control statements:

Selection -Selection - ifif and and switchswitch statements statements

Iteration - Iteration - forfor,, whilewhile,, andand do-whiledo-while statementsstatements

Jump - Jump - breakbreak, , continuecontinue,, returnreturn,, and and gotogoto statementsstatements

Page 3: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

3

The if StatementThe if StatementIts format is:Its format is: if( expression )if( expression ) statement;statement; elseelse statement;statement;

The The elseelse clause is clause is OPTIONALOPTIONAL. Both the . Both the ifif and and elseelse may contain may contain blocks of codeblocks of code as shown below. as shown below.

if( expression ) {if( expression ) { statement1;statement1; statement2;statement2; }} else {else { statement3;statement3; statement4;statement4; }}

Code block

Code block

Page 4: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

4

The if Statement The if Statement (continued)(continued)

At no time will the code in both the At no time will the code in both the ifif and and elseelse blocks be executed. blocks be executed.

The conditional expression of an The conditional expression of an ifif statement can be any type of valid statement can be any type of valid expression that produces a expression that produces a truetrue or or falsefalse result. For example:result. For example: int Good; if( Good ) . . .int Good; if( Good ) . . .

int Fun(); if( Fun() ) . . .int Fun(); if( Fun() ) . . .

if( 8 > 6 ) . . .if( 8 > 6 ) . . .

bool Old; if( Old ) . . .bool Old; if( Old ) . . .

Remember the Remember the elseelse clause is clause is OPTIONALOPTIONAL..

Page 5: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

5

The Conditional ExpressionThe Conditional Expression

Remember that a Remember that a value ofvalue of zerozero is is automatically converted to automatically converted to falsefalse, and all , and all non-non-zero valueszero values are converted to are converted to truetrue. .

Therefore, any expression that results in a Therefore, any expression that results in a zerozero or or non-zero non-zero value can be used to control value can be used to control an an ifif statement. statement.

The following program reads two integers from The following program reads two integers from the keyboard and divides the first value by the the keyboard and divides the first value by the second value displaying the quotient second value displaying the quotient (remember that division by zero is undefined (remember that division by zero is undefined and will cause your program to and will cause your program to BLOW-UPBLOW-UP).).

Page 6: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

6

The Conditional Expression The Conditional Expression (continued)(continued)

// Divide the first number by the second.// Divide the first number by the second.#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int a, b;int a, b;

cout << "Enter two numbers: ";cout << "Enter two numbers: "; cin >> a >> b;cin >> a >> b;

if( b ) if( b ) // make sure divisor is not zero// make sure divisor is not zero cout << a / b << '\n';cout << a / b << '\n'; elseelse cout << "Cannot divide by zero.\n";cout << "Cannot divide by zero.\n";

return 0;return 0;}}

Page 7: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

7

The Conditional Expression The Conditional Expression (continued)(continued)

You could have used the following code in You could have used the following code in the previous program:the previous program:

if( b != 0 )if( b != 0 ) cout << a / b << endl;cout << a / b << endl;

Using this code is redundant and potentially Using this code is redundant and potentially inefficient.inefficient.

Page 8: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

8

Nested ifsNested ifsA A nestednested ifif is an is an ifif statement that is the statement that is the target of another target of another ifif or or elseelse. They are very . They are very common.common.

C/C++ allows at least C/C++ allows at least 256256 levels of nesting. levels of nesting.

An An elseelse statement statement ALWAYSALWAYS refers to the refers to the nearest nearest ifif statement that is within the same statement that is within the same block of codeblock of code as the as the elseelse and and NOTNOT already already associated with an associated with an elseelse. .

This sounds complicated!This sounds complicated!

Page 9: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

9

Nested ifs Nested ifs (continued)(continued)

Consider the following:Consider the following:

if( i ) {if( i ) { if( j )if( j ) statement1;statement1; if( k )if( k ) statement2;statement2; // this if// this if elseelse statement3;statement3; // is associated with this else // is associated with this else }} elseelse statement4;statement4; // associated with if( i ) // associated with if( i )

Page 10: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

10

Nested ifs Nested ifs (continued)(continued)

What will the following code output What will the following code output assuming the code compiles correctly?assuming the code compiles correctly?int x = 3;int x = 3;

int y = 2;int y = 2;

if ( x > 2 ) {if ( x > 2 ) {

if ( y > 2 ) if ( y > 2 ) {{

int z = x + y;int z = x + y;

cout << "z is " << z << endl;cout << "z is " << z << endl;

}}

}}

elseelse

cout << “x is " << x << endl;cout << “x is " << x << endl;

Page 11: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

11

Nested ifs Nested ifs (continued)(continued)

What will the following code output What will the following code output assuming the code compiles correctly?assuming the code compiles correctly? int x = 2;int x = 2;int y = 3;int y = 3;

if ( x > 2 )if ( x > 2 ) if ( y > 2 ) {if ( y > 2 ) { int z = x + y;int z = x + y; cout << "z is " << z << endl;cout << "z is " << z << endl;

}}elseelse cout << “x is “ << x << endl;cout << “x is “ << x << endl;

Page 12: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

12

Nested ifs Nested ifs (continued)(continued)

Nested Nested ifif statements can become quite statements can become quite complex. If there are more than complex. If there are more than threethree alternatives and indentation is not alternatives and indentation is not consistent, it may be difficult for you to consistent, it may be difficult for you to determine the logical structure of the determine the logical structure of the ifif statement.statement.

In this case it is a common programming In this case it is a common programming practice anpractice anif-else-if ladderif-else-if ladder construct. construct.

Page 13: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

13

if-else-if ladderif-else-if ladder

Example:Example:

if( condition ) if( condition ) {{ // code statements if this condition is True// code statements if this condition is True

}}else if( condition ) else if( condition ) {{ // code statements if this condition is True// code statements if this condition is True

}}else if( condition ) else if( condition ) {{ // code statements if this condition is True// code statements if this condition is True

}}else else {{ // code statements if all conditions are False// code statements if all conditions are False

}}

Page 14: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

14

if-else-if ladder if-else-if ladder (continued)(continued)

As soon as a As soon as a truetrue condition occurs, the condition occurs, the associated statement(s) are executed, and associated statement(s) are executed, and the rest of the ladder is bypassed.the rest of the ladder is bypassed.

If none of the conditions are If none of the conditions are truetrue, the , the final final elseelse statement is executed (it acts as the statement is executed (it acts as the default condition).default condition).

If more than one condition is If more than one condition is truetrue, only the , only the task following the task following the first truefirst true condition condition executes. Therefore, the order of the executes. Therefore, the order of the conditions can affect the outcome.conditions can affect the outcome.

Page 15: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

15

if-else-if ladder if-else-if ladder (continued)(continued)

// Demonstrate an if-else-if ladder.// Demonstrate an if-else-if ladder.#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int x;int x;

for( x = 0; x < 6; x++ ) {for( x = 0; x < 6; x++ ) { if( x == 1 )if( x == 1 ) cout << "x is one\n";cout << "x is one\n"; else if( x == 2 )else if( x == 2 ) cout << "x is two\n";cout << "x is two\n"; else if( x == 3 )else if( x == 3 ) cout << "x is three\n";cout << "x is three\n"; else if( x == 4 )else if( x == 4 ) cout << "x is four\n";cout << "x is four\n"; elseelse cout << "x is not between 1 and 4\n";cout << "x is not between 1 and 4\n"; }}

return 0;return 0;}}

Page 16: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

16

if-else-if ladder if-else-if ladder (continued)(continued)

Output:Output:x is not between 1 and 4x is not between 1 and 4x is onex is onex is twox is twox is threex is threex is fourx is fourx is not between 1 and 4x is not between 1 and 4

Notice the default Notice the default elseelse is executed only if is executed only if nonenone of the preceding of the preceding ifif statements are statements are truetrue..

Page 17: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

17

Using Separate if StatementsUsing Separate if Statementschar MaritalStatus;char MaritalStatus;

if( MaritalStatus == ‘M’ )if( MaritalStatus == ‘M’ ) cout << “Married “;cout << “Married “;if( MaritalStatus == ‘S’ )if( MaritalStatus == ‘S’ ) cout << “Single “;cout << “Single “;if( MaritalStatus == ‘D’ )if( MaritalStatus == ‘D’ ) cout << “Divorced “;cout << “Divorced “;if( MaritalStatus == ‘W’ )if( MaritalStatus == ‘W’ ) cout << “Widowed “;cout << “Widowed “;if( MaritalStatus == ‘P’ )if( MaritalStatus == ‘P’ ) cout << “Separated”;cout << “Separated”;elseelse cout << “Unknown “;cout << “Unknown “;

Is this code OK?Is this code OK?

Page 18: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

18

Using Nested if StatementsUsing Nested if Statementschar MaritalStatus;char MaritalStatus;

if( MaritalStatus == ‘M’ )if( MaritalStatus == ‘M’ ) cout << “Married “;cout << “Married “;elseelse if( MaritalStatus == ‘S’ )if( MaritalStatus == ‘S’ ) cout << “Single “;cout << “Single “; else else if( MaritalStatus == ‘D’ )if( MaritalStatus == ‘D’ ) cout << “Divorced “;cout << “Divorced “; elseelse if( MaritalStatus == ‘W’ )if( MaritalStatus == ‘W’ ) cout << “Widowed “;cout << “Widowed “; elseelse if( MaritalStatus == ‘P’ )if( MaritalStatus == ‘P’ ) cout << “Separated”;cout << “Separated”; elseelse cout << “Unknown “;cout << “Unknown “;

Is this code OK?Is this code OK?

Page 19: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

19

Using an if-else-if ladderUsing an if-else-if ladderchar MaritalStatus;char MaritalStatus;

if( MaritalStatus == ‘M’ )if( MaritalStatus == ‘M’ ) cout << “Married “;cout << “Married “;else if( MaritalStatus == ‘S’ )else if( MaritalStatus == ‘S’ ) cout << “Single “;cout << “Single “;else if( MaritalStatus == ‘D’ )else if( MaritalStatus == ‘D’ ) cout << “Divorced “;cout << “Divorced “;else if( MaritalStatus == ‘W’ )else if( MaritalStatus == ‘W’ ) cout << “Widowed “;cout << “Widowed “;else if( MaritalStatus == ‘P’ )else if( MaritalStatus == ‘P’ ) cout << “Separated”;cout << “Separated”;elseelse cout << “Unknown “;cout << “Unknown “;

Is this code OK?Is this code OK?

Page 20: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

20

The for LoopThe for LoopThe general form is:The general form is:

for ( initialize; expression; increment ) for ( initialize; expression; increment ) statement;statement;

OROR for ( initialize; expression; increment ) {for ( initialize; expression; increment ) {

statement sequencestatement sequence }}

Where:Where: initializationinitialization - Executed when the loops first starts and is - Executed when the loops first starts and is

executed only once. This step typically executed only once. This step typically initializesinitializes the loop control variable. the loop control variable.

expressionexpression - Tested to see if the expression is - Tested to see if the expression is truetrue oror falsefalse. If. If truetrue the loop continues else it is terminated. the loop continues else it is terminated.

incrementincrement - This step usually increments or decrements - This step usually increments or decrements thethe loop control variable each time the loop loop control variable each time the loop repeats.repeats.

Page 21: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

21

The for Loop ExampleThe for Loop ExampleThis prgram displays the square roots of the This prgram displays the square roots of the numbers between numbers between 11 and and 9999..

#include <iostream>#include <iostream>#include <cmath>#include <cmath>using namespace std;using namespace std;

int main() {int main() { int num;int num; double sq_root;double sq_root; for( num = 1; num < 100; num++ ) {for( num = 1; num < 100; num++ ) { sq_root = sqrt( (double) num );sq_root = sqrt( (double) num ); cout << num << “ “ << sq_root << ‘\n’;cout << num << “ “ << sq_root << ‘\n’; }}

return 0;return 0;}}

Page 22: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

22

The for Loop ExampleThe for Loop ExampleOutput:Output:1 11 12 1.414212 1.414213 1.732053 1.732054 24 25 2.236075 2.236076 2.449496 2.449497 2.645757 2.645758 2.828438 2.828439 39 310 3.1622810 3.16228

Page 23: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

23

The for Statement SamplesThe for Statement Samples int num;int num;

for( num = 0; num < 10; num++ ) {for( num = 0; num < 10; num++ ) { cout << “Num = “ << num << endl; cout << “Num = “ << num << endl;}}

int num; int num; for( num = 10; num > 0; num-- ) {for( num = 10; num > 0; num-- ) { cout << “Num = “ << num << endl; cout << “Num = “ << num << endl;}}

int z;int z;for( num = 0, z = 4; num < 10; num++, z = z * 2 ) for( num = 0, z = 4; num < 10; num++, z = z * 2 ) {{ cout << “Num = “ << num << endl; cout << “Num = “ << num << endl; cout << “Z = “ << z << endl; cout << “Z = “ << z << endl;}}

for( ; ; )for( ; ; ) cout << “Good news” << endl; cout << “Good news” << endl;

Page 24: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

24

The for Statement Samples The for Statement Samples (continued)(continued)

for( int i = 0; i < 100; i++ )for( int i = 0; i < 100; i++ ) cout << ‘ ’; cout << ‘ ’;

num = 1;num = 1;for( ; num <= 10; num = num + 1 ) {for( ; num <= 10; num = num + 1 ) { cout << “Num = “ << num << endl; cout << “Num = “ << num << endl;}}

int num;int num;char ch;char ch;for( num = 0; ch != ‘Q’; num++ ) {for( num = 0; ch != ‘Q’; num++ ) { cout << “Num = “ << num << endl; cout << “Num = “ << num << endl;}}

for( ; !feof( PayFile ); ) {for( ; !feof( PayFile ); ) { Process(); Process();}}

Page 25: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

25

The for StatementThe for Statement The condition expression is The condition expression is ALWAYSALWAYS tested at the top of tested at the top of

the loop. This means (as in a do-while loop) the the loop. This means (as in a do-while loop) the statements inside the loop will not be executed if the statements inside the loop will not be executed if the condition is condition is falsefalse to begin with. to begin with.

The The forfor is one of the most versatile statements in C/C++. is one of the most versatile statements in C/C++.

The The forfor statement may have multiple initialization statement may have multiple initialization statements (must be separated by commas), conditional statements (must be separated by commas), conditional expressions, and increment and/or decrement statements.expressions, and increment and/or decrement statements.

The initialization, conditional expression, and increment The initialization, conditional expression, and increment sections are all optional, but the semicolons ( sections are all optional, but the semicolons ( ;; ) are ) are required.required.

Page 26: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

26

Time Delay LoopTime Delay LoopThe for statement can be used to implement time The for statement can be used to implement time delay loop. For example:delay loop. For example:

for( x = 0; x < 1000; x++ );for( x = 0; x < 1000; x++ );

This code simply stops execution of the program This code simply stops execution of the program for as long as it takes to count to for as long as it takes to count to 10001000..

Note the Note the semicolonsemicolon at the end of the statement. at the end of the statement. This is required because the This is required because the forfor statement expects statement expects at least one statement in the loop.at least one statement in the loop.

Page 27: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

27

switch Statementswitch StatementThe The switchswitch statement is useful when the selection is statement is useful when the selection is based on the value of a single variable or of a simple based on the value of a single variable or of a simple expression. The value of the expression may be of type expression. The value of the expression may be of type intint,, charchar, or an , or an enumerated typeenumerated type..The general syntax is:The general syntax is:

switch ( switch ( variable/value returned from a functionvariable/value returned from a function ) ){{ case case constant1constant1 : : statement or statement sequencestatement or statement sequence break;break; case case constant2constant2 : : statement or statement sequencestatement or statement sequence break;break; .. .. default : default : statement or statement sequencestatement or statement sequence break; break; }}

Page 28: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

28

switch Statement switch Statement (continued)(continued)

The The breakbreak causes an exit from the causes an exit from the switchswitch statement, and execution continues with the statement, and execution continues with the statement that follows the closing brace of the statement that follows the closing brace of the switch statement body.switch statement body.

The The defaultdefault statement statement MUSTMUST be last and be last and contains the statement sequence to be executed contains the statement sequence to be executed if non of the other if non of the other casecase values are detected. values are detected.

If the If the breakbreak is omitted the execution falls is omitted the execution falls through into the next alternative.through into the next alternative.

Page 29: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

29

switch Statement switch Statement (continued)(continued)

The The switchswitch differs from the if in that the switch can test differs from the if in that the switch can test only for equality between the switch expression and the only for equality between the switch expression and the casecase constant. The if conditional expression can be any constant. The if conditional expression can be any type.type.

No two No two casecase constants in the same constants in the same switchswitch can have the can have the same values, unless you have a nested same values, unless you have a nested switchswitch statement. statement.

A switch statement is usually more efficient than a nested A switch statement is usually more efficient than a nested ififs.s.

The statement/statement sequences associated with each The statement/statement sequences associated with each casecase are are NOTNOT blocks. However the entire blocks. However the entire switchswitch statement does define a block ( statement does define a block ( { . . . }{ . . . } ). ).

A A switchswitch statement can have at least statement can have at least 16,38416,384 casecase statements.statements.

Page 30: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

30

Sample switch StatementSample switch Statement#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int x;int x;

cout << "Enter a number between 1 and 4: ";cout << "Enter a number between 1 and 4: "; cin >> x;cin >> x; switch ( x ) {switch ( x ) { case 1 : cout << "You entered One\n";case 1 : cout << "You entered One\n"; break;break; case 2 : cout << "You entered Two\n";case 2 : cout << "You entered Two\n";

break;break; case 3 : cout << "You entered Three\n";case 3 : cout << "You entered Three\n";

break;break; case 4 : cout << "You entered Four\n";case 4 : cout << "You entered Four\n";

break;break; default: cout << "You entered an Unrecognized Number\n";default: cout << "You entered an Unrecognized Number\n"; break; break; // this break statement is optional// this break statement is optional }} return 0;return 0; }}

Page 31: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

31

Sample switch StatementSample switch StatementWhat will this switch statement do?What will this switch statement do?

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int x;int x;

cout << "Enter a number between 1 and 4: ";cout << "Enter a number between 1 and 4: "; cin >> x;cin >> x; switch ( x ) {switch ( x ) { case 1 : cout << "You entered One\n";case 1 : cout << "You entered One\n"; case 2 : cout << "You entered Two\n";case 2 : cout << "You entered Two\n"; case 3 : cout << "You entered Three\n";case 3 : cout << "You entered Three\n"; case 4 : cout << "You entered Four\n";case 4 : cout << "You entered Four\n"; default: cout << "You entered an Unrecognized Number\n";default: cout << "You entered an Unrecognized Number\n"; }} return 0;return 0; }}

Page 32: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

32

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { for( int i = 0; i < 12; i++)for( int i = 0; i < 12; i++) switch( i ) {switch( i ) { case 0 :case 0 : case 1 :case 1 : case 2 :case 2 : case 3 :case 3 : case 4 : cout << "i is < than 5“ << endl;case 4 : cout << "i is < than 5“ << endl; break;break; case 5 :case 5 : case 6 :case 6 : case 7 :case 7 : case 8 :case 8 : case 9 : cout << “i is < than 10“ << endl;case 9 : cout << “i is < than 10“ << endl; break;break; default: cout << "i is 10 or more“ << endl;default: cout << "i is 10 or more“ << endl; } } // end of switch// end of switch return 0;return 0; } } // end of main// end of main

The The breakbreak Statement is Statement is OptionalOptional

Page 33: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

33

Output:Output:i is less than 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 5i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is less than 10i is 10 or morei is 10 or morei is 10 or more i is 10 or more

The The breakbreak Statement is Statement is OptionalOptional

Page 34: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

34

int month = 4;int month = 4;char season[12];char season[12];

switch ( month ) {switch ( month ) { case 12 : case 12 : case 1 : case 1 : case 2 : strcpy(season, "Winter“);case 2 : strcpy(season, "Winter“); break;break; case 3 : case 3 : case 4 : case 4 : case 5 : strcpy(season, “Spring“);case 5 : strcpy(season, “Spring“); break;break; case 6 : case 6 : case 7 : case 7 : case 8 : strcpy(season, "Summer“);case 8 : strcpy(season, "Summer“); break;break; case 9 : case 9 : case 10 : case 10 : case 11 : strcpy(season, "Autumn“);case 11 : strcpy(season, "Autumn“); break;break; default : strcpy(season, "Bogus Month“);default : strcpy(season, "Bogus Month“);} } // end of switch// end of switchcout << "April is in the " << season << ".“ << endl;cout << "April is in the " << season << ".“ << endl;

Page 35: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

35

Sample switch StatementSample switch Statementchar MaritalStatus;char MaritalStatus;

switch( MaritalStatus ) {switch( MaritalStatus ) { case ‘M’ : cout << “Married “;case ‘M’ : cout << “Married “; break;break; case ‘S’ : cout << “Single “;case ‘S’ : cout << “Single “; break; break; case ‘D’ : cout << “Divorced “;case ‘D’ : cout << “Divorced “; break;break; case ‘W’ : cout << “Widowed “;case ‘W’ : cout << “Widowed “; break;break; case ‘P’ : cout << “Separated“;case ‘P’ : cout << “Separated“; break;break; default : cout << “Unknown “;default : cout << “Unknown “; break;break;} } // end of switch// end of switch

Page 36: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

36

Switch statements may be Switch statements may be nestednested. For example:. For example:

int count;int count;

switch ( count ) {switch ( count ) { case 1 : switch ( target ) { case 1 : switch ( target ) { // a nested switch // a nested switch case 0 : cout << “target is zero” << endl;case 0 : cout << “target is zero” << endl; break;break; case 1 : cout << “target is one” << endl;case 1 : cout << “target is one” << endl; break;break; } } // end of nested switch// end of nested switch break; break; case 2 : case 2 : .. .. break;break; case 3 : case 3 : .. .. break;break;} } // end of first switch // end of first switch

Nested switch StatementsNested switch Statements

Page 37: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

37

while Loopwhile LoopAnother loop provided in C/C++ is the Another loop provided in C/C++ is the whilewhile..

Its general form is:Its general form is:

while ( expression )while ( expression ) statement;statement;

OROR

while ( expression ) {while ( expression ) { statement sequencestatement sequence}}

As long as the As long as the expressionexpression evaluates to evaluates to truetrue the the statement or statement sequence is executed. If statement or statement sequence is executed. If the the expressionexpression is initially is initially falsefalse, the statement or , the statement or statement sequence is never executed.statement sequence is never executed.

Page 38: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

38

while Loop Examplewhile Loop ExampleThis program displays all the ASCII characters This program displays all the ASCII characters between between 3232 ( a space ) and ( a space ) and 255255..

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { unsigned char ch;unsigned char ch;

ch = 32;ch = 32; while( ch ) {while( ch ) { cout << ch;cout << ch; ch++;ch++; } } // end of while// end of while

return 0;return 0;} } // end of main// end of main

Page 39: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

39

while Loop Examplewhile Loop ExampleThis program displays a series of periods (This program displays a series of periods (..). The number of ). The number of periods displayed depends on the value entered by the user.periods displayed depends on the value entered by the user.

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int len;int len;

cout << “Enter length ( 1 to 79 ): “;cout << “Enter length ( 1 to 79 ): “; cin >> len;cin >> len;

while( len > 0 && len < 80 ) {while( len > 0 && len < 80 ) { cout << ‘.’;cout << ‘.’; len--;len--; } } // end of while// end of while

return 0;return 0;} } // end of main// end of main

Page 40: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

40

while Loop Examplewhile Loop ExampleWhat is wrong, if anything, with this program?What is wrong, if anything, with this program? #include <iostream>#include <iostream>

using namespace std;using namespace std;

int main() {int main() { int len;int len;

cout << “Enter length ( 1 to 79 ): “;cout << “Enter length ( 1 to 79 ): “; cin >> len;cin >> len;

while( len > 0 && len < 80 );while( len > 0 && len < 80 ); {{ cout << ‘.’;cout << ‘.’; len--;len--; } } // end of while// end of while

return 0;return 0;} } // end of main// end of main

Page 41: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

41

The do-while LoopThe do-while Loop

The The do-whiledo-while loop has the same general syntax as the loop has the same general syntax as the whilewhile loop except that it tests its condition at the loop except that it tests its condition at the bottombottom of the loop. This means that the program of the loop. This means that the program statements in the loop body will statements in the loop body will ALWAYSALWAYS be executed be executed at least one time.at least one time.

The do-whileThe do-while loop is like the loop is like the whilewhile loop in that you loop in that you may not know at design time how many times you will may not know at design time how many times you will need to loop.need to loop.

The general form is:The general form is:dodo {{ statementsstatements;;} while ( } while ( expressionexpression ); );

As long as the expression evaluates to As long as the expression evaluates to truetrue the the statements in the loop are executed.statements in the loop are executed.

Page 42: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

42

do-while Loop Exampledo-while Loop ExampleThis program loops until the number This program loops until the number 100100 is is entered.entered.

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int num;int num;

do {do { cout << “Enter a number (100 to stop): “;cout << “Enter a number (100 to stop): “; cin >> num;cin >> num; } while( num != 100 ); } while( num != 100 );

return 0;return 0;} } // end of main// end of main

Page 43: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

43

#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { char choice;char choice; do {do { cout << "Help on:“ << endl;cout << "Help on:“ << endl; cout << " 1. if“ << endl;cout << " 1. if“ << endl; cout << " 2. switch“ << endl;cout << " 2. switch“ << endl; cout << " 3. while“ << endl;cout << " 3. while“ << endl; cout << " 4. do-while“ << endl;cout << " 4. do-while“ << endl; cout << " 5. for“ << endl << endl;cout << " 5. for“ << endl << endl; cout << "Choose one: ";cout << "Choose one: "; cin >> choice;cin >> choice; } while( choice < '1' || choice > '5' );} while( choice < '1' || choice > '5' ); cout << endl;cout << endl; switch( choice ) {switch( choice ) { case '1' : cout << "The if:“ << endl;case '1' : cout << "The if:“ << endl; cout << "if(condition) statement;“ << endl;cout << "if(condition) statement;“ << endl; cout << "else statement;“ << endl;cout << "else statement;“ << endl; break;break;

Using a do-while to Process a Menu Using a do-while to Process a Menu SelectionSelection

Page 44: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

44

case '2' : cout << "The switch:“ << endl;case '2' : cout << "The switch:“ << endl; cout << "switch(expression) {“ << endl;cout << "switch(expression) {“ << endl; cout << " case constant:“ << endl;cout << " case constant:“ << endl; cout << " statement sequence“ << endl;cout << " statement sequence“ << endl; cout << " break;“ << endl;cout << " break;“ << endl; cout << " // ...“ << endl;cout << " // ...“ << endl; cout << "}“ << endl;cout << "}“ << endl; break;break; case '3' : cout << "The while:“ << endl;case '3' : cout << "The while:“ << endl; cout << "while(condition) statement;“ << endl;cout << "while(condition) statement;“ << endl; break;break; case '4' : cout << "The do-while:“ << endl;case '4' : cout << "The do-while:“ << endl; cout << "do {“ << endl;cout << "do {“ << endl; cout << " statement;“ << endl;cout << " statement;“ << endl; cout << "} while (condition);“ << endl;cout << "} while (condition);“ << endl; break;break; case '5' : cout << "The for:“ << endl;case '5' : cout << "The for:“ << endl; cout << "for(init; condition; iteration)“ << endl;cout << "for(init; condition; iteration)“ << endl; cout << " statement;“ << endl;cout << " statement;“ << endl; break;break; } } // end of switch// end of switch return 0;return 0;} } // end of main// end of main

Using a do-while to Process a Using a do-while to Process a Menu SelectionMenu Selection

Page 45: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

45

Help on:Help on: 1. if1. if 2. switch2. switch 3. while3. while 4. do-while4. do-while 5. for5. forChoose one: 4Choose one: 4

The do-while:The do-while:do {do { statement;statement;} while ( condition );} while ( condition );

Sample OutputSample Output

Page 46: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

46

Using continueUsing continueYou can force an early iteration of a loop, You can force an early iteration of a loop, bypassing the loop’s normal control structure, by bypassing the loop’s normal control structure, by using the using the continuecontinue statement. statement.

The The continuecontinue statement forces the next iteration statement forces the next iteration of the loop to take place, skipping any statements of the loop to take place, skipping any statements between itself and the conditional expression that between itself and the conditional expression that controls the loop.controls the loop.

For example:For example: int x;int x;

for( . . .; . . .; . . . ) {for( . . .; . . .; . . . ) { statement1;statement1; if( some-condition )if( some-condition ) continue;continue; statement2;statement2; statement3;statement3; } }

If the continue statement is executed, statements 2 and 3 are skipped that time through the loop. The test is then made to determine if the loop is to repeat or not.

Page 47: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

47

Using continueUsing continueHere is an example of the using the continue statement:Here is an example of the using the continue statement:#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int x;int x; for( x = 0; x <= 100; x++ ) {for( x = 0; x <= 100; x++ ) { if( x % 2 )if( x % 2 ) continue;continue; cout << x << ‘ ‘;cout << x << ‘ ‘; }} return 0;return 0;}}

The program above displays the The program above displays the eveneven numbers from numbers from 00 to to 100100..

Page 48: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

48

Using break to Exit LoopsUsing break to Exit Loops

Executing a break statement in a loop causes the Executing a break statement in a loop causes the loop to be loop to be immediatelyimmediately exited/terminated and exited/terminated and control is given to the first statement following the control is given to the first statement following the loop.loop.

For example:For example: #include <iostream>#include <iostream> using namespace std;using namespace std;

int main() {int main() { int t;int t; for( t = 0; t < 100; t++ ) {for( t = 0; t < 100; t++ ) { if( t == 10 )if( t == 10 ) break;break; cout << t << ‘ ‘;cout << t << ‘ ‘; }} return 0;return 0; }}

Page 49: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

49

Using break to Exit LoopsUsing break to Exit Loops#include <iostream>#include <iostream> using namespace std;using namespace std;

int main() {int main() { int t, count;int t, count; for( t = 0; t < 100; t++ ) {for( t = 0; t < 100; t++ ) { count = 1;count = 1; for( ; ; ) {for( ; ; ) { cout << count << ‘ ‘;cout << count << ‘ ‘; count++;count++; if( count == 10 )if( count == 10 ) break;break; }} cout << endl;cout << endl; }} return 0;return 0; }}

Page 50: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

50

Nested LoopsNested Loops#include <iostream>#include <iostream>using namespace std;using namespace std;

int main() {int main() { int i, j;int i, j; for( i = 2; i < 1000; i++ ) {for( i = 2; i < 1000; i++ ) { for( j = 2; j <= (i / j ); j++ )for( j = 2; j <= (i / j ); j++ ) if( !(i % j ) ) if( !(i % j ) ) break;break; if( j > (i / j) )if( j > (i / j) ) cout << i << “ is prime” << endl;cout << i << “ is prime” << endl; }} return 0;return 0;}}

This program finds all the prime numbers from This program finds all the prime numbers from 22 to to 10001000..

Page 51: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

51

The goto Statement Does Have The goto Statement Does Have its Placeits Place

The use of the The use of the gotogoto statement, which represents an statement, which represents an unconditionalunconditional branchbranch) has been discouraged for ) has been discouraged for years. The C/C++ language does provide a years. The C/C++ language does provide a gotogoto statement.statement.

However, there are no programming situations that However, there are no programming situations that require the use of the require the use of the gotogoto statement. Its use is for statement. Its use is for very special logic situations in a program.very special logic situations in a program.

The The gotogoto statement requires a statement requires a labellabel which is any which is any valid identifier followed by a colon ( valid identifier followed by a colon ( :: ). This ). This labellabel MUSTMUST be located in the same function as the be located in the same function as the gotogoto statement that uses it. statement that uses it.

You CANNOT use a goto statement in any of your

programs. It will cost you 200 points.

Page 52: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

52

The goto Statement Does Have The goto Statement Does Have its Placeits Place

void SomeFunction() {void SomeFunction() { for( . . . ) {for( . . . ) { for( . . . ) {for( . . . ) { while( . . . ) { while( . . . ) { if( . . . ) { if( . . . ) { cout << “Error in program. << endl; cout << “Error in program. << endl; goto getout;goto getout; } } . . . . . . . . } } . . . . } } . . . . } }getout:getout:} } // end of SomeFunction()// end of SomeFunction()

Page 53: Chapter 4 Program Control Statements C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

53

Happy Trails!Happy Trails!