6.7. Loops

If there is one thing that computers are good at, it is repetitive tasks. C has various constructs for repeating a block of code, which is known as looping. Looping is also a form of branching because at the end of a loop, execution can either continue or return to the beginning of the loop.

The simplest form of loop in C is the while loop. while keeps looping until a condition is no longer true. The condition is tested whenever execution returns to the beginning of the loop after each iteration. A while loop takes this form:

while ( condition ) {
    ...
}

The order of events in a while loop goes as follows: When the while is encountered, the condition in parentheses is tested. If it is true, the block of code between the braces after the while is executed, and execution jumps from the closing brace back to the while statement, where the condition is tested again. This continues until the condition evaluates to zero (false), at which point execution jumps to immediately after the last brace and continues.

Here is a concrete example of a while loop:

int i = 0;
while ( i < 2 ) {
    printf("%d\n", i);
    ++i;
}

The execution of this example code proceeds as follows:

  1. When the while is first encountered, i is equal to 0, which is less than 2, so execution jumps to the code in the braces.

  2. The printf statement is executed, printing 0 to standard output.

  3. i is then incremented to 1.

  4. At the closing brace, execution jumps back to the while, and again performs the test. Since i is 1, and this ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.