Amos Wu
Amos Wu

Reputation: 37

Finding max and min integers from user input using for loop in C++?

The following code intends to ask the user to specify the number of integers they would like to input and then find and display the maximum and minimum values between them. However, it's not compiling, and it might be because of the way I initialized the minInt and maxInt variables, but I'm unsure. Please help! Thanks in advance!

#include <iostream>
using namespace std;
int main()

{
        int inNum, inInt, minInt, maxInt, i;

        minInt = INT_MAX;
        maxInt = INT_MIN;
        cout << "How many numbers would you like to enter?" << endl;
        cin >> inNum;
        cout << "Please enter " << inNum << " integers." << endl;
        for(i = 0 ; i < inNum; i++)
        {
                cin >> inInt >> endl;
                if(inInt > maxInt)
                {
                        maxInt = inInt;
                }
                if(inInt < minInt)
                {
                        minInt = inInt;
                }
        }
        cout << "min: " << minInt << endl;
        cout << "max: " << maxInt << endl;
        return 0;
}

Upvotes: 0

Views: 2556

Answers (2)

Alejandro Montilla
Alejandro Montilla

Reputation: 2654

I've found 2 errors:

  1. <climits> is not included, where INT_MAXand INT_MIN is defined
  2. And cin does not support endl

So the code should be somenthing like:

#include <iostream>
#include <climits>

using namespace std;
int main()
{
    int inNum, inInt, minInt, maxInt, i;

    minInt = INT_MAX;
    maxInt = INT_MIN;
    cout << "How many numbers would you like to enter?" << endl;
    cin >> inNum;
    cout << "Please enter " << inNum << " integers." << endl;
    for(i = 0 ; i < inNum; i++)
    {
            //Error 3: cin >> inInt >> endl; cin does not support endl
            cin >> inInt;
            if(inInt > maxInt)
            {
                    maxInt = inInt;
            }
            if(inInt < minInt)
            {
                    minInt = inInt;
            }
    }
    cout << "min: " << minInt << endl;
    cout << "max: " << maxInt << endl;
    return 0;
}

Upvotes: 0

dbush
dbush

Reputation: 224082

Here's your problem:

cin >> inInt >> endl;

You don't need to have endl here.

cin >> inInt;

Upvotes: 3

Related Questions