5.6.3.1. While-Loops

A while-loop is a statement of 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. For example,

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

Watch out: semicolons

Do not write a semicolon after the condition. 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(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 result is unnecessary. It is just the same as sum. So the following does the job.

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


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 them and the loop. Initializing control variables in the wrong place is a common mistake.

  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 a common mistake.

  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.



Standards for loops

Only one loop per function

The standards require that a single function cannot contain more than one loop. But a function can call other functions that contain loops. If you seem to need more than one loop, move at least one of the loops into a separate function.

Code that is done at the end of the loop should be written after the loop.

The standards require that code that is done when a loop is finished should be written after the loop, not in the loop body. That seems to be common sense, but beginners frequently violate that rule. Click on the link to see an example of what to avoid.

Do not simulate nested loops

Beginners often create a complicated loop that is really simulating more than one loop. See here


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 an integer that is not 0 then you can compute xn by initializing p = 1 and then multiplying p by x a total of n times. Write C++ statements that accomplish that, leaving p = xn. Answer

  3. Suppose that n is a positive integer. A proper divisior of n is an integer k where 0 < k < n and k is a divisor (or factor) of n. For example, 2 is a proper divisor of 6. Say that n is perfect if n is equal to the sum of all of its proper divisors. For example, 6 is perfect because the proper divisors of 6 are 1, 2 and 3 and 1 + 2 + 3 = 6.

    Write C++ statements that set variable sum equal to the sum of the proper divisors of n (where variable n has already been given a value) and sets variable perf to true if n is perfect, false if not.

    Answer

  4. What is nested-loop simulation, and why shouldn't you use it? Answer

  5. The following has a while-loop whose body is hidden from you.

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