For Sum


Program Listing

ForSum.cpp

/************************************************************************
*                                                                       *
*   Program:    CounterSum                                              *
*                                                                       *
*   Abstract:   This program will add up a list of input values.        *
*               It uses a loop controlled by a counter.                 *
*                                                                       *
************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {

//  Get the size of the list

    cout << "How many numbers are to be added?  " << flush;
    int Size;
    cin >> Size;
    
    int Total = 0;
    int Number;

//  Add to total, until end of file

    for (int i = 0; i < Size; i++) {    // Initialize, test, & update
        cout << "Enter a number:  " << flush;   // Prompt
        cin >> Number;                  // Read
        Total += Number;                // Action
    }

//  Print the total
    
    cout << endl << "The total is " << Total << endl;
    
    return 0;
}

Sample Run #1

How many numbers are to be added?  3
Enter a number:  20
Enter a number:  30
Enter a number:  40

The total is 90

Sample Run #2

How many numbers are to be added?  0

The total is 0



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:34 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/ForSum.html

Return to Coms 261 home page