Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the largest and second largest number

Tags:

c

Write a program that inputs a series of 10 numbers and find the 2 largest values of the 10 numbers? (Only using if and loop)

Can anybody help me to solve the problem?. I tried to but it was not right. It cannot list out the second largest number. Any helps would be appreciated.

  #include "stdafx.h"
  #include <stdio.h>
  #include <stdlib.h>
  #include <math.h>


int main()
{
    int counter = 0, number, largest = 0,largest2=0;
    for (counter = 1; counter <= 10; counter++) {
        printf("Enter number (%d): ", counter);
        scanf_s("%d", &number);
        if (number > largest)
        {
            largest = number;
        }
        else
        {
            if (number > largest2)
                largest2 = number;
        }
    }
    printf("The largest number is %d\n", largest);
    printf("The second largest number is %d\n", largest2);
    system("pause");
    return 0;
}
like image 709
Dave Nguyen Avatar asked Dec 02 '22 12:12

Dave Nguyen


1 Answers

When you get a new largest number, the old largest number become the second largest number. So all you need is a single check for the largest number, and two assignments.

Something like

if (number > largest)
{
    largest2 = largest;
    largest = number;
}

You still need to check for numbers larger than largest2.

like image 112
Some programmer dude Avatar answered Dec 09 '22 15:12

Some programmer dude