For loops

In most languages, the for loop is a statement which is performed a fixed number of times.Each time a counter variable is updated. This can be how it is used in C, but it is much more powerful. The statement has the following simple forms:
for (c-var=init-val; c-var<=final-value; c-var++ ) statement
for (c-var=init-val; c-var>=final-value; c-var-- ) statement
or more generally:
for(c-v=init-val;c-v compop final-val;c-v=c-v incop inc) statement
The control variable is first set to the initial value and the controlled statement performed once. This control variable is then repeatedly incremented as defined in the increment clause, followed each time by the controlled statement being executed, until the value of the control variable reaches the final value. Once the final value is reached, the loop terminates after one execution with this value.

Thus

    for (I = 4; I<=10; I++) printf("%d\n",I);
is exactly equivalent to
    I = 4;
	while (I<=10)
	{
		printf("%d\n",I);
		I++;
	}
In the second form, using --, the variable is decreased each time the controlled statement is performed. Note that the comparison operator is now >= rather than <= in the increasing case.

Thus

    for (I = 10; I>= 4; I--) printf("%d\n",I)
is exactly equivalent to
    I = 10;
	while (I>=4)
	{
		printf("%d\n",I);
		I--;
	}
Note that it is very easy to create a non-terminating for loop, if the initial and final values have the wrong relative magnitudes, i.e. if the initial value is greater than the final when the combination <= / ++ is used or less when >= / -- is used.

It is also important not to mix up the combinations of comparison and increment.

The third form of for statement allows a more general updating of the controlled variable, not just steps of one. It can be used either to increase or decrease the value, but the same care is needed to ensure termination.

An example of a for loop

#include <stdio.h>

/* example of use of for loops */

void main()
{
    int I, J;

    for (I = 0; I<=90; I = I + 10) {
        for (J = 0; J<=9; J++) printf("%d",2*(I+J));
        printf("\n");
    }
}
Plain text to compile.

Exercises on this section.


Next - another loop example.

Back to Contents page.