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++;
}
Run the active code below, which uses a for loop.
Run the active code below, which uses a while loop.
- 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!
Q-4: Where are the incrementors in for loops and while?
Construct the half_life() function that prints the first num half lives
of the initial amount.
Run the active code below, which uses a for loop with a negative change in the “INCREMENTOR”.