O'Reilly logo

Beginning Mac OS® X Programming by Drew McCormack, Michael Trent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required