It turns out that loops which continue a given number of times are very common in programs. We can write them using the while construction, but it is rather fiddly, and we have to remember to set the initial value for the control variable, update it and perform the test in the right places. For this reason the C language has a special construction specially for repeating code a given number of times.

The for loop combines the initialization of the control variable, the test and the increment into a single construction. It is described as:

for ( init ; con ; update )
statement ;

The initialization statement (init) is performed once when the for loop starts. In our loop we use it to set the variable i (I like to use the variable name i for control variables) to zero.

The condition (con) is checked before the loop is performed and each time a loop is completed. This means that if the condition is false at the start the loop is never performed. In this respect the for loop is a bit like the while construction we saw above. When the condition becomes false the for loop is complete.

The update is performed when the loop has been completed, just before the condition is tested.

The statement is performed each time round the for loop.

When the loop is finished the control variable is left containing the value which caused it to stop.

One thing worth mentioning is the way that I have counted starting with i at 0 and continuing while i is less than the limit. There is no requirement to do this, in that the following would work just as well:

for ( i = 1 ; i <= 4 ; i++ ) 

This is just as valid as the code I used, the control variable would start at 1 and count up. When the loop finishes i would contain 5. I tend to start counting at 0 because I often used "for loops" to manipulate items in arrays. These are numbered starting at 0, so I make the control variable start at 0.

Note that the three components of the for loop do not have to do with the management of a control variable if you don't want to do that. For example if your for loop was waiting for an event the condition could be testing whether the event is true or not. We will see examples of fancy for loops in some of the exercises.

If you run the program in the CPIC you will see how it counts up to 4 and then the loop ends.