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;
}
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
#include <iostream>
usingnamespace 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;
}
elseif (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!