Previous Table of Contents Next


3.4.5. for Loops

The for loop is usually used to step some variable through a sequence of values. (It is analogous to the for/to/do loop in Pascal, to the do loop in Fortran, and to the for/to/step loop in BASIC.) The syntax is the most general of C’s loops:

for( expr1 ; expr2 ; expr3 )
         statement

expr1 is the initialization expression; it is executed exactly once, before execution of the loop begins. expr2 is the test expression. Like the controlling expression in a while loop, its value is tested before each trip through the body of the loop, and a trip is made only if the expression evaluates to nonzero. (If the expression is initially false, no trips at all are made.) expr3 is the increment expression. It is executed after each trip through the loop, before testing for another trip. Like the expressions in expression statements, expr1 and expr3 must have side effects in order to be useful.

For example, the elementary for loop

for(i = 0; i < 10; i++)
        printf(“%d\n”, i);

initializes i to 0, loops as long as i is less than 10, and increments i by one after each trip through the loop. Ten values of i are therefore printed, from 0 to 9, inclusive.

Because the three expressions that control a for loop are arbitrary, it is possible to arrange for any arithmetic or geometric sequence (or even, as we see in section 3.7.6, for nonnumeric sequences). Here are several more examples:

Loop Range

for(i = 1; i <= 10; i++) 1, 2, 3, … 10
for(i = 2; i <= 10; i += 2) 2, 4, 6, … 10
for(i = 10; i > 0; i--) 10, 9, 8, … 1
for(i = 1; i < 1000; i *= 2) 1, 2, 4, 8, … 512
for(i = 2; i < 100; i = i * i) 2, 4, 16

The form exemplified by

for(i = 0; i < 10; i++)

with an initial value of 0 and a less-than condition, is most common in C, in part because arrays are 0-based.

The three expressions that control a for loop are collected at the top for convenience, not because they or the variables they manipulate are privileged in any way. After exit from the loop, the control variable retains its final value (generally, the first value that caused the test expression to fail). In addition, the control variable may be modified within the loop (although any such modification should be made judiciously, as it can easily lead to impenetrable code).

It is possible to arrange for two (or more) variables to be manipulated by one for loop. Doing so is one use of the comma operator. Here is a simple example:

for(i = 1, j = 10; i < j; i++, j--) …

In this case, expr1 is

i = 1, j = 10

which initializes i to 1 and then initializes j to 10. Similarly, expr3 is

i++, j--

All three of the controlling expressions in a for loop are optional. If the initialization expression (expr1) is omitted, there is no explicit initialization; any variables used in the loop (or the other controlling expressions) have presumably been initialized beforehand. If the increment expression (expr3) is omitted, there is no explicit increment step; any updating of the loop variable(s) is presumably taken care of by code within the body of the loop. Finally, if the test expression (expr2) is omitted, it is simply assumed to be true, and the loop becomes an infinite one (again, unless terminated by abnormal means). If any expressions are omitted, the semicolons remain. Thus, another form of infinite loop in C is

for(;;)
        …

The while and for loops share certain similarities, and it is possible to implement one in terms of the other. The two fragments

                                   expr1;
for( expr1 ; expr2 ; expr3 )         while ( expr2 )
        {                               {
        statements                      statements
        }                               expr3 ;
                                        }

behave almost identically (differing only in the presence of a continue statement; see section 3.4.7). As a general rule, it is appropriate to use a for loop when one or two variables, following an initialize/test/increment pattern, play a prominent role in controlling a loop, and to use a while loop otherwise. (In particular, it is poor style to jam three unrelated expressions into the controlling expressions of a for loop.)

3.4.6. do/while Loops

Finally, C has a test-at-the-bottom loop (analogous to the repeat/until loop of Pascal, but with the sense of the test reversed). The syntax is

do statement
while( expression );

Note the trailing semicolon. In practice, the statement is almost always a brace-enclosed block. Here is an example that generates (in reverse order) the digits in the base-10 representation of the number n:

do       {
        putdigit(n % 10);
        n = n / 10;
         } while(n > 0);

In this example, the at-least-once behavior of the do/while loop is desirable (and distinctly preferable to the behavior of the while loop); it ensures that one digit is generated even if n is initially 0. (The example assumes that the hypothetical function putdigit actually does something with the generated digits and also assumes that n is nonnegative.)


Previous Table of Contents Next