Loops

Looping is useful for many things, such as counting, comparing, incrementing (whether it be addition or multiplication) de-incrementing, and also for assignments (assigning all values of an array to a value for example). This section will explain how to use the three types of loops: for, while and do while.

For

#include <stdio.h>

int main()
{
    int x = 0;

    for(x = 0; x < 10; x++)
    {
        printf("%i\n", x);
    }

    return 0;
}

The for loop has three entries, the first being the starting conditions (x = 0, y = 1; for example), the second being the end of loop conditions (in this case when x is no longer less than 10) and the third being the update conditions. In this example, x++ means to take the value of x then increment it by 1 (post-increment). You can have a pre-increment, such as ++x. In this case it doesn't matter which you use. Inside the curly braces are the code that is to be repeated, in this example it just prints the value of x. An interesting note is that all three fields are optional, you can make an infinite loop by using for(;;) for example.

While

#include <stdio.h>

int main()
{
    int x = 0;

    while(x < 10)
    {
        printf("%i\n", x);
        x++;
    }

    return 0;
}

The while loop has just one argument, the condition that, if true, will make the loop repeat. Note the use of x++ in the repetition, or it will be an infinite loop (as x will always be less than 10). This loop produces the same output as the for loop in the previous example, a way of showing that there is often more than one way to do something.

Do While

#include <stdio.h>

int main()
{
    int x = 0;

    do
    {
        printf("%i\n", x);
        x++;
    } while(x < 0);

    printf("%i\n", x);

    return 0;
}

The do while loop is different from the previous two loops in that the for and while loops tested for the termination conditions at the top of the loops. The do while loop tests for the termination condition at the bottom of the loop, in other words the statements inside the loop are always executed at least once. Although this loop is not used as often as the other two it is still used in some cases (I hardly use it, I had to open up The C Programming Language, Second Edition, Brian W. Kernighan and Dennis M. Ritchie for reference).