954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Deitel's "C++ How To Program" exercise 2.18

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

LubLub
Newbie Poster
4 posts since Dec 2004
Reputation Points: 10
Solved Threads: 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?

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

Tx ChainSaw

But the exercise asks for while statements...

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

LubLub

LubLub
Newbie Poster
4 posts since Dec 2004
Reputation Points: 10
Solved Threads: 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(nsecond) //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.

chound
Junior Poster
145 posts since Aug 2004
Reputation Points: 15
Solved Threads: 1
 

Thanks,

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

LubLub

LubLub
Newbie Poster
4 posts since Dec 2004
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You