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

## All 4 Replies

get a number

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

something along those lines?

Tx ChainSaw

But the exercise asks for while statements...

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

LubLub

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.

Thanks,

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

LubLub

Be a part of the DaniWeb community

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