11C. Planning For-Loops

We have seen that a good way to plan a while-loop is to do a pre-simulation. Although that can also be helpful with a for-loop, you usually think about a for-loop differently.

A well written for-loop does its body for each member of a sequence of values. For example, assuming that body does not change k,

  for(int k = 1; k <= 3; k++)
  {
    body
  }
is equivalent to
  k = 1;
  body
  k = 2;
  body
  k = 3;
  body
which does body for each member k of sequence [1, 2, 3].

Suppose you would like to compute the sum 12 + 22 + 32 + … + n2. A for loop makes that simple:

  initialize sum = 0
  For each k in sequence [1,2,...,n]
    add k2 to sum
The same idea can be used to find the sum of the squares of any sequence of numbers x1, x2, …, xn, as long as you can think of how to write a for-loop heading that walks through that sequence. For example, here is a C++ definition of a function that returns the 12 + 32 + 52 + … + n 2, assuming that n is an odd positive integer.

  // sumsqOdd returns 12 + 32 + 52 + … + n2.
  //
  // Requirement: n is odd.

  int sumsqOdd(const int n)
  {
    int sum = 0;
    for(int k = 1; k <= n; k += 2)
    {
      sum = sum + k*k;
    }
    return sum;
  }

A for-loop simplifies the thought process by breaking it into two independent parts: (1) decide what sequence S of values you want to look at, and (2) decide what you want to do for each member of sequence S.


Exercises

  1. Write a C++ definition of isPerfect, but this time use a for-loop. Answer