Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 10.4 for loops

The loops we have written so far have a number of elements in common. All of them start by initializing a variable; they have a test, or condition, that depends on that variable; and inside the loop they do something to that variable, like increment it.
This type of loop is so common that there is an alternate loop statement, called for, that expresses it more concisely. The general syntax looks like this:
for (INITIALIZER; CONDITION; INCREMENTOR) {
  BODY
}
This statement is exactly equivalent to
INITIALIZER;
while (CONDITION) {
  BODY
  INCREMENTOR
}
except that it is more concise and, since it puts all the loop-related statements in one place, it is easier to read. For example:
int i;
for (i = 0; i < 4; i++) {
  cout << count[i] << endl;
}
is equivalent to
int i = 0;
while (i < 4) {
  cout << count[i] << endl;
  i++;
}
Listing 10.4.1. Run this active code, which uses a for loop.
Listing 10.4.2. Run this active code, which uses a while loop.
The INCREMENTOR does not have to do ++ to a variable. It can be any statement you like, but it should do something to modify the looping variable. If you want to count down, you could use i-- as your INCREMENTOR.
Listing 10.4.3. Run this active code, which uses a for loop with a negative change in the “INCREMENTOR”.

Checkpoint 10.4.1.

Checkpoint 10.4.2.

Where are the incrementors in for loops and while?
  • in the BODIES of both loops
  • Incorrect!
  • in the BODY of a for loop, and in the statement of a while loop
  • Incorrect!
  • in the statement of a for loop, and in the BODY of a while loop
  • Correct!
  • in the statements of both loops
  • Incorrect!

Checkpoint 10.4.3.

Construct the half_life() function that prints the first num half lives of the initial amount.
You have attempted 1 of 7 activities on this page.