14. For Loops
The purpose of a for loop is to repeat one or more statements. A for loop is a counter-controlled loop. The major difference between for and do loops is the location of the test. A counter-controlled while loop is functionally equivalent to (i.e., works the same as) a for loop.
General Form
The general form of a for loop is as follows:
for (initialization; test; adjustment)
{
loop-body
}
Some important points:
- The word
foris a keyword. - The statements to repeat should be placed within the braces indicating the loop body.
- Initialization – used to assign an initial value to the loop counter.
- Test – a Boolean expression or compound condition, as needed.
- Adjustment – used to change the value of the loop counter (often by adding one to it).
- The parentheses and semicolons are required.
- If the loop body consists of multiple statements, the braces are required. If the loop body is only a single statement, the braces are optional.
Do not put a semicolon after the closing parenthesis at the top of the loop. If a semicolon is placed there accidentally, the loop will not work correctly.
The statements in the loop body should be indented and left aligned to visually emphasize they are in the loop.
How a For Loop Works
The steps taken when a for loop executes are as follows:
- The loop’s initialization is executed, giving the loop counter its initial value.
- The test is performed.
If the test evaluates to
true:- The statements in the loop body are executed.
- The loop’s adjustment is executed giving the loop counter its next value.
- Go back to Step 2.
- If the test evaluates to
false, execution of the loop ends then execution passes to the first executable statement following theforloop.
Given how a for loop works, here are a few additional points:
- The keyword
fordoes not perform any action. It only indicates the beginning of the loop. - The initialization part of the loop executes first and only once.
- The test should evaluate to
trueuntil the counter reaches the value specified in the test at which repetition should stop. - It is rare for the result of the test’s first evaluation to be
falseas for loops are usually set up to count from a starting value to an ending value without question. - As long as the test evaluates to
true, the statements in the loop body will repeat. - The test is referred to as a pretest because it is first performed before the loop body statements execute.
- The loop counter’s value should be completely controlled by the initialization and adjustment parts of the loop.
Example – Counting By One
The example that follows provides a for loop version of the code used to display the word “Hello” three times. Step through the code following the steps above:
int counter;
for (counter = 0; counter < 3; counter++) {
std::cout << "Hello" << std::endl;
}
Since the initialization part of the for loop assigns a value of zero to the counter, the declaration does not do so. It would not hurt to initialize the variable in its declaration, but the step is unnecessary.
The loop body consists of a single statement, so the braces are optional. If removed, the code still works as expected. The single statement loop body should still be indented.
Compare the sequence of steps in this example to those in the “Loop Body Statements Always Execute” example in the While Loops section. As can be seen, the steps are identical. A for loop works the same as a counter-controlled while loop.
The postincrement operator is used in the adjustment. Three acceptable alternatives are as follows:
++counter
counter = counter + 1
counter += 1
Any one of the four choices is fine. Note that no semicolon appears in any option.
Example – Counting by a Value Other Than One
A for loop does not require only adjusting the counter by one or initializing the counter to zero:
int counter;
for (counter = 4; counter < 40; counter += 4) {
std::cout << "Current value = " << counter << std::endl;
}
The code displays multiples of four. In this version, however, the program controls how many values are displayed, not the user. As can be seen, the counter is initialized to four, not zero, and the counter is increased by four, not one.
The loop counter has two roles in this example. It is being used, as expected, to end the loop’s repetition when it should stop. The counter is also used in the cout statement to display the multiples of four. What is the largest value displayed?