0

The exercise is finding the largest and second largest numbers of ten entered. The numbers can only be entered once. No functions, arrays, of the STL can be used... Just while statements

The problem I'm having is with a sequence 5, 4, 9... The 5 becomes the largest, 4 is second largest, and when the 9 becomes largest, 4 is still the second largest (the 5 drops out).

Is there any way to do this short of :

while(count < 10){                   
           cout << "Enter a number: ";
           cin >> number;

           number10 = number9;
           number9 = number8;
           number8 = number7;
           number7 = number6;
           number6 = number5;
           number5 = number4;
           number4 = number3;
           number3 = number2;
           number2 = number1;
           number1 = number;

           count++;
       }

and then comparing all of this against one another. There has to be a better way.
TIA
LubLub

Edited by happygeek: fixed formatting

3
Contributors
4
Replies
5
Views
12 Years
Discussion Span
Last Post by LubLub
0

How about:

get a number

if n > largest then secondLargest = largest, largest = n;
else if n > secondLargest then secondLargest = n;

something along those lines?

0

Tx ChainSaw

But the exercise asks for while statements...

I understand how the if/else code would solve this one for me.

LubLub

0

count =0;
int n, first = 0, second = 0;

while(count<10)
{
cout<<"Enter a number ";
cin>>n;

if(n>first) //checking with the values of first(largest number)
first = n;
else if(n<first && n>second) //checking with the values of second and first if it is below first and above //second(2nd largest number)
second = n;

count++;
}

I think this should work. I've not run it yet.

0

Thanks,

Using all the advice, I was able to figure it out with while loops.

LubLub

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.