Chapter 8 - The for loop
We have so far met two techniques for iterating over a block of code multiple times: the while loop and the do/while loop. There is a third loop construct in C, however, and it is so often used that a discussion of it cannot reasonably be delayed any longer.
Perhaps the simplest way to look at it is to compare it to a while loop. So let's look at the syntax of a for loop, and then try to construct an equivalent while loop.
for(pre_expression; condition; post_expression) { code; more code; still more code; }
Here is how we would do the same thing in a while loop:
pre_expression; while(condition) { code; more code; still more code; post_expression; }
The for loop makes some kinds of processing more obvious. If we take a while loop like this one, which is intended to perform some set of actions for every integer in the range 0 to 9:
i = 0; while(i < 10) { some_function(i); some_other_function(i); another_function(i); i++; /* as you may remember from the last chapter, this adds 1 to i */ }
we can perhaps see that the mechanism for managing i is a little too spread-out for comfort. The for loop brings everything together into one place:
for(i = 0; i < 10; i++) { some_function(i); some_other_function(i); another_function(i); }
This does look a lot cleaner, despite the rather fearsome loop control statement.
When does the pre-expression happen? Before everything else, and once only.
When does the condition get evaluated? After the pre-expression (because that happens before everything else), but before the loop body (the code between the braces). If, at this point, the condition evaluates to false (0), the loop isn't executed, and control picks up at the first statement to follow the loop body.
When does the post-condition get evaluated? After the loop body, and only if the condition evaluated true (non-0).
So if you want to loop over all the values from 0 to 9 inclusive, here's how you would construct your loop:
int i; for(i = 0; i < 10; i++) { code; more code; } outside;
The body of the loop will be executed ten times, with i having the values 0 through 9 on successive iterations. When control passes outside the loop, i will have the value 10 (because the post-expression makes it 10, which is why it fails the test i < 10).
We are not limited, of course, to merely adding 1 on each iteration of the loop. The post-expression could be any of these, for example:
for(i = 1; i < 100; i += 2) /* first 50 odd numbers */
or
for(i = 100; i > 0; i /= 3) /* 100, 33, 11, 3, 1 */
or even
for(i = 0, j = 100; i < j; i++, j--) /* converge */
The last example illustrates an interesting usage of the comma operator. Two uses, actually. The first lets us assign values to two loop control objects rather than just one, and the second allows us to converge those values towards each other in the post-expression part of the loop control.
That same example also shows that for statements can get a little long. Remember that C allows us to be very free with whitespace. We could have written the loop as follows without changing the meaning:
for(i = 0, j = 100; i < j; i++, j--) /* converge */
That's a lot easier to read. Don't forget that you might one day have to fix an error in your program. At that point, being able to read it becomes a distinct advantage! Don't hesitate to use whitespace to make your code more readable. Whitespace is cheap, and prices are coming down all the time. In 2015, I bought a 32GB USB flash drive for about £25. For a penny, then, we can buy enough storage for about thirteen million space characters. So don't be afraid to use whitespace if it helps make the code more readable.
Summary
In this chapter, you learned about the for loop.
In the next chapter, we will again tackle the thorny problem of output, this time using the printf function.
Progress
Terminology
- precedence
- array
- index
- pointer
- sentinel value
- null character
- null terminator
- string
- sequence, selection, and iteration
Syntax
- comments
- types
- char
- operators
- increment and decrement operators
- ++n n++ --n n--
- assignment operators
- = += -= *= /= %=
- additive operators
- the + operator
- the - operator
- multiplicative operators
- the * operator
- the / operator
- the % operator
- equality and relational operators
- == != < > <= >= !
- logical operators
- the && operator
- the || operator
- address and indirection operators
- the unary * operator
- the unary & operator
- the array subscripting operator []
- miscellaneous operators
- the conditional operator ? :
- the comma operator ,
- the sizeof operator
- increment and decrement operators
- control structures
- if/else
- while
- do/while
- for