Finding largest and smallest integer

I am working on a project in which I have to find the largest and smallest integer in a set of 5.

My problem is this: If the list of numbers is ascending in the 'smallest' portion, the program gives me an incorrect answer. Likewise, if the numbers are descending, the 'largest' part is incorrect.

Can anybody take the time to look at my code and give me some pointers? Any help would be appreciated.

Here is the section that's troubling me:

1
2
3
4
5
6
7
8
9
10
11
12
13
 if (opt == 1) {
            if (num1 > num2) min = num2;
            if (min > num3) min = num3;
            if (min > num4) min = num4;
            if (min > num5) min = num5; 
               cout<<"The smallest number is "<< min <<"."<<endl; }
               
    if (opt == 2) {
            if (num1 < num2) max = num2;
            if (max < num3) max = num3;
            if (max < num4) max = num4;
            if (max < num5) max = num5; 
               cout<<"The largest number is "<< max <<"."<<endl; }
You should assign min/max to num1 before the comparisons
num1 - num5 are already defined earlier in the program, if that's what you mean. If not, could you elaborate a bit more on assigning a min/max?
min = num1
Try comparing all the numbers against max, rather than each other.

My mistake, you already do that...
Last edited on
Is this what you mean? I added this to the beginning but I still come up with the same result:

1
2
3
4
5
6
7
8
int num1; 
int num2;
int num3;
int num4;
int num5;
int min = num1;
int max = num1;
int opt;
Read your code:
1
2
3
4
5
6
if (opt == 1) {
            if (num1 > num2) min = num2;
            if (min > num3) min = num3;
            if (min > num4) min = num4;
            if (min > num5) min = num5; 
               cout<<"The smallest number is "<< min <<"."<<endl; }

can min ever be equal to num1 based on this?
Thanks for pointing that out, Bazzy. Everything is working perfectly now and your help is much appreciated.
Topic archived. No new replies allowed.