What am I doing wrong!!!

When I build and run, it always put the large and small on 1.... I entered the integers, "1,2,3,4,5"...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main()
{
int userIn,small, large;
cout << "Enter 5 integers\n";
cin >> userIn;
small=userIn;
large=userIn;

for (int i=1; i<5; i++) {
  if (userIn<small)
    small=userIn;
  if (userIn>large)
    large=userIn;
}
cout << "Smallest: " << small << endl;
cout << "Largest: " << large << endl;

return 0;
}
When you hit this line of code, cin >> userIn;

You are going to take one number, not five seperate numbers.

The next two lines of code..

small=userIn;
large=userIn;

assign variables small and large, the one number you enter in the console.

The for loop, you cycle through four times.

With each cycle you check to see if the variable userIn is less than the variable small.
Which it won't be, they'll equal the same because of the these lines of code..

cin >> userIn;
small=userIn;

Similarly you check if the variable userIn is more than the variable large.. but it'll never be because of these lines of code..

cin >> userIn;
large=userIn;

Hope that helps.


You can't do like this. you have to use array or else.
Sorry,my English is pool.
You just enter a number, so you just get the first number of the maximum and minimum value. Below is the right code:
#include <iostream>
using namespace std;
int main()
{
int userIn[5],small, large;
cout << "Enter 5 integers\n";
for(int a=0;a<5;a++)//enter 5 numbers
{
cin >> userIn[a];
}
small=userIn[0];
large=userIn[0];

for (int b=1; b<5; b++) {
if (userIn[b]<small)
small=userIn[b];
if (userIn[b]>large)
large=userIn[b];
}
cout << "Smallest: " << small << endl;
cout << "Largest: " << large << endl;

return 0;
}
Arrays are not needed, but they are the easiest way to do it. Obviously the OP is having more issues with the concept of what he's doing so adding more features and syntax isn't exactly the best idea.

Your cout/cin needs to be in for loop as well, and you need to check that i == 0 after your cin statement, assign large/small to userIn, and then proceed with your if statements. This should resolve your issue.
Last edited on
Topic archived. No new replies allowed.