9F. While-Loops

A C++ while-loop is similar 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 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

Notice that, if the condition in a while-loop heading is false the first time it is tested, the body is not done at all. Keep that in mind. Usually, you find that the ability to do the loop body no times is what you want. But avoid doing anything in the body that must be done, no matter what.


Example: computing 1 + 2 + … + n

Loops are one of two fundamental ways to solve problems that require repetition. (The other is recursion, which we will see later.)

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 can keep a running sum. You also need to keep track of where you are in the process; that is, you need to know how much of the sum you have already computed. That suggests using 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;
  }

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

  4. 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