Source of sum_odd_positives.cpp


  1: //sum_odd_positives.cpp
  2: //Sums the odd integers from 1 to a value input by the user.
  3: //Illustrates a variable local to a block.

  5: #include <iostream>
  6: using namespace std;

  8: int main()
  9: {
 10:     cout << "\nThis program finds the value of the sum of all odd "
 11:         "positive integers from 1\nto an integer input by the user "
 12:         "(inclusive, if the integer input is odd).\nTerminate by "
 13:         "entering a non-positive integer.\n\n";

 15:     int sum = 100 + 20 + 3;  //This is the first "sum".
 16:     cout << "Outer (fixed) sum: " << sum << "\n\n";

 18:     int j;
 19:     cout << "Enter an integer: ";
 20:     cin >> j;  cin.ignore(80, '\n');
 21:     while (j > 0)
 22:     {
 23:         int sum = 0;  //This is the second "sum".
 24:         int i = j;
 25:         while (i > 0)
 26:         {
 27:             if (i % 2  ==  1)
 28:                 sum = sum + i;  //Which "sum" is this, and why?
 29:             --i;
 30:         }
 31:         cout << "Inner (varying) sum of odd integers, "
 32:             "from 1 to " << j << " is " << sum << ".\n";
 33:         cout << "\nEnter another integer: ";
 34:         cin >> j;  cin.ignore(80, '\n');
 35:     }

 37:     cout << "\nOuter (fixed) sum: " << sum << endl;
 38:     cout << endl;
 39: }