Loops


Loops allow for some code to be repeated until some condition becomes false, or some counter elapses.

There are two main loops in C. The first is a while loop. This loop repeatedly executes a block of code until some condition becomes false. It is written as while followed by some condition in parentheses, followed by the code to execute in curly brackets. For example a loop that counts downward from 10 to 1 could be written as follows.

  1. int i = 10;
  2. while (i > 0) {
  3. puts("Loop Iteration");
  4. i = i - 1;
  5. }

The second kind of loop is a for loop. Rather than a condition, this loop requires three expressions separated by semicolons ;. These are an initialiser, a condition and an incrementer. The initialiser is performed before the loop starts. The condition is checked before each iteration of the loop. If it is false, the loop is exited. The incrementer is performed at the end of each iteration of the loop. These loops are often used for counting as they are more compact than the while loop.

For example to write a loop that counts up from 0 to 9 we might write the following. In this case the ++ operator increments the variable i.

  1. for (int i = 0; i < 10; i++) {
  2. puts("Loop Iteration");
  3. }