I need to create a program that will allow the users to enter a series of integers with 0 as the sentinel. At the end, the largest integer will be displayed.
I originally had the statement largest = value
under the if statement but changed it to a conditional statement which makes more sense to me since the previous way I had it just gave me the last value before the sentinel was entered. It seems to give me the "right" output, but is the way I set it up with the conditional statement correct? If not, how can I fix it?
Original output
This program finds the largest integer in a list.
Enter 0 to signal the end of the input.
Please enter an integer: 21
Please enter an integer: 15
Please enter an integer: 9
Please enter an integer: 6
Please enter an integer: 3
Please enter an integer: 0
The largest value is 3.
Press any key to continue . . .
Current output
This program finds the largest integer in a list.
Enter 0 to signal the end of the input.
Please enter an integer: 15
Please enter an integer: 200
Please enter an integer: 3
Please enter an integer: 5
Please enter an integer: 21
Please enter an integer: 0
The largest value is 200.
Press any key to continue . . .
Source code:
#include "stdafx.h"
#include <iostream>
using namespace std;
const int SENTINEL = 0;
/* Main Program */
int main()
{
cout << "This program finds the largest integer in a list.";
cout << "\nEnter " << SENTINEL << " to signal the end of the input." << endl;
int largest = SENTINEL;
while (true)
{
int value;
cout << "\nPlease enter an integer: ";
cin >> value;
if (value == SENTINEL)
break;
largest = (value > largest) ? value : largest;
}
cout << "\nThe largest value is " << largest << "." << endl;
cout << endl;
system("PAUSE");
return 0;
}