Comparing a series of integers, returns largest and smallest

How can I improve/optimize this program that asks the user to enter a series of integers and then displays the largest and smallest values entered? I have to use a sentinel value of -99.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;

int main()
{
	int number, least, greatest, compare = -99;

	cout << "Enter some integers, then enter -99 when finished.\n";
	cout << "This program will show you the greatest and least of them.\n";
	
	cout << "Enter an integer: ";
	cin >> number;
	greatest = least = number;

	while (number != -99)
	{
		compare = number;
		cout << "Enter an integer: ";
		cin >> number;
	
		if (number > compare && number > greatest && number != -99)
			greatest = number;
		if (number < compare && number < least && number != -99)
			least = number;
		if (number == compare && number != -99)
			number = number;
	}

	if (number == compare) 
	{
		cout << "You did not enter any integers.\n";
		return 0;
	}

	cout << "The greatest integer entered is: " << greatest << endl;
	cout << "The smallest integer entered is: " << least << endl;

	return 0;
}


I'm not really sure how to do it but would it be easier to write the user input to a file before sorting and reading the largest/smallest values?

Thanks for your time.
1
2
if (number == compare && number != -99)
	number = number;

I don't get this. Actually, I don't get what you use 'compare' for at all.
Oops, that bit is redundant, I'm not really sure about the convoluted logic of my program. I'm trying to use the compare variable to store the first input value (number), before overwriting the value with a new input. I'm using the same variable for all user input. The first imput (compare) and the new input (number) are compared with values of the variables greatest and least and the largest and smallest inputs are stored. The compare variable also does double-duty by allowing the program to quit if the first input value is the sentinel value (-99). I hope that makes sense.
You could use std::min() and std::max() instead of the if (..) statements

1
2
3
4
5
if (number != 99)
{
    least = std::min(least, number);
    greatest = std::max(greatest, number);
}


Thanks, I was looking for something like that.
Topic archived. No new replies allowed.