I'm taking a beginning C++ class right now, and we're supposed to make a program that allows the user to enter as many numbers as they like and when they're done, display the largest and smallest of the numbers entered.

However, I can't figure out how to make it display the largest and smallest number and I've tried everything I can think of. Also, the first number, no matter what is entered, displays the invalid number line.

Any help is greatly appreciated!

//large and small
#include <iostream>
using namespace std;

int main()
{
    int number,
        small,
        large;

    small = 100;
    large = 1;

    cout << "Please enter a number between 1 and 100." << endl;
    cin >> number;

    while (number < 1 || number > 100);
    {
        cout << "Invalid number." << endl;
        cout << "Please enter a number between 1 and 100." << endl;
        cin >> number;
    }

    while (number >= 1 || number <= 100)
    {
        if (number < small)
        {
            small = number;
        }
        else
        if (number > large)
        {
            large = number;
        }
        cout << "Please enter another number between 1 and 100." << endl;
        cin >> number;
    }
        cout << "The smallest number is " << small << " and the largest number is " << large << "." << endl;

    return 0;
}

Recommended Answers

All 3 Replies

line #17

while (number < 1 || number > 100); //<--remove ";"

remove semicolon at the end of the line

line #24:

while (number >= 1 || number <= 100) //<-- this is allways true

change "||" to "&&".

line #30 - remove else statement, or you will get incorect answers if you first enter big number (f.e. 98) and then small one (f.e. 12)

Now program works, as long as you enter vars from range <1,100>.
f.e. if you enter 120, then it will keep asking you for a var from range <1,100>, but once you enter a proper var, program will end if you enter var beyond the range.

Interesting. You have quite a few unneeded pieces of code, so instead of me telling you all the things you don't need, I will just give you my example to use as a reference.

Hope it helps:

#include<iostream>
using namespace std;
int main()
{
	int smallest=100, largest=0, number;
	do{
		cout << "Please enter a number between 1 and 100.: ";
		cin >> number;
		if(number < 101)
		{if(number > largest)
		largest = number;
		if(number < smallest)
			smallest = number;}
	}while((number>0)&&(number<101));
	cout << endl << "The largest number is " << largest << " and the smallest number is " << smallest << endl << endl;
}

Edit: I did not see the post above mine, as I was taking the time to write the code, and found he had posted 18 minutes before mine. (Which by the way is 100% correct)

Thank you both!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.