9A. For-Loops


For-loops

If A, B and C are expressions then

  for(A; B; C)
  {
     body
  }
is equivalent to
  {
    A;
    while(B)
    {
       body
       C;
    }
  }
For example,
  for(i = 0; i < 5; i++)
  {
     printf"%d\n", i);
  }
is the same as
  {
    i = 0;
    while(i < 5)
    {
       printf("%d\n", i);
       i++;
    }
  }

An advantage of a for-loop is that the initialization, update and test of one of the control variables are all together in one place, so it is easier to see what the loop is doing and it is less likely that you will make a mistake.


Details on for-loops

Declaring a variable in a for-loop heading

The first part of a for-loop heading can create a new variable. But a variable created there can only be used in the for-loop heading and body. For example
  for(int i = 0; i < 5; i++)
  {
     printf("%d\n", i);
  }
creates variable i that can only be used in this for-loop. You are not allowed to say
  for(int i = 0; i < 5; i++)
  {
     printf("%d\n", i);
  }
  printf("%d\n", i);
since that tries to use i outside of the for-loop.

If you want to use the loop control variable after the loop, declare it before the loop..


Omitting part of a for-loop heading

Every for-loop heading has exactly two semicolons. But you can omit any (or all) of the three parts that are separated by semicolons.
  • If the first part is empty, no initialization is done.

  • If the second part is empty, it is assumed to be true, so the loop keeps going until stopped some other way.

  • If the third part is empty, no update is added to the end of the body.

For example,
  for(; k < n; k++)
  {
    ...
  }
assumes that k has already been initialized.

Watch out: semicolons

Be careful not to end the heading of a for-loop with a semicolon.
  int n;
  for(n = 0; n < 4; n++);
  {
    printf("%i\n", n);
  }
writes
  4
because the body of the for-loop is an empty statement. If n had been created in the for-loop heading, the above code would not compile because the printf line is not part of the loop body, making n out of scope.


Summary

A for-loop allows you to put all of the code to manage one loop control variable in one line. That shortens loops and makes them easier to understand. It also takes away opportunities to make mistakes, since you cannot forget to do initialization or update of the variable controlled by the for-loop heading.


Exercises

  1. Solve question 1 from page 8A, but this time use a for-loop. Answer

  2. Solve question 2 from page 8A, but this time use a for-loop. Answer

  3. Solve question 1 from page 8B, but this time use a for-loop. Answer