which is ctr = 1;, executes. The startExpression is executed only once in any for loop.
The testExpression is then tested. In this example, the testExpression is ctr<= 5;. If it
is true—and it will be true the first time in this code—the body of the for loop executes. When the
body of the loop finishes, the countExpression is executed (ctr is incremented).
Tip
As you can see, indenting the body of a for loop helps separate the body of the loop
from the rest of the program, making the loop more readable. (The same is true for the
other kinds of loops, such as do-while loops.)
That’s a lot to absorb in one full swoop, even in one paragraph. Let’s make it easy. Follow the line in
Figure 15.1, which shows the order in which for executes. While following the line, reread the
preceding paragraph. It should then make more sense to you.
FIGURE 15.1 Following the order of for.
Note
The for loop’s format is strange because of the embedded semicolons that are
required. It is true that semicolons go only at the end of executable statements, but
statements inside for loops are executable. For instance, the initial expression, ctr
= 1;, is completed before the loop begins, as Figure 15.1 shows.
Here is the very same loop written as a while statement:
Click here to view code image
ctr = 1;
while (ctr <= 5)
{
printf("Counter is at %d.\n", ctr);
ctr++;