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++;
}
for loop.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.
for loop with a negative change in the βINCREMENTORβ.Checkpoint 10.4.2.
- 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 of activities on this page.
