Loops

When you need to repeat a sequence of statements in a program, you should use a loop. If the description of some portion of your program has phrases like:

A for loop has the following structure:

for (start_expression; continue_condition; update_statement)
{
statements
}

The start_expression is normally an initialization of some variable used in the loop. More than one statement can be written here, separated by commas.

The continue_condition will determine whether the statements in the for loop should be executed. If it is false, the program will continue its execution after the last statement of the for loop.

The update statement usually increments or decrements one or more variables initialized in the start expression (and checked in the continue condition.)

The following are the steps involved in execution of a for loop.

  1. start expression
  2. continue expression
  3. if continue expression is true, execute statements; else, exit loop
  4. update statement
  5. go to step 2

Here's a basic example of a for loop:

for (i = 0; i < 10; i++)
   sum = sum + i;

A while loop is equivalent to a for loop in that they are completely interchangeable. You always have the freedom to choose either. Nonetheless, just because you only need to learn one of them doesn't mean that you shouldn't learn both. There are advantages to each of them. You'll develop an intuition about which kind to use as your programming style develops.

A while loop has the following structure:

while (condition)
{
statements
}

The 'condition' part of a while loop construct is equivalent to what I called the 'continue-condition' above in the for loop. See the page on conditions for a more detailed description.

The while loop doesn't have the start expression or update statement of the for loop. If you use a while loop, you need to make sure that you write code for these steps, if they're necessary.

The following are the steps of a while loop:

  1. test the condition: if true, go to 2; else go to 4
  2. execute statements
  3. go to 1
  4. continue C program following loop

 

In descriptions above of the for and while loops, it was assumed that there would be more than one statement in the loop. In this case, curly brackets ( { , } ) are necessary to group the statements. If the loop has only one statement, the brackets are not necessary. However, it doesn't hurt to always use them.