Sentinel Sum


Program Listing

SentinelSum.cpp

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

#include <iostream>
#include <string>

using namespace std;

const int SENTINEL = -1;

int main() {

//  Get value from user

    cout << "Enter an integer (enter " << SENTINEL << " to quit):  " << flush;
                                    // Prompt
    int Total = 0;
    int Number;
    cin >> Number;                  // Read

//  Add to total, until sentinel value is encountered

    while (Number != SENTINEL) {    // Test
        Total += Number;            // Action
        cout << "Enter an integer (enter " << SENTINEL << " to quit):  " << flush;
                                    // Prompt
        cin >> Number;              // Read
    }

//  Print the total

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

Sample Run #1

Enter an integer (enter -1 to quit):  20
Enter an integer (enter -1 to quit):  30
Enter an integer (enter -1 to quit):  40
Enter an integer (enter -1 to quit):  -1

The total is 90

Sample Run #2

Enter an integer (enter -1 to quit):  -1

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:33 1999 .

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

Return to Coms 261 home page