Finding Second Largest Number in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to find the second-largest number out of three user input numbers in C programming language. We will be using an algorithm that utilizes nested if-else loops to find the second largest number.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Declare Three Variables

The first step is to declare three variables of double data type. These will be the three numbers we will receive as input from the user.

#include <stdio.h>

int main()
{
    double num1, num2, num3;

    // rest of the code
}

Get Input from the User

The next step is to receive input from the user for the three variables declared in the previous step. We will use the scanf function to receive input.

printf("Enter three numbers: ");
scanf("%lf %lf %lf", &num1, &num2, &num3);

Find the Second Largest Number

Now, let's find the second largest number using nested if-else loops.

if (num1 > num2 && num1 > num3)
{
    if (num2 > num3)
    {
        printf("Second largest number: %.2lf", num2);
    }
    else
    {
        printf("Second largest number: %.2lf", num3);
    }
}
else if (num2 > num1 && num2 > num3)
{
    if (num1 > num3)
    {
        printf("Second largest number: %.2lf", num1);
    }
    else
    {
        printf("Second largest number: %.2lf", num3);
    }
}
else
{
    if (num1 > num2)
    {
        printf("Second largest number: %.2lf", num1);
    }
    else
    {
        printf("Second largest number: %.2lf", num2);
    }
}

Complete the Program

Let's put all the code that we have written so far together to complete the program.

#include <stdio.h>

int main()
{
    double num1, num2, num3;

    printf("Enter three numbers: ");
    scanf("%lf %lf %lf", &num1, &num2, &num3);

    if (num1 > num2 && num1 > num3)
    {
        if (num2 > num3)
        {
            printf("Second largest number: %.2lf", num2);
        }
        else
        {
            printf("Second largest number: %.2lf", num3);
        }
    }
    else if (num2 > num1 && num2 > num3)
    {
        if (num1 > num3)
        {
            printf("Second largest number: %.2lf", num1);
        }
        else
        {
            printf("Second largest number: %.2lf", num3);
        }
    }
    else
    {
        if (num1 > num2)
        {
            printf("Second largest number: %.2lf", num1);
        }
        else
        {
            printf("Second largest number: %.2lf", num2);
        }
    }

    return 0;
}

Summary

In this lab, we learned how to find the second largest number out of three user input numbers using nested if-else loops. We hope this lab helped you understand this algorithm and how it can be implemented in C programming language.

Other C Tutorials you may like