10A. While-Loops

While-loops

A C++ while-loop is nearly identical to a Java while-loop. It has the form

  while(condition)
  {
    statements
  }
The statements are called the loop body.

The loop starts by testing whether condition is true (or nonzero). If it is, then the statements in the loop body are performed and the loop goes back to its top, testing the condition again. The loop keeps going until it reaches its top and finds that condition is false (or 0). At that point, the loop ends, and the statement that follows the loop (if any) is performed. For example,

  int n = 0;
  while(n < 4)
  {
    printf("%i\n", n);
    n++;
  }
writes
  0
  1
  2
  3


Example: computing 1 + 2 + … + n

Loops are useful for solving problems that have … in their descriptions, where the number of steps depends on the value of a variable.

A common-sense way to think of a loop is to think how you would solve the problem by hand, and then write the loop to do that. In the case of 1 + 2 + … + n, you might keep a running sum, as in the following function definition. You also need to keep track of where you are in the process, so there are two variables.

  //sum(n) returns 1 + 2 + ... + n

  int sum(const int n)
  {
    int s = 0;       // the running sum
    int i = 0;       // how far we have gone
    while(i < n)
    {
      i = i + 1;
      s = s + i;
    }
    return s;
  }

Hand simulation of a loop

Does the definition of sum work? Let's do a hand simulation of it with n = 3. Variables i and sum change each time the loop body is performed, which makes crossing out and replacing values messy. Let's instead show the values of i and sum in columns, with the most recent value at the bottom of the column. First, do the initializations.

     i    s    n
     0    0    3
Since the test i < n is true, we need to perform the loop body. First it adds 1 to i, giving
     i    s    n
     0    0    3
     1     
Next, it adds i to s. Notice that i is now 1.
     i    s    n
     0    0    3
     1    1
Again, i < n, so the loop body is done again. After doing the entire loop body, we have the following.
     i    s    n
     0    0    3
     1    1
     2    3
Since i is still less than n, we do the loop body again.
     i    s    n
     0    0    3
     1    1
     2    3
     3    6
Now i is not less than n. The loop is finished. Continuing with the next statement, the function returns 6, which is correct since 1 + 2 + 3 = 6.


Watch out: infinite loops

What if the update of i is accidentally omitted from the definition of sum? That is, we write
  //sum(n) returns 1 + 2 + ... + n

  int sum(const int n)
  {
    int s = 0;
    int i = 0;
    while(i < n)
    {
      s = s + i;
    }
    return s;
  }
Doing a hand simulation shows the problem.
     i    s    n
     0    0    3
          0
          0
          0
Since i never changes, the loop does not ever stop. If you suspect that your program is looping forever in Linux, type control-C to stop it. A debugger, such as gdb, is a good way to find the source of an infinite loop. Start gdb, run your program, stop it with control-C, then to a bt command to see the current function frames, most recently entered frame first. Here is an abbreviated sample session with gdb. Symbol ^C means that control-C was pressed.
  $ gdb ./myprogram
  ...
  (gdb) run
  ... ^C
  (gdb) bt
  ...
  (gdb) print n
  ...
  (gdb) quit

Watch out: initializing and updating control variables

Variables that are changed by a loop's body are called the loop's control variables.

It is a good idea to identify which variables you want to be control variables before you write a loop. Then, after writing it, check the following.

  1. Did you initialize each of the control variables? They should be initialized immediately before the loop. Do not put anything in between the initialization and the loop. Initializing control variables in the wrong place is a common source of mistakes.

    What if you omit the initialization? Here is the sum function with initialization of i done but no initialization of s.

      //sum(n) returns 1 + 2 + ... + n
    
      int sum(const int n)
      {
        int s;
        int i = 0;
        while(i < n)
        {
          i = i + 1;
          s = s + i;
        }
        return s;
      }
    
    A hand simulation quickly shows the problem.
         i    s    n
         0    ?    3
              ?
    
    Adding a number to a junk value gives a junk value.

  2. Did you change each control variable in the loop body in an appropriate way? If one of the control variables is not changed by the loop body, something is fishy.

  3. Are you changing or using variables other than the control variables in the loop body? If so, make sure that is what you intend to do. Using the wrong variables is another common source of mistakes.

    Here is an example, a modified version of the sum function.

      //sum(n) returns 1 + 2 + ... + n
    
      int sum(const int n)
      {
        int s = 0;
        int i = 0;
        while(i < n)
        {
          i = i + 1;
          s = s + n;
        }
        return s;
      }
    
    Notice that the loop body uses n. It has no business doing that. A careful hand simulation shows what goes wrong.
         i    s    n
         0    0    3
         1    3
         2    6
         3    9
    
    The result, 9, is not correct.

  4. The condition in the while-loop heading typically asks about at least one of the control variables. If it doesn't, ask yourself whether that is sensible for this loop.


Watch out: semicolons

Do not write a semicolon after the while-loop heading. For example,
  int n = 0;
  while(n < 4);
  {
    printf("%i\n", n);
    n++;
  }
keeps going forever. The problem is that the loop body is a semicolon, which is a do nothing statement.

Watch out: else after while

A while-loop does not have an else part. When it ends, it just ends. So do not write
  while(test)
  {
    loop body
  }
  else 
  {
    do something
  }

Watch out: uninitialized variables

A while-loop can perform its body no times. Look at the following function definition.
  int demo(const int n)
  {
    int result;
    int t   = n;
    int sum = 0;
    while(t > 0)
    {
      sum    = sum + t;
      result = sum;
      t--;
    }
    return result;
  }
Notice that, if n ≤ 0, then the loop body is not performed at all, so no value is ever stored into variable 'result'. The function returns a junk value.

That is easy to fix. A little thought shows that variable 'result' is unnecessary. It is just the same as sum. So the following does the job.

  int demo(const int n)
  {
    int t   = n;
    int sum = 0;
    while(t > 0)
    {
      sum = sum + t;
      t--;
    }
    return sum;
  }



Summary

Use a while-loop for repetition.

Loops provide many opportunities for making mistakes, so you need to approach them in a disciplined way. Hand simulation is an important tool for ensuring that a loop is correct.

We will have more to say later on ways of developing loops that do not involve hours of debugging.


Exercises

  1. Suppose that you have some statements STEP that you want to perform n times. Using a while-loop, write C++ statements to do that. Just write STEP to stand for whatever you want to repeat. Answer

  2. If n is nonnegative integer and x is a nonzero integer then you can compute xn by initializing p = 1 and then multiplying p by x a total of n times. Using a while-loop, write a definition of function power(x, n), which returns xn, where n and x are both integers, assuming n ≥ 0 and x ≠ 0. Answer

  3. The following has a while-loop whose body is hidden from you. The body does not contain a break, return or goto statement.

      while (x != 12)
      {
        …
      }
      y = x;
    
    Suppose you know that the loop eventually stops. What value is stored into y? Answer