# Thread: how do u find 2nd largest number??

1. ## how do u find 2nd largest number??

i need to find the two largest vaules of 10 numbers using a while loop.

so far i can only find the largest number but can't fingure out how to get the 2nd largest number.

here is how i find the largest number

Code:
```int counter = 1, number, largest = 0, second_largest = 0;

while ( counter <= 10 ) {
printf("enter number: ");
scanf("%d", &number );

if ( number > largest )
number = largest;

counter++;
}```
how do i find the second largest number??? 2. First of all, when you paste a code, add code tags!
Second, look here:

2nd_largest = 0;
First, you make largest = second_largest. then in the loop if the number isn't bigger than the largest you put it on second largest and check again. 3. Don't forget to change the second_largest in case the largest changes.

Code:
```if number > largest then
second_largest = largest
largest = number
else if number > second_largest then
second_largest = number``` 4. ok!

i got this and it seems to work also

Code:
```if ( second_largest < number )
second_largest = largest;

if ( largest < number )
largest = number;``` 5. Originally posted by juancardenas
ok!

i got this and it seems to work also

Code:
```if ( second_largest < number )
second_largest = largest;

if ( largest < number )
largest = number;```
No. that's wrong. Consider the following three numbers being read consecuivly:

1
2
3
Code:
```if( second number (0) < 1 )
second number = 1
if( largest number (0) < 1 )
second number = 1
if( second number (1) < 2 )
second number = 2
if( largest number (1) < 2 )
second number = 2
if( second number (2) < 3 )
second number = 3
if( largest number (2) < 3 )
second number = 3```
In your sample code, both number and second number end up being the same

Quzah. 6. I would suggest doing a descending sort array and then calling the function with some pointer arithmetic. Example,

printf("%d", *iptr);
iptr++;
printf("%d", *iptr); 7. ## Code:
```I would suggest doing a descending sort array and then calling the function with some pointer arithmetic. Example,

printf("%d", *iptr);
iptr++;
printf("%d", *iptr);```

He could also do the same without using pointers! Keep it simple if at all possible. 8. Something like that I think it should work:
Code:
```#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int nFirst, nSecond, nNumber;
nFirst = nSecond = 0;

printf("Enter numbers, -1 to exit\n");
do {
scanf("%d",&nNumber);
if (nNumber > nFirst)
{
nSecond = nFirst;
nFirst = nNumber;
}

else if (nNumber > nSecond)
nSecond = nNumber;
} while (nNumber != -1);

printf("The biggest number: %d and the second biggest: %d\n",nFirst,nSecond);
system("PAUSE");
return 0;
}``` 9. everyone here seems to be assuming that the numbers are positive and therefore at the beginning setting the largest and second largest to 0.

you should take into acount that some or all of the numbers may be negative. Popular pages Recent additions 