“If you think we’re wax-works,” he said, “you ought to pay, you know. Wax-works weren’t made to be looked at for nothing. Nohow!”
“Contrariwise,” added the one marked “DEE,” “if you think we’re alive, you ought to speak.”
LEWIS CARROLL, Through the Looking-Glass
The programs you have seen thus far each consist of a simple list of statements to be executed in the order given. However, to write more sophisticated programs, you will also need some way to vary the order in which statements are executed. The order in which statements are executed is often referred to as flow of control. In this section we will present two simple ways to add some flow of control to your programs. We will discuss a branching mechanism that lets your program choose between two alternative actions, choosing one or the other depending on the values of variables. We will also present a looping mechanism that lets your program repeat an action a number of times.
Sometimes it is necessary to have a program choose one of two alternatives, depending on the input. For example, suppose you want to design a program to compute a week’s salary for an hourly employee. Assume the firm pays an overtime rate of one-and-one-half times the regular rate for all hours after the first 40 hours worked. As long as the employee works 40 or more hours, the pay is then equal to
rate * 40 + 1.5 * rate * (hours − 40)
However, if there is a possibility that the employee will work less than 40 hours, this formula will unfairly pay a negative amount of overtime. (To see this, just substitute 10
for hours
, 1
for rate
, and do the arithmetic. The poor employee will get a negative paycheck.) The correct pay formula for an employee who works less than 40 hours is simply
rate * hours
If both more than 40 hours and less than 40 hours of work are possible, then the program will need to choose between the two formulas. In order to compute the employee’s pay, the program action should be
Decide whether or not (hours > 40)
is true.
If it is, do the following assignment statement:
grossPay = rate * 40 + 1.5 * rate * (hours − 40);
If it is not, do the following:
grossPay = rate * hours;
There is a C++ statement that does exactly this kind of branching action. The if-else
statement chooses between two alternative actions. For example, the wage calculation we have been discussing can be accomplished with the following C++ statement:
if (hours > 40)
grossPay = rate * 40 + 1.5 * rate * (hours − 40);
else grossPay = rate * hours;
A complete program that uses this statement is given in Display 2.8.
if-else
Statement 1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 int hours;
6 double grossPay, rate;
7 cout << "Enter the hourly rate of pay: $";
8 cin >> rate;
9 cout << "Enter the number of hours worked,\n"
10 << "rounded to a whole number of hours: ";
11 cin >> hours;
12 if (hours > 40)
13 grossPay = rate * 40 + 1.5 * rate * (hours - 40);
14 else
15 grossPay = rate * hours;
16 cout.setf(ios::fixed);
17 cout.setf(ios::showpoint);
18 cout.precision(2);
19 cout << "Hours = " << hours << endl;
20 cout << "Hourly pay rate = $" << rate << endl;
21 cout << "Gross pay = $" << grossPay << endl;
22 return 0;
23 }
Sample Dialogue 1
Enter the hourly rate of pay: $20.00 Enter the number of hours worked, rounded to a whole number of hours: 30 Hours = 30 Hourly pay rate = $20.00 Gross pay = $600.00
Sample Dialogue 2
Enter the hourly rate of pay: $10.00 Enter the number of hours worked, rounded to a whole number of hours: 41 Hours = 41 Hourly pay rate = $10.00 Gross pay = $415.00
Two forms of an if-else
statement are described in Display 2.9. The first is the simple form of an if-else
statement; the second form will be discussed in the subsection entitled “Compound Statements.” In the first form shown, the two statements may be any executable statements. The Boolean_Expression
is a test that can be checked to see if it is true or false, that is, to see if it is satisfied or not. For example, the Boolean_Expression
in the earlier if-else
statement is
hours > 40
When the program reaches the if-else
statement, exactly one of the two embedded statements is executed. If the Boolean_Expression
is true (that is, if it is satisfied), then the Yes_Statement
is executed; if the Boolean_Expression
is false (that is, if it is not satisfied), then the No_Statement
is executed. Notice that the Boolean_Expression
must be enclosed in parentheses. (This is required by the syntax rules for if-else
statements in C++.) Also notice that an if-else
statement has two smaller statements embedded in it.
if-else
StatementA Single Statement for Each Alternative:
1 if (Boolean_Expression)
2 Yes_Statement
3 else
4 No_Statement
A Sequence of Statements for Each Alternative:
5 if (Boolean_Expression)
6 {
7 Yes_Statement_1
8 Yes_Statement_2
9 ...
10 Yes_Statement_Last
11 }
12 else
13 {
14 No_Statement_1
15 No_Statement_2
16 ...
17 No_Statement_Last
18 }
A Boolean expression is any expression that is either true or false. An if-else
statement always contains a Boolean_Expression
. The simplest form for a Boolean_Expression
consists of two expressions, such as numbers or variables, that are compared with one of the comparison operators shown in Display 2.10. Notice that some of the operators are spelled with two symbols: for example, ==, !=, <=, >=. Be sure to notice that you use a double equal == for the equal sign, and you use the two symbols != for not equal. Such operators should not have any space between the two symbols. The part of the compiler that separates the characters into C++ names and symbols will see the !=
, for example, and tell the rest of the compiler that the programmer meant to test for INEQUALITY. When an if-else
statement is executed, the two expressions being compared are evaluated and compared using the operator. If the comparison turns out to be true, then the first statement is performed. If the comparison fails, then the second statement is executed.
Math Symbol | English | C++ Notation | C++ Sample | Math Equivalent |
---|---|---|---|---|
= |
equal to |
== |
× + 7 == 2 * y |
x + 7 = 2y |
≠ |
not equal to |
!= |
ans != 'n' |
ans ≠ 'n' |
< |
less than |
< |
count < m + 3 |
count < m + 3 |
≤ |
less than or equal to |
<= |
time <= limit |
time ≤ limit |
> |
greater than |
> |
time > limit |
time > limit |
≥ |
greater than or equal to |
>= |
age >= 21 |
age ≥ 21 |
You can combine two comparisons using the “and” operator, which is spelled &&
in C++. For example, the following Boolean expression is true (that is, is satisfied) provided x
is greater than 2
and x
is less than 7
:
(2 < x) && (x < 7)
When two comparisons are connected using a &&
, the entire expression is true, provided both of the comparisons are true (that is, provided both are satisfied); otherwise, the entire expression is false.
You can also combine two comparisons using the “or” operator, which is spelled ||
in C++. For example, the following is true provided y
is less than 0
or y
is greater than 12
:
(y < 0) || (y > 12)
When two comparisons are connected using a ||
, the entire expression is true provided that one or both of the comparisons are true (that is, satisfied); otherwise, the entire expression is false.
Remember that when you use a Boolean expression in an if-else
statement, the Boolean expression must be enclosed in parentheses. Therefore, an if-else
statement that uses the &&
operator and two comparisons is parenthesized as follows:
if ( (temperature >= 95) && (humidity >= 90) )
. . .
The inner parentheses around the comparisons are not required, but they do make the meaning clearer, and we will normally include them.
You can negate any Boolean expression using the ! operator. If you want to negate a Boolean expression, place the expression in parentheses and place the !
operator in front of it. For example,!(x < y)
means “x
is not less than y
.”
Since the Boolean expression in an if-else
statement must be enclosed in parentheses, you should place a second pair of parentheses around the negated expression when it is used in an if-else
statement. For example, an if-else
statement might begin as follows:
if (!(x < y))
...
The !
operator can usually be avoided. For example, our hypothetical if-else
statement can instead begin with the following, which is equivalent and easier to read:
if (x >= y)
...
We will not have much call to use the ! operator until later in this book, so we will postpone any detailed discussion of it until then.
Sometimes you want one of the two alternatives in an if-else
statement to do nothing at all. In C++ this can be accomplished by omitting the else
part. These sorts of statements are referred to as if
statements to distinguish them from if-else
statements. For example, the first of the following two statements is an if
statement:
if (sales >= minimum)
salary = salary + bonus;
cout << "salary = $" << salary;
If the value of sales
is greater than or equal to the value of minimum
, the assignment statement is executed and then the following cout
statement is executed. On the other hand, if the value of sales
is less than minimum
, then the embedded assignment statement is not executed, so the if
statement causes no change (that is, no bonus is added to the base salary), and the program proceeds directly to the cout
statement.
You will often want the branches of an if-else
statement to execute more than one statement each. To accomplish this, enclose the statements for each branch between a pair of braces, {
and }
, as indicated in the second syntax template in Display 2.9 and illustrated in Display 2.11. A list of statements enclosed in a pair of braces is called a compound statement. A compound statement is treated as a single statement by C++ and may be used anywhere that a single statement may be used. (Thus, the second syntax template in Display 2.9 is really just a special case of the first one.) Display 2.11 contains two compound statements, embedded in an if-else
statement.
if-else
1 if (my_score > your_score)
2 {
3 cout << "I win!\n";
4 wager = wager + 100;
5 }
6 else
7 {
8 cout << "I wish these were golf scores.\n";
9 wager = 0;
10 }
Syntax rules for if-else
demand that the Yes statement and No statement be exactly one statement. If more statements are desired for a branch, the statements must be enclosed in braces to convert them to one compound statement. If two or more statements not enclosed by braces are placed between the if
and the else, then the compiler will give an error message.
Write an if-else
statement that outputs the word High
if the value of the variable score
is greater than 100
and Low
if the value of score
is at most 100
. The variable score
is of type int
.
Suppose savings
and expenses
are variables of type double
that have been given values. Write an if-else
statement that outputs the word Solvent
, decreases the value of savings
by the value of expenses
, and sets the value of expenses
to 0
, provided that savings
is at least as large as expenses
. If, however, savings
is less than expenses
, the if-else
statement simply outputs the word Bankrupt
and does not change the value of any variables.
Write an if-else
statement that outputs the word Passed
provided the value of the variable exam
is greater than or equal to 60
and the value of the variable programs_done
is greater than or equal to 10
. Otherwise, the if-else
statement outputs the word Failed
. The variables exam
and programs_done
are both of type int
.
Write an if-else
statement that outputs the word Warning
provided that either the value of the variable temperature
is greater than or equal to 100
, or the value of the variable pressure
is greater than or equal to 200
, or both. Otherwise, the if-else
statement outputs the word OK
. The variables temperature
and pressure
are both of type int
.
Consider a quadratic expression, say
x2 − x − 2
Describing where this quadratic is positive (that is, greater than 0), involves describing a set of numbers that are either less than the smaller root (which is −1
) or greater than the larger root (which is +2
). Write a C++ Boolean expression that is true when this formula has positive values.
Consider the quadratic expression
x2 − 4x + 3
Describing where this quadratic is negative involves describing a set of numbers that are simultaneously greater than the smaller root (+1
) and less than the larger root (+3
). Write a C++ Boolean expression that is true when the value of this quadratic is negative.
What is the output of the following cout
statements embedded in these if-else
statements? You are to assume that these are embedded in a complete correct program. Explain your answer.
if (0)
cout << "0 is true";
else
cout << "0 is false";
cout << endl;
if (1)
cout << "1 is true";
else
cout << "1 is false";
cout << endl;
if (−1)
cout << "−1 is true";
else
cout << "−1 is false";
cout << endl;
Note: This is an exercise only. This is not intended to illustrate programming style you should follow.
Most programs include some action that is repeated a number of times. For example, the program in Display 2.8 computes the gross pay for one worker. If the company employs 100 workers, then a more complete payroll program would repeat this calculation 100 times. A portion of a program that repeats a statement or group of statements is called a loop. The C++ language has a number of ways to create loops. One of these constructions is called a while
statement or while
loop. We will first illustrate its use with a short toy example and then do a more realistic example.
The program in Display 2.12 contains a simple while
statement shown in color. The portion between the braces, {
and }
, is called the body of the while
loop; it is the action that is repeated. The statements inside the braces are executed in order, then they are executed again, then again, and so forth until the while
loop ends. In the first sample dialogue, the body is executed three times before the loop ends, so the program outputs Hello
three times. Each repetition of the loop body is called an iteration of the loop, and so the first sample dialogue shows three iterations of the loop.
while
Loop 1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 int countDown;
6 cout << "How many greetings do you want? ";
7 cin >> countDown;
8 while (countDown > 0)
9 {
10 cout << "Hello ";
11 countDown = countDown - 1;
12 }
13 cout << endl;
14 cout << "That's all!\n";
15 return 0;
16 }
17
Sample Dialogue 1
How many greetings do you want? 3
Hello Hello Hello
That's all!
Sample Dialogue 2
How many greetings do you want? 1
Hello
That's all!
Sample Dialogue 3
The meaning of a while
statement is suggested by the English word while
. The loop is repeated while the Boolean expression in the parentheses is satisfied. In Display 2.12 this means that the loop body is repeated as long as the value of the variable countDown
is greater than 0
. Let’s consider the first sample dialogue and see how the while
loop performs. The user types in 3
so the cin
statement sets the value of countDown
to 3
. Thus, in this case, when the program reaches the while
statement, it is certainly true that countDown
is greater than 0
, so the statements in the loop body are executed. Every time the loop body is repeated, the following two statements are executed:
cout << "Hello ";
countDown = countDown − 1;
Therefore, every time the loop body is repeated, "Hello "
is output and the value of the variable countDown
is decreased by one. After the computer repeats the loop body three times, the value of countDown
is decreased to 0
and the program in Display 2.12 and the Boolean expression in parentheses are no longer satisfied. So, this while
statement ends after repeating the loop body three times.
The syntax for a while
statement is given in Display 2.13. The Boolean_Expressions
allowed are exactly the same as the Boolean expressions allowed in an if-else
statement. Just as in if-else
statements, the Boolean expression in a while
statement must be enclosed in parentheses. In Display 2.13 we have given the syntax templates for two cases: the case when there is more than one statement in the loop body and the case when there is just a single statement in the loop body. Note that when there is only a single statement in the loop body, you need not include the braces {
and }
.
while
StatementLet’s go over the actions performed by a while
statement in greater detail. When the while
statement is executed, the first thing that happens is that the Boolean expression following the word while
is checked. It is either true or false. For example, the comparison
countDown > 0
is true if the value of countDown
is positive. If it is false, then no action is taken and the program proceeds to the next statement after the while
statement. If the comparison is true, then the entire body of the loop is executed. At least one of the expressions being compared typically contains something that might be changed by the loop body, such as the value of countDown
in the while
statement in Display 2.12. After the body of the loop is executed, the comparison is again checked. This process is repeated again and again as long as the comparison continues to be true. After each iteration of the loop body, the comparison is again checked and if it is true, then the entire loop body is executed again. When the comparison is no longer true, the while
statement ends.
The first thing that happens when a while
statement is executed is that the Boolean expression is checked. If the Boolean expression is not true when the while
statement begins, then the loop body is never executed. That is exactly what happens in Sample Dialogue 3 of Display 2.12. In many programming situations you want the possibility of executing the loop body zero times. For example, if your while
loop is reading a list consisting of all the failing scores on an exam and nobody failed the exam, then you want the loop body to be executed zero times.
As we just noted, a while
loop might execute its loop body zero times, which is often what you want. If, on the other hand, you know that under all circumstances your loop body should be executed at least one time, then you can use a do-while
statement. A do-while
statement is similar to a while
statement except that the loop body is always executed at least once. The syntax for a do-while
statement is given in Display 2.14. A program with a sample do-while
loop is given in Display 2.15. In that do-while
loop, as in any do-while
loop, the first thing that happens is that the statements in the loop body are executed. After that first iteration of the loop body, the do-while
statement behaves the same as a while
loop. The Boolean expression is checked. If the Boolean expression is true, the loop body is executed again; the Boolean expression is checked again, and so forth.
do-while
Statementdo-while
Loop 1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 char ans;
6 do
7 {
8 cout << "Hello\n";
9 cout << "Do you want another greeting?\n"
10 << "Press y for yes, n for no,\n"
11 << "and then press return: ";
12 cin >> ans;
13 } while (ans == 'y' || ans == 'Y');
14 cout << "Good-Bye\n";
15 return 0;
16 }
Sample Dialogue
Hello Do you want another greeting? Press y for yes, n for no, and then press return: y Hello Do you want another greeting? Press y for yes, n for no, and then press return: Y Hello Do you want another greeting? Press y for yes, n for no, and then press return: n Good-Bye
We discussed binary operators in the section entitled “Arithmetic Operators and Expressions.” Binary operators have two operands. Unary operators have only one operand. You already know of two unary operators, +
and −
, as used in the expressions +7
and −7
. The C++ language has two other very common unary operators, ++
and −−
. The ++
operator is called the increment operator and the −−
operator is called the decrement operator. They are usually used with variables of type int
. If n
is a variable of type int
, then n++
increases the value of n
by one and n−−
decreases the value of n
by one. So n++
and n−−
(when followed by a semicolon) are executable statements. For example, the statements
int n = 1, m = 7;
n++;
cout << "The value of n is changed to " << n << endl;
m−−;
cout << "The value of m is changed to " << m << endl;
yield the following output:
The value of n is changed to 2 The value of m is changed to 6
And now you know where the “++” came from in the name “C++.”
Increment and decrement statements are often used in loops. For example, we used the following statement in the while
loop in Display 2.12:
countDown = countDown − 1;
However, most experienced C++ programmers would use the decrement operator rather than the assignment statement, so the entire while
loop would read as follows:
while (countDown > 0)
{
cout << "Hello ";
countDown−−;
}
Suppose you have a bank charge card with a balance owed of $50 and suppose the bank charges you 2% per month interest. How many months can you let pass without making any payments before your balance owed will exceed $100? One way to solve this problem is to simply read each monthly statement and count the number of months that go by until your balance reaches $100 or more. Better still, you can calculate the monthly balances with a program rather than waiting for the statements to arrive. In this way you will obtain an answer without having to wait so long (and without endangering your credit rating).
After one month the balance would be $50 plus 2% of $50, which is $51. After two months the balance would be $51 plus 2% of $51, which is $52.02. After three months the balance would be $52.02 plus 2% of $52.02, and so on. In general, each month increases the balance by 2%. The program could keep track of the balance by storing it in a variable called balance
. The change in the value of balance
for one month can be calculated as follows:
balance = balance + 0.02 * balance ;
If we repeat this action until the value of balance
reaches (or exceeds) 100.00
and we count the number of repetitions, then we will know the number of months it will take for the balance to reach 100.00
. To do this, we need another variable to count the number of times the balance is changed. Let us call this new variable count
. The final body of our while
loop will thus contain the following statements:
balance = balance + 0.02 * balance;
count++;
In order to make this loop perform correctly, we must give appropriate values to the variables balance
and count
before the loop is executed. In this case, we can initialize the variables when they are declared. The complete program is shown in Display 2.16.
1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 double balance = 50.00;
6 int count = 0;
7 cout << "This program tells you how long it takes\n"
8 << "to accumulate a debt of $100, starting with\n"
9 << "an initial balance of $50 owed.\n"
10 << "The interest rate is 2% per month.\n";
11 while (balance < 100.00)
12 {
13 balance = balance + 0.02 * balance;
14 count++;
15 }
16 cout << "After " << count << " months,\n";
17 cout.setf(ios::fixed);
18 cout.setf(ios::showpoint);
19 cout.precision(2);
20 cout << "your balance due will be $" << balance << endl;
21 return 0;
22 }
23
Sample Dialogue
This program tells you how long it takes to accumulate a debt of $100, starting with an initial balance of $50 owed. The interest rate is 2% per month. After 36 months, your balance due will be $101.99
A while
loop or a do-while
loop does not terminate as long as the Boolean expression after the word while
is true. This Boolean expression normally contains a variable that will be changed by the loop body, and usually the value of this variable eventually is changed in a way that makes the Boolean expression false and therefore terminates the loop. However, if you make a mistake and write your program so that the Boolean expression is always true, then the loop will run forever. A loop that runs forever is called an infinite loop.
First let’s describe a loop that does terminate. The following C++ code will write out the positive even numbers less than 12. That is, it will output the numbers 2
, 4
, 6
, 8
, and 10
, one per line, and then the loop will end.
x = 2;
while (x != 12)
{
cout << x << endl;
x = x + 2;
}
The value of x
is increased by 2
on each loop iteration until it reaches 12
. At that point, the Boolean expression after the word while
is no longer true, so the loop ends.
Now suppose you want to write out the odd numbers less than 12, rather than the even numbers. You might mistakenly think that all you need do is change the initializing statement to
x = 1;
but this mistake will create an infinite loop. Because the value of x
goes from 11
to 13
, the value of x
is never equal to 12
, so the loop will never terminate.
This sort of problem is common when loops are terminated by checking a numeric quantity using ==
or !=
. When dealing with numbers, it is always safer to test for passing a value. For example, the following will work fine as the first line of our while
loop:
while (x < 12)
With this change, x
can be initialized to any number and the loop will still terminate.
A program that is in an infinite loop will run forever unless some external force stops it. Since you can now write programs that contain an infinite loop, it is a good idea to learn how to force a program to terminate. The method for forcing a program to stop varies from system to system. The keystrokes Control-C will terminate a program on many systems. (To type a Control-C, hold down the Control key while pressing the C key.)
What is the output produced by the following (when embedded in a correct program with x
declared to be of type int
)?
x = 10;
while (x > 0)
{
cout << x << endl;
x = x − 3;
}
What output would be produced in the previous exercise if the > sign were replaced with < ?
What is the output produced by the following (when embedded in a correct program with x
declared to be of type int
)?
x = 10;
do {
cout << x << endl;
x = x − 3;
} while (x > 0);
What is the output produced by the following (when embedded in a correct program with x
declared to be of type int
)?
x = −42;
do {
cout << x << endl;
x = x − 3;
} while (x > 0);
What is the most important difference between a while
statement and a do-while
statement?
What is the output produced by the following (when embedded in a correct program with x
declared to be of type int
)?
x = 10;
while (x > 0)
{
cout << x << endl;
x = x + 3;
}
Write a complete C++ program that outputs the numbers 1 to 20, one per line. The program does nothing else.