Chapter – 6
Control Flow
This chapter introduces the statements needed to control the flow of a program.These are
- loops with while, do-while, and for
- selections with if-else, switch, and the conditional operator
- jumps with goto, continue, and break.
■ THE while STATEMENT
Structogram for while
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-58.png?resize=534%2C163&ssl=1)
Sample program
// average.cpp
// Computing the average of numbers
#include <iostream>
using namespace std;
int main()
{
int x, count = 0;
float sum = 0.0;
cout << "Please enter some integers:\n"
"(Break with any letter)"
<< endl;
while( cin >> x )
{
sum += x;
++count;
}
cout << "The average of the numbers: "
<< sum / count << endl;
return 0;
}
Sample output from the above program
Please enter some integers: (Break with any letter) 9 10 12q The average of the numbers: 10.3333
Loops are used to perform a set of instructions repeatedly. The set of instructions to be iterated is called the loop body. C++ offers three language elements to formulate iteration statements: while, do-while, and for. The number of times a loop is repeated is defined by a controlling expression. In the case of while and for statements this expres- sion is verified before the loop body is executed, whereas a do-while loop is performed once before testing.
The while statement takes the following format:
Syntax:
while( expression ) statement // loop body
When entering the loop, the controlling expression is verified, i.e. the expression is evaluated. If this value is true, the loop body is then executed before the controlling expression is evaluated once more.
If the controlling expression is false, i.e. expression evaluates to false, the pro- gram goes on to execute the statement following the while loop.
It is common practice to place the loop body in a new line of the source code and to indent the statement to improve the readability of the program.
Example:
int count = 0;
while( count < 10)
cout << ++count << endl;
As this example illustrates, the controlling expression is normally a boolean expression. However, the controlling expression might be any expression that can be converted to the bool type including any arithmetic expressions. As we already learned from the sec- tion on boolean operators, the value 0 converts to false and all other values convert to true.
□ Building Blocks
If you need to repeat more than one statement in a program loop, you must place the statements in a block marked by parentheses { }. A block is syntactically equivalent to a statement, so you can use a block wherever the syntax requires a statement.
The program on the opposite page calculates the average of a sequence of integers input via the keyboard. Since the loops contains two statements, the statements must be placed in a block.
The controlling expression cin >> x is true provided the user inputs an integer. The result of converting the expression cin >> x to a bool type will be true for any valid input and false in any other case. Invalid input, if the user types a letter instead of an integer, for example, terminates the loop and executes the next statement.
■ THE for STATEMENT
Structogram for for
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-66.png?resize=434%2C185&ssl=1)
Sample program
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-67.png?resize=435%2C274&ssl=1)
Screen output
Euro | Dollar |
1 | 0.95 |
2 | 1.90 |
3 | 2.85 |
4 | 3.80 |
5 | 4.75 |
□ Initializing and Reinitializing
A typical loop uses a counter that is initialized, tested by the controlling expression and reinitialized at the end of the loop.
Example:
int count = 1; // Initialization
while( count <= 10) // Controlling
{ // expression
cout << count
<< ". loop" << endl;
++count; // Reinitialization
}
In the case of a for statement the elements that control the loop can be found in the loop header. The above example can also be expressed as a for loop:
Example:
int count;
for( count = 1; count <= 10; ++count)
cout << count
<< ". loop" << endl;
Any expression can be used to initialize and reinitialize the loop. Thus, a for loop has the following form:
Syntax: for( expression1; expression2; expression3 ) statement
expression1 is executed first and only once to initialize the loop. expression2 is the controlling expression, which is always evaluated prior to executing the loop body:
- if expression2 is false, the loop is terminated
- if expression2 is true, the loop body is executed. Subsequently, the loop is reinitialized by executing expression3 and expression2 is re-tested.
You can also define the loop counter in expression1. Doing so means that the counter can be used within the loop, but not after leaving the loop.
Example: for( int i = 0; i < 10; cout << i++ );
As this example illustrates, the loop body can be an empty statement. This is always the case if the loop header contains all necessary statements. However, to improve readabil- ity, even the empty statement should occupy a line of its own.
■ THE for STATEMENT (CONTINUED)
Sample program
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-68.png?resize=434%2C587&ssl=1)
Any of the three expressions in a for statement can be omitted, however, you must type at least two semicolons. The shortest loop header is therefore:
Example: for(;;)
This statement causes an infinite loop, since the controlling expression is assumed to be true if expression2 is missing. In the following
Example: for( ; expression; )
the loop header is equivalent to while(expression). The loop body is executed as long as the test expression is true.
□ The Comma Operator
You can use the comma operator to include several expressions where a single expression is syntactically correct. For example, several variables can be initialized in the loop header of a for statement. The following syntax applies for the comma operator
Syntax: expression1, expression2 [, expression3 ...]
The expressions separated by commas are evaluated from left to right.
Example:
int x, i, limit;
for( i=0, limit=8; i < limit; i += 2) x = i * i, cout << setw(10) << x;
The comma operator separates the assignments for the variables i and limit and is then used to calculate and output the value of x in a single statement.
The comma operator has the lowest precedence of all operators — even lower than the assignment operators. This means you can leave out the parentheses in the above example.
Like any other C++ expression, an expression containing the comma operator has a value and belongs to a certain type. The type and value are defined by the last expression in a statement separated by commas.
Example: x = (a = 3, b = 5, a * b);
In this example the statements in brackets are executed before the value of the product of a * b is assigned to x.
■ THEdo-whileSTATEMENT
Structogram for do-while
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-69.png?resize=436%2C133&ssl=1)
Sample program
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-70.png?resize=434%2C336&ssl=1)
In contrast to while and for loops, which are controlled by their headers, the do- while loop is controlled by its footer, i.e. the controlling expression is evaluated after executing the first loop. This results in the loop body being performed at least once.
Syntax:
do
statement
while( expression);
When a do-while loop is executed, the loop body is processed first. Only then is the controlling expression evaluated. The loop body is iterated again if the result is true, otherwise the loop is terminated.
NOTE: The do-while loop must be followed by a semicolon.
□ Nesting Loops
Loops can be nested, that is, the loop body can also contain a loop. The ANSI standard stipulates a maximum depth of 256 nested loops.
The program on the opposite page outputs a number of tones with the number being defined by user input.
The program contains two loops — one of which is nested in the other. Each time the outer do-while loop is repeated a short break occurs. The break is caused by the inner for loop where the variable i is incremented from 0 to the value of delay.
Text and a tone are subsequently output. The tone is generated by outputting the control character BELL (ASCII code 7), which is represented by the escape sequence \a.
Since a do-while statement is used, the program outputs a tone even if the user types 0 or a negative number.
■ SELECTIONS WITH if-else
Structogram for the if-else statement
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-71.png?resize=436%2C169&ssl=1)
Sample program
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-72.png?resize=435%2C327&ssl=1)
Sample output for this program
Enter two different numbers: 7.5 5.7 The smaller number is: 5.7
The if-else statement can be used to choose between two conditional statements.
Syntax:
if( expression ) statement1 [ else statement2 ]
When the program is run, expression is first evaluated and the program control branches accordingly. If the result is true, statement1 is executed and statement2 is executed in all other cases, provided an else branch exists. If there is no else and expression is false, the control jumps to the statement following the if statement.
□ Nestedif-elseStatements
As the program opposite illustrates, multiple if-else statements can be nested. But not every if statement has an else branch. To solve the resulting problem, an else branch is always associated with the nearest preceding if statement that does not have an else branch.
Example:
In this example, the else branch belongs to the second if, as is indicated by the fact that the statement has been indented. However, you can use a code block to redefine the association of an else branch.
Example:
if( n > 0 )
if( n%2 == 1 )
cout << " Positive odd number ";
else
cout << "Positive even number";
□ Defining Variables in if Statements
You can define and initialize a variable within an if statement. The expression is true if converting the variable’s value to a bool type yields true. In this case the variable is available within the if statement.
Example:
if( int x = func() ) { . . . } // Here to work with x.
The return value of the function, func(), is used to initialize the variable x. If this value is not 0, the statements in the next block are executed. The variable x no longer exists after leaving the if statement.
■ Else-if CHAINS
Structogram for an else-if chain
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-73.png?resize=435%2C257&ssl=1)
Sample program
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-74.png?resize=435%2C341&ssl=1)
□ Layout and Program Flow
You can use an else-if chain to selectively execute one of several options. An else- if chain implies a series of embedded if-else statements whose layout is normally as follows:
if ( expression1 )
statement1
else if( expression2 )
statement2
.
.
.
else if( expression(n) )
statement(n)
[ else statement(n+1)]
When the else-if chain is executed, expression1, expression2, … are evaluated in the order in which they occur. If one of the expressions proves to be true, the corresponding statement is executed and this terminates the else-if chain.
If none of the expressions are true, the else branch of the last if statement is exe- cuted. If this else branch is omitted, the program executes the statement following the else-if chain.
□ The Sample Program
The program opposite uses an else-if chain to evaluate the penalty for driving too fast and outputs the fine on screen.
The speed limit and the actual speed are read from the keyboard. If the user types 60 as the speed limit and 97.5 as the actual speed, the first three expressions are not true, and the last else branch is executed. This outputs the message “Hand over your driver’s license!” on a new line.
■ CONDITIONAL EXPRESSIONS
Structogram for a conditional expression
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-75.png?resize=435%2C188&ssl=1)
Sample program
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-76.png?resize=435%2C296&ssl=1)
Sample output for this program
Type two different numbers: 173.2 216.7 The greater value is: 216.7
□ Conditional Operator
The conditional operator ?: is used to form an expression that produces either of two values, depending on the value of some condition. Because the value produced by such an expression depends on the value of a condition, it is called conditional expression.
In contrast to the if-else statement the selection mechanism is based on expres- sions: one of two possible expressions is selected. Thus, a conditional expression is often a concise alternative to an if-else statement.
Syntax: expression ? expression1 : expression2
expression is evaluated first. If the result is true, expression1 is evaluated; if not expression2 is executed. The value of the conditional expression is therefore either the value of expression1 or expression2.
Example: z = (a >= 0) ? a : -a;
This statement assigns the absolute value of a to the variable z. If a has a positive value of 12, the number 12 is assigned to z. But if a has a negative value, for example –8, the number 8 is assigned to z.
Since this sample program stores the value of the conditional expression in the vari- able z, the statement is equivalent to
if( a > 0 ) z = a; else z = -a;
□ Precedence
The conditional operator is the only C++ operator with three operands. Its precedence is higher than that of the comma and assignment operators but lower than all other opera- tors. In other words, you could omit the brackets in the first example.
You can use the result of a conditional evaluation without assigning it, as the sample program on the opposite page shows. In this example, x is printed on screen if x is greater than y, and y is printed otherwise.
However, you should assign the result of complex expressions to a variable explicitly to improve the readability of your program.
■ SELECTING WITH switch
Structogram for the switch statement
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-77.png?resize=435%2C233&ssl=1)
Example
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-78.png?resize=435%2C254&ssl=1)
□ The switch Statement
Just like the else-if chain, the switch statement allows you to choose between mul- tiple alternatives. The switch statement compares the value of one expression with multiple constants.
switch( expression ) { case const1: [ statement ] [ break; ] case const2: [ statement ] [ break; ] . . . [default: statement ] }
First, the expression in the switch statement is evaluated. It must be an integral type. The result is then compared to the constants, const1, const2, …, in the case labels. The constants must be different and can only be integral types (boolean values and character constants are also integral types).
If the value of an expression matches one of the case constants, the program branches to the appropriate case label. The program then continues and the case labels lose their significance.
You can use break to leave the switch statement unconditionally. The statement is necessary to avoid executing the statements contained in any case labels that follow.
If the value of the expression does not match any of the case constants, the program branches to the default label, if available. If you do not define a default label, noth- ing happens. The default does not need to be the last label; it can be followed by addi- tional case labels.
Differences between switch andelse-if Chains
The else-if chain is more versatile than the switch statement. Every selection can be programmed using an else-if chain. But you will frequently need to compare the value of an integral expression with a series of possible values. In this case (and only this case), you can use a switch statement.
As the example opposite shows, a switch statement is more easily read than an equivalent else-if chain, so use the switch statement whenever possible.
■ JUMPS WITH break, continue, AND goto
Structogram for break within a while statement
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-79.png?resize=434%2C184&ssl=1)
Sample program containing a break statement
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-81.png?resize=435%2C367&ssl=1)
NOTE: The expression (char)ac yields the value ac of type char.
□ break
The break statement exits from a switch or loop immediately. You can use the breakkeyword to jump to the first statement that follows the switch or loop.
The program on the opposite page, which outputs a group of 20 ASCII characters and their corresponding codes, uses the break keyword in two places. The first break exits from an infinite while(true) { … } loop when a maximum value of 256 has been reached. But the user can also opt to continue or terminate the program. The second break statement is used to terminate the while loop and hence the program.
□ continue
The continue statement can be used in loops and has the opposite effect to break, that is, the next loop is begun immediately. In the case of a while or do-while loop the program jumps to the test expression, whereas a for loop is reinitialized.
Example:
for( int i = 0; i < 100; i++ ) { . . . // Processes all integers. if( i % 2 == 1) continue; . . . // Process even // numbers only. }
goto and Labels
C++ also offers a goto statement and labels. This allows you to jump to any given point marked by a label within a function. For example, you can exit from a deeply embedded loop construction immediately.
Example:
for( . . . ) for( . . . ) if (error) goto errorcheck; . . . errorcheck: . . . // Error handling
A label is a name followed by a colon. Labels can precede any statement.
Any program can do without goto statements. If you need to use a goto statement, do so to exit from a code block, but avoid entering code blocks by this method.
EXERCISES
Screen output for exercise 2
![](https://i0.wp.com/thesli.in/wp-content/uploads/2023/12/image-258.png?resize=485%2C280&ssl=1)
Note on exercise 4
Use the function time() to initialize the random number generator:
#include <time.h> // Prototype of time()
#include <stdlib.h> // Prototypes of srand()
// and rand()
long sec;
time( &sec ); // Take the number of seconds and
srand( (unsigned)sec ); // use it to initialize.
Exercise 1
Rewrite the EuroDoll.cpp program in this chapter to replace both the for
loops with while loops.
Exercise 2
Write a C++ program that outputs a complete multiplication table (as shown opposite) on screen.
Exercise 3
Write a C++ program that reads an integer between 0 and 65535 from the keyboard and uses it to seed a random number generator.Then output 20 random numbers between 1 and 100 on screen.
Exercise 4
Write a program for the following numerical game:
The computer stores a random number between 1 and 15 and the player (user) attempts to guess it.The player has a total of three attempts.After each wrong guess, the computer tells the user if the number was too high or too low. If the third attempt is also wrong, the number is output on screen.
The player wins if he or she can guess the number within three attempts.The player is allowed to repeat the game as often as he or she wants.
NOTE: Use the system time to seed the random number generator as shown opposite. The time() function returns the number of seconds since 1/1/1970, 0:0. The long value of the sec variable is converted to unsigned by unsigned(sec) and then passed to the srand() function.
SOLUTIONS
Exercise 1
The for loops of program EuroDoll.cpp are equivalent to the following while
loops:
// The outer loop sets the lower
// limit and the step width used:
lower=1, step=1;
while( lower <= maxEuro)
{
// The inner loop outputs a block:
euro = lower;
upper = step*10;
while( euro <= upper && euro <= maxEuro)
{
cout << setw(12) << euro
<< setw(20) << euro*rate << endl;
euro += step;
}
step *= 10, lower = 2*step;
}
Exercise 2
// MultTable.cpp // Outputs a multiplication table #include <iostream> #include <iomanip> using namespace std; int main() { int factor1, factor2; cout << "\n\n " << " ****** MULTIPLICATION TABLE ******" << endl; // Outputs the first and second line: cout << "\n\n\n "; // 1. line for( factor2 = 1 ; factor2 <= 10 ; ++factor2 ) cout << setw(5) << factor2; cout << "\n " // 2. line << "-----------------------------------" << endl; // Outputs the remaining lines of the table: for( factor1 = 1 ; factor1 <= 10 ; ++factor1 ) { cout << setw(6) << factor1 << " |"; for( factor2 = 1 ; factor2 <= 10 ; ++factor2 ) cout << setw(5) << factor1 * factor2; cout << endl; } cout << "\n\n\n"; // To shift up the table return 0; }
Exercise 3
// random.cpp
// Outputs 20 random numbers from 1 to 100.
#include <stdlib.h> // Prototypes of srand() and rand()
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
unsigned int i, seed;
cout << "\nPlease type an integer between "
"0 and 65535: ";
cin >> seed; // Reads an integer.
srand( seed); // Seeds the random
// number generator.
cout << "\n\n "
"****** RANDOM NUMBERS ******\n\n";
for( i = 1 ; i <= 20 ; ++i)
cout << setw(20) << i << ". random number = "
<< setw(3) << (rand() % 100 + 1) << endl;
return 0;
}
Exercise 4
// NumGame.cpp : A numerical game against the computer
#include <cstdlib> // Prototypes of srand() and rand()
#include <ctime> // Prototype of time()
#include <iostream>
using namespace std;
int main()
{
int number, attempt;
char wb = 'r'; // Repeat or finish.
long sec;
time( &sec); // Get the time in seconds.
srand((unsigned)sec); // Seeds the random
// number generator
cout << "\n\n "
<< " ******* A NUMERICAL GAME *******" << endl;
cout << "\n\nRules of the game:" << endl;
while( wb == 'r')
{
cout << "I have a number between 1 and 15 in mind \n"
<< "You have three chances to guess correctly!\n"
<< endl;
number = (rand() % 15) + 1;
bool found = false; int count = 0;
while( !found && count < 3 )
{
cin.sync(); // Clear input buffer
cin.clear();
cout << ++count << ". attempt: ";
cin >> attempt;
if(attempt < number) cout << "too small!"<< endl;
else if(attempt > number) cout <<"too big!"<< endl;
else found = true;
}
if( !found)
cout << "\nI won!"
<< " The number in question was: "
<< number << endl;
else
cout << "\nCongratulations! You won!" << endl;
cout << "Repeat —> <r> Finish —> <f>\n";
do
cin.get(wb);
while( wb != 'r' && wb != 'f');
}
return 0;
}