/* * File: sum2.cpp * Author: Robert I. Pitts * Last Modified: February 2, 2000 * Topic: Debugging Run-Time Errors without a Debugger * ---------------------------------------------------------------- * * Usage: * ===== * The user enters numbers separated by spaces, with 0 (zero) * entered as the last number. Then, the sum of those numbers * is displayed. */ #include /************************ Function Prototypes *********************/ // PrintValues: Prints the values with +'s between each. void PrintValues(float values[], int howmany); // SumValues: Returns the sum of the values. float SumValues(float values[], int howmany); /*************************** Main Function *************************/ int main() { const int MAX_VALUES = 10; // Can deal with at most MAX_VALUES numbers. float values[MAX_VALUES]; // Array to hold the numbers. int howmany; // How many numbers entered. cout << "Enter numbers to sum below (separated by spaces)." << endl << "Enter 0 (zero) as the last number." << endl; do { // Read the next number. cin >> values[howmany]; // Increment the count. howmany++; // Should error check "howmany"! } while (values[howmany-1] != 0); float sum = SumValues(values, howmany); cout << "The sum of "; PrintValues(values, howmany); cout << " is " << sum << endl; return 0; // 0 means program exited successfully. } /************************ Function Definitions *********************/ void PrintValues(float values[], int howmany) { for (int i = 0; i < howmany; i++) { if (i != 0) // Print "+" before all but first number cout << " + "; cout << values[i]; } } float SumValues(float values[], int howmany) { float sum = 0; for (int i = howmany; i > 0; i--) { sum += values[i]; } return sum; }