Find First and Second Biggest in N Numbers, without using Arrays: C Program

Write a C program to find first and second biggest numbers in list of N numbers without using arrays and without sorting the list and by using while loop.

Related Read:
while loop in C programming
Find Biggest of N Numbers, without using Arrays: C Program

Source Code: Find First and Second Biggest in N Numbers, without using Arrays: C Program

 
#include<stdio.h>

int main()
{
    int limit, num, fbig = 0, sbig = 0;

    printf("Enter the limit\n");
    scanf("%d", &limit);

    printf("Enter %d positive numbers\n", limit);
 

    while(limit > 0)
    {
        scanf("%d", &num);

        if(num > fbig)
        {
            sbig = fbig;
            fbig = num;
        }
        if(num > sbig && num < fbig)
        {
            sbig = num;
        }

        limit--;
    }

    printf("First Big is %d\n", fbig);
    printf("Second Big is %d\n", sbig);

    return 0;
}

Output 1:
Enter the limit
5
Enter 5 numbers
1
2
3
4
5
First Big is 5
Second Big is 4

Output 2:
Enter the limit
5
Enter 5 numbers
5
4
3
2
1
First Big is 5
Second Big is 4

Output 3:
Enter the limit
5
Enter 5 numbers
1
4
3
5
2
First Big is 5
Second Big is 4

Output 4:
Enter the limit
8
Enter 8 numbers
1
5
9
3
7
4
6
8
First Big is 9
Second Big is 8

Find First and Second Biggest in N Numbers, without using Arrays: C Program



YouTube Link: https://www.youtube.com/watch?v=gs4YT-Qcw6k [Watch the Video In Full Screen.]


Logic To Find First and Second Biggest Number in N Numbers, without using Arrays

First we ask the user to enter length of numbers list. If user enters limit value as 5, then we ask the user to enter 5 numbers. Once the user enters limit value, we iterate the while loop until limit value is 0. For each iteration of while loop we ask the user to enter a integer number. We check if the new number entered by the user is greater than fbig. If true, we swap the value of fbig to sbig and value of num to fbig. If the new number entered by the user is not greater than fbig, then we check if its greater than sbig. If true, we transfer the value of num to sbig.

Once the value of limit is 0, control exits the while loop, and inside fbig we have first biggest number from the list of numbers entered by the user and sbig will have the second biggest number from the list of numbers entered by the user.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert