Find Largest and Smallest

My problem is to ask the user to input numbers, 0 being the number that quits the program. If they input another number, it just continues asking them for a number.

When they do enter zero it then tells them the greatest number they entered and the smallest number they entered but the smallest number cannot be 0.

When I run the program it works for nonzero numbers, and when I enter zero it prints my congratulatory message but my largest number is always 1628438944 and I can't figure out how to state that smallest != 0.

Any suggestions? Here's my code as is.

#include <iostream>
using namespace std;
int main ()
{
int number;
int largest;
int smallest;
bool isValid = true;


while (number != 0)
{
cout << " Enter a number (0 to end)." << endl;
cin >> number;

if (number > largest && number!= 0)
{
largest = number;
}
else if (number < smallest && number != 0)
{
smallest = number;
}
}
if (number == 0)
{
cout << "Awesome you can read!" << endl;
cout << "Largest number entered was " << largest << endl;
cout << "Smallest number entered was " << smallest << endl;
isValid = false;
}


return 0;
}
You aren't initializing any of the numbers
I suggest you initializing largest with std::numeric_limits<int>::min()
and smallest with std::numeric_limits<int>::max()
You should also remove the else
The loop should better be a do-while
1
2
3
4
do
{
   //code...
}while ( number != 0 );
Last edited on
You can also just set them both to equal the first number.
I would suggest something like

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
40
41
42
#include <iostream>
using namespace std;
int main ()
{
int number;
int largest;
int smallest;
bool isValid = true;

cout << "Enter a number (0 to end)." << endl;
cin >> number;

largest = number;
smallest = number;

while (number != 0)
{

   if (number > largest )
   {
      largest = number;
   }
   else 
      if (number < smallest)
      {
         smallest = number;
      }

   cout << "Enter a number (0 to end)." << endl;
   cin >> number;

}


cout << "Awesome you can read!" << endl;
cout << "Largest number entered was " << largest << endl;
cout << "Smallest number entered was " << smallest << endl;
isValid = false;


return 0;
}


This should run without any problems, I left it so that you could test for whether to display a message indicating that no numbers were entered, have fun figuring it out the rest of the way!
Topic archived. No new replies allowed.