// Oldham, Jeffrey D. // 1999 Sep 07 // CS 1320 // // Program to Add Many Integers // input <- Prompted by the program, the user types zero or more integers. // output-> The integers' sum is printed. // We are now working on when to stop the while loop. We want to stop // the while loop when there is no more input. We want an expression // that will yield true when an integer is typed and will yield false // when no integer is typed. The expression "cin >> second_integer" // does just that! The only problem is that it is in the middle of // the loop body. // Let's unroll the loop so we can use "cin >> second_integer" as the // test. The statements the loop performs look like: // cout << "Please enter an integer: "; // first loop iteration // cin >> second_integer; // sum += second_integer; // cout << "Please enter an integer: "; // second loop iteration // cin >> second_integer; // sum += second_integer; // ... // more loop iterations // The loop below executes exactly the same statements. // Try testing the program by typing inputs of zero integers, one // integer, two integers, and three integers. #include int main() { int second_integer; int sum = 0; // The sum of no integers is zero. cout << "Please enter an integer: "; while (cin >> second_integer) { sum += second_integer; // Add the integer to the sum. cout << "Please enter an integer: "; } cout << "The sum is " << sum << ".\n"; return 0; }