While

Loops #

One of the most powerful things that a computer can do is loop. This gives us the power to run a piece of code more than once, and we only have to write it once. Any time you find yourself writing more than a few lines of code over and over in a sequence, see if you can reduce it by using a loop.

We are going to start off by using while loops, and the easiest way to get to know them is to start counting with them.

While loops #

A while loop is similar to an if statement without the else part, except it loops.

while(1)
{
    printf("Hello!");
}

The above code will keep repeating forever, like an if statement the 1 is evaluated as true, and the code block immediately following it is executed. Where the while loop differs is that it then returns to the start again and checks to see if it is still true. If it is, it runs the block of code again, if not, it jumps down to the next line of code after it.

As you may have guessed, the above loop is infinite, it will repeat forever as 1 is always true. In order to control the iterations of our loop we need to use a variable. Historically the variable i has been used, and who are we to break with tradition?

int i = 0;

while(i < 10)
{
    printf("%d",i);
    i++;
}

This code has an example of a while loop that starts at 0, checks to see if i < 10, if it is, it executes the code block which prints out i and increments (adds one to) it. It will print out the numbers from 0 to 9 inclusive.

We can manipulate the range of values output by this loop just by changing the initial value of i, the value the condition tests against, and the amount by which we increase or decrease i.

For example if I want to make the above loop count down from 9 to 0 I would do the following:

int i = 9;

while(i >= 0)
{
    printf("%d",i);
    i--;
}

Note that I changed the starting value, the condition is not checking to see if it is greater than zero, and I am decrementing (subtracting one from) the value.