Next: Example while loop: Table Up: The while statement Previous: Example while loop: Printing

Example while loop: Summing Arithmetic Progression

The following portion of C++ uses a while statement to produce the sum 1+2+3+ ...+n, where a value for n is entered by the user. It assumes that integer variables i, n and sum have been declared:

cout << "Enter a value for n: ";
cin >> n;
sum = 0;
i = 1;
while (i <= n)
  {
    sum += i;
    i++;
  }
cout << "The sum of the first " << n
     << " numbers is " << sum << endl;
Download program.
There are several important points to note here:
  1. The condition i <= n requires that i and n must have values before the while loop is executed. Hence the initialisation of i to 1 and the entry of a value for n before the while statement.
  2. It is possible that a while loop may not be executed at all. For example if the user entered a value 0 for n then the condition i <= n would be false initially and the statement part of the while loop would never be entered.
  3. When accumulating the sum of a sequence the variable in which we accumulate the sum must be initialised to zero before commencing the summation. Note also that if the user entered a value for n that was less than 1 then the initialisation of sum would mean that the program would return zero as the accumulated total -- if n is zero this is certainly a sensible value.
  4. There is no unique way to write a while statement for a particular loop. For example the loop in this example could have been written as follows:
    i = 0;
    while (i < n)
      {
        i = i + 1;
        sum = sum + i;
      }
    
    without changing the result.



Next: Example while loop: Table Up: The while statement Previous: Example while loop: Printing