3.3 More About C++ Loop Statements

It is not true that life is one damn thing after another—

It’s one damn thing over and over.

EDNA ST. VINCENT MILLAY, Letter to Arthur Darison Ficke, October 24, 1930

A loop is any program construction that repeats a statement or sequence of statements a number of times. The simple while loops and do-while loops that we have already seen are examples of loops. The statement (or group of statements) to be repeated in a loop is called the body of the loop, and each repetition of the loop body is called an iteration of the loop. The two main design questions when constructing loops are: What should the loop body be? How many times should the loop body be iterated?

The while Statements Reviewed

The syntax for the while statement and its variant, the do-while statement, is reviewed in Display 3.9. The important difference between the two types of loops involves when the controlling Boolean expression is checked. When a while statement is executed, the Boolean expression is checked before the loop body is executed. If the Boolean expression evaluates to false, then the body is not executed at all. With a do-while statement, the body of the loop is executed first and the Boolean expression is checked after the loop body is executed. Thus, the do-while statement always executes the loop body at least once. After this start-up, the while loop and the do-while loop behave very much the same. After each iteration of the loop body, the Boolean expression is again checked; if it is true, then the loop is iterated again. If it has changed from true to false, then the loop statement ends.

Display 3.9 Syntax of the while Statement and do-while Statement

An illustration shows syntax of “while” statement and “do-while” statement.

The first thing that happens when a while loop is executed is that the controlling Boolean expression is evaluated. If the Boolean expression evaluates to false at that point, then the body of the loop is never executed. It may seem pointless to execute the body of a loop zero times, but that is sometimes the desired action. For example, a while loop is often used to sum a list of numbers, but the list could be empty. To be more specific, a checkbook balancing program might use a while loop to sum the values of all the checks you have written in a month—but you might take a month’s vacation and write no checks at all. In that case, there are zero numbers to sum and so the loop is iterated zero times.

Increment and Decrement Operators Revisited

You have used the increment operator as a statement that increments the value of a variable by 1. For example, the following will output 42 to the screen:

int number = 41;
number++;
cout << number;

Thus far we have always used the increment operator as a statement. But the increment operator is also an operator, just like the + and ? operators. An expression like number++ also returns a value, so number++ can be used in an arithmetic expression such as

2 * (number++)

The expression number++ first returns the value of the variable number, and then the value of number is increased by 1. For example, consider the following code:

int number = 2;
 int valueProduced = 2 * (number++);
cout << valueProduced << endl;
cout << number << endl;

This code will produce the following output:

4
3

Notice the expression 2 * (number++). When C++ evaluates this expression, it uses the value that number has before it is incremented, not the value that it has after it is incremented. Thus, the value produced by the expression number++ is 2, even though the increment operator changes the value of number to 3. This may seem strange, but sometimes it is just what you want. And, as you are about to see, if you want an expression that behaves differently, you can have it.

The expression v++ evaluates to the value of the variable v, and then the value of the variable v is incremented by 1. If you reverse the order and place the ++ in front of the variable, the order of these two actions is reversed. The expression ++v first increments the value of the variable v and then returns this increased value of v. For example, consider the following code:

int number = 2;
 int valueProduced = 2 * (++number);
cout << valueProduced << endl;
cout << number << endl;

This code is the same as the previous piece of code except that the ++ is before the variable, so this code produces the following output:

6
3

Notice that the two increment operators number++ and ++number have the same effect on a variable number: They both increase the value of number by 1. But the two expressions evaluate to different values. Remember, if the ++ is before the variable, then the incrementing is done before the value is returned; if the ++ is after the variable, then the incrementing is done after the value is returned.

The program in Display 3.10 uses the increment operator in a while loop to count the number of times the loop body is repeated. One of the main uses of the increment operator is to control the iteration of loops in ways similar to what is done in Display 3.10.

Display 3.10 The Increment Operator as an Expression

 1	   //Calorie-counting program.
 2	  #include <iostream>
 3	using namespace std;
 4	
 5	int main( )
 6	{
 7		int numberOfItems, count,
 8			caloriesForItem, totalCalories;
 9
10		  cout << "How many items did you eat today? ";
11		  cin >> numberOfItems;
12
13		  totalCalories = 0;
14		  count = 1;
15		  cout << "Enter the number of calories in each of the\n"
16			   << numberOfItems << " items eaten:\n";
17
18		  while (count++ <= numberOfItems)
19		  {
20			  cin >> caloriesForItem;
21			  totalCalories = totalCalories
22							  + caloriesForItem;
23		  }
24
25		  cout << "Total calories eaten today = "
26			   << totalCalories << endl;
27		  return 0;
28	  }
29

Sample Dialogue

How many items did you eat today?
7
Enter the number of calories in each of the
7 items eaten:
300 60 1200 600 150 1 120
Total calories eaten today = 2431

Everything we said about the increment operator applies to the decrement operator as well, except that the value of the variable is decreased by 1 rather than increased by 1. For example, consider the following code:

int number = 8;
 int valueProduced = number−−;
cout << valueProduced << endl;
cout << number << endl;

This produces the output

8
7

On the other hand, the code

int number = 8;
 int valueProduced = −−number;
	cout << valueProduced << endl;
	cout << number << endl;

produces the output

7
7

number–– returns the value of number and then decrements number; on the other hand, number first decrements number and then returns the value of number.

You cannot apply the increment and decrement operators to anything other than a single variable. Expressions such as (x + y)++, ––(x + y), 5++, and so forth are all illegal in C++.

Self-Test Exercises

  1. What is the output of the following (when embedded in a complete program)?

    int count = 3;
     while (count−− > 0)
    	cout << count << " ";
  2. What is the output of the following (when embedded in a complete program)?

    int count = 3;
     while (−−count > 0)
    	cout << count << " ";
  3. What is the output of the following (when embedded in a complete program)?

    int n = 1;
     do
    	 cout << n << " ";
     while
     (n++ <= 3);
  4. What is the output of the following (when embedded in a complete program)?

    int n = 1;
     do
    	 cout << n << " ";
     while
     (++n <= 3);

The for Statement

The while statement and the do-while statement are all the loop mechanisms you absolutely need. In fact, the while statement alone is enough. However, there is one sort of loop that is so common that C++ includes a special statement for this. In performing numeric calculations, it is common to do a calculation with the number 1, then with the number 2, then with 3, and so forth, until some last value is reached. For example, to add 1 through 10, you want the computer to perform the following statement ten times, with the value of n equal to 1 the first time and with n increased by 1 each subsequent time:

sum = sum + n;

The following is one way to accomplish this with a while statement:

sum = 0;
n = 1;
 while (n <= 10)
{
	sum = sum + n;
	n++;
}

Although a while loop will do here, this sort of situation is just what the for statement (also called the for loop) was designed for. The following for statement will neatly accomplish the same task:

sum = 0;
 for (n = 1; n <= 10; n++)
	sum = sum + n;

Let’s look at this for statement piece by piece.

First, notice that the while loop version and the for loop version are made by putting together the same pieces: They both start with an assignment statement that sets the variable sum equal to 0. In both cases, this assignment statement for sum is placed before the loop statement itself begins. The loop statements themselves are both made from the pieces.

n = 1; n <= 10; n++ and sum = sum + n;

These pieces serve the same function in the for statement as they do in the while statement. The for statement is simply a more compact way of saying the same thing. Although other things are possible, we will only use for statements to perform loops controlled by one variable. In our example, that would be the variable n. With the equivalence of the previous two loops to guide us, let’s go over the rules for writing a for statement.

A for statement begins with the keyword for followed by three things in parentheses that tell the computer what to do with the controlling variable. The beginning of a for statement looks like the following:

for (Initialization_Action; Boolean_Expression; Update_Action)

The first expression tells how the variable is initialized, the second gives a Boolean expression that is used to check for when the loop should end, and the last expression tells how the loop control variable is updated after each iteration of the loop body. For example, the above for loop begins

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

The n = 1 says that n is initialized to 1. The n <= 10 says the loop will continue to iterate the body as long as n is less than or equal to 10. The last expression, n++, says that n is incremented by 1 after each time the loop body is executed.

The three expressions at the start of a for statement are separated by two, and only two, semicolons. Do not succumb to the temptation to place a semicolon after the third expression. (The technical explanation is that these three things are expressions, not statements, and so do not require a semicolon at the end.)

Display 3.11 shows the syntax of a for statement and also describes the action of the for statement by showing how it translates into an equivalent while statement. Notice that in a for statement, as in the corresponding while statement, the stopping condition is tested before the first loop iteration. Thus, it is possible to have a for loop whose body is executed zero times.

Display 3.11 The for Statement

for Statement
SYNTAX
1	 for (Initialization_Action; Boolean_Expression; Update_Action)
2		 Body_Statement
EXAMPLE
1	 for (number = 100; number >= 0; number−−)
2		 cout << number
3			   << " bottles of beer on the shelf.\n";

Equivalent while Loop

EQUIVALENT SYNTAX

1	Initialization_Action;
2	 while (Boolean_Expression)
3	 {
4		 Body_Statement
5		 Update_Action;
6	 }

EQUIVALENT EXAMPLE

1	number = 100;
2	 while (number >= 0)
3	 {
4		 cout << number
5			  << " bottles of beer on the shelf.\n";
6		 number−−;
7	 }

Output

100 bottles of beer on the shelf.
99 bottles of beer on the shelf.
				.
				.
				.
0 bottles of beer on the shelf.

Display 3.12 shows a sample for statement embedded in a complete (although very simple) program. The for statement in Display 3.12 is similar to the one discussed above, but it has one new feature. The variable n is declared when it is initialized to 1. So, the declaration of n is inside the for statement. The initializing action in a for statement can include a variable declaration. When a variable is used only within the for statement, this can be the best place to declare the variable. However, if the variable is also used outside of the for statement, then it is best to declare the variable outside of the for statement.

Display 3.12 A for Statement

An illustration shows a code segment of “for” loop.

Output

The sum of the numbers 1 to 10 is 55

The ANSI C++ standard requires that a C++ compiler claiming compliance with the standard treat any declaration in a for loop initializer as if it were local to the body of the loop. Earlier C++ compilers did not do this. You should determine how your compiler treats variables declared in a for loop initializer. In the interests of portability, you should not write code that depends on this behavior. The ANSI C++ standard requires that variables declared in the initialization expression of a for loop be local to the block of the for loop. The next generation of C++ compilers will likely comply with this rule, but compilers presently available may or may not comply.

Our description of a for statement was a bit less general than what is allowed. The three expressions at the start of a for statement may be any C++ expressions and therefore they may involve more (or even fewer!) than one variable. However, our for statements will always use only a single variable in these expressions.

In the for statement in Display 3.12, the body was the simple assignment statement

sum = sum + n;

The body may be any statement at all. In particular, the body may be a compound statement. This allows us to place several statements in the body of a for loop, as shown in Display 3.13.

Display 3.13 for Loop with a Multistatement Body

SYNTAX

An illustration shows a code segment of “for” loop with multistatement body.

EXAMPLE

	   for (int number = 100; number >= 0; number--)
	{
		cout << number
			 << " bottles of beer on the shelf.\n";
		  if (number > 0)
			cout << "Take one down and pass it around.\n";
	}

Thus far, you have seen for loops that increase the loop control variable by 1 after each loop iteration, and you have seen for loops that decrease the loop control variable by 1 after each loop iteration. There are many more possible kinds of variable updates. The variable can be incremented or decremented by 2 or 3 or any number. If the variable is of type double, it can be incremented or decremented by a fractional amount. All of the following are legitimate for loops:

int n;
 for (n = 1; n <= 10; n = n + 2)
	cout << "n is now equal to " << n << endl;
for (n = 0; n > −100; n = n − 7)
	cout << "n is now equal to " << n << endl;
for (double size = 0.75; size <= 5; size = size + 0.05)
	cout << "size is now equal to " << size << endl;

The update need not even be an addition or subtraction. Moreover, the initialization need not simply set a variable equal to a constant. You can initialize and change a loop control variable in just about any way you wish. For example, the following demonstrates one more way to start a for loop:

for (double x = pow(y, 3.0); x > 2.0; x = sqrt(x))
	cout << "x is now equal to " << x << endl;

What Kind of Loop to Use

When designing a loop, the choice of which C++ loop statement to use is best postponed to the end of the design process. First design the loop using pseudocode, then translate the pseudocode into C++ code. At that point it will be easy to decide what type of C++ loop statement to use.

If the loop involves a numeric calculation using a variable that is changed by equal amounts each time through the loop, use a for loop. In fact, whenever you have a loop for a numeric calculation, you should consider using a for loop. It will not always be suitable, but it is often the clearest and easiest loop to use for numeric calculations.

In most other cases, you should use a while loop or a do-while loop; it is fairly easy to decide which of these two to use. If you want to insist that the loop body will be executed at least once, you may use a do-while loop. If there are circumstances for which the loop body should not be executed at all, then you must use a while loop. A common situation that demands a while loop is reading input when there is a possibility of no data at all. For example, if the program reads in a list of exam scores, there may be cases of students who have taken no exams, and hence the input loop may be faced with an empty list. This calls for a while loop.

Self-Test Exercises

  1. What is the output of the following (when embedded in a complete program)?

    for (int count = 1; count < 5; count++)
    	cout << (2 * count) << " ";
  2. What is the output of the following (when embedded in a complete program)?

    for (int n = 10; n > 0; n = n - 2)
    {
    	cout << "Hello ";
    	cout << n << endl;
    }
  3. What is the output of the following (when embedded in a complete program)?

    for (double sample = 2; sample > 0; sample = sample − 0.5)
    	cout << sample << " ";
  4. For each of the following situations, tell which type of loop (while, do-while, or for) would work best:

    1. Summing a series, such as 1/2 + 1/3 + 1/4 + 1/5 + … + 1/10.

    2. Reading in the list of exam scores for one student.

    3. Reading in the number of days of sick leave taken by employees in a department.

    4. Testing a function to see how it performs for different values of its arguments.

  5. Rewrite the following loops as for loops.

    1. int i = 1;
      	 while (i <= 10)
      	  {
      			if (i < 5 && i != 2)
      			 cout << 'X';
      		  i++;
      	  }
    2. int i = 1;
       while (i <= 10)
      	  {
      			cout << 'X';
      			i = i + 3;
      	  }
    3. long m = 100;
       do {
      			cout << 'X';
      			m = m + 100;
      	  }
       while (m < 1000);
  6. What is the output of this loop? Identify the connection between the value of n and the value of the variable log.

    int n = 1024;
     int log = 0;
     for (int i = 1; i < n; i = i * 2)
    	log++;
    cout << n << " " << log << endl;
  7. What is the output of this loop? Comment on the code.

    int n = 1024;
     int log = 0;
     for (int i = 1; i < n; i = i * 2);
    	log++;
    cout << n << " " << log << endl;
  8. What is the output of this loop? Comment on the code.

    int n = 1024;
     int log = 0;
     for (int i = 0; i < n; i = i * 2)
    	log++;
    cout << n << " " << log << endl;

The break Statement

You have already used the break statement as a way of ending a switch statement. This same break statement can be used to exit a loop. Sometimes you want to exit a loop before it ends in the normal way. For example, the loop might contain a check for improper input and if some improper input is encountered, then you may want to simply end the loop. The code in Display 3.14 reads a list of negative numbers and computes their sum as the value of the variable sum. The loop ends normally provided the user types in ten negative numbers. If the user forgets a minus sign, the computation is ruined and the loop ends immediately when the break statement is executed.

Display 3.14 A break Statement in a Loop

An illustration shows a code segment of “break” statement in a loop.

Sample Dialogue

Enter 10 negative numbers:
−1 −2 −3 4 −5 −6 −7 −8 −9 −10
ERROR: positive number or zero was entered as the
4th number! Input ends with the 4th number.
4th number was not added in.
−6 is the sum of the first 3 numbers.

Self-Test Exercises

  1. What is the output of the following (when embedded in a complete program)?

    int n = 5;
     while (−−n > 0)
    {
    	if (n == 2)
     		   break;
    	cout << n << " ";
    }
    cout << "End of Loop.";
  2. What is the output of the following (when embedded in a complete program)?

    int n = 5;
     while (−−n > 0)
    {
     	   if (n == 2)
    		exit(0);
    	cout << n << " ";
    }
    cout << "End of Loop.";
  3. What does a break statement do? Where is it legal to put a break statement?