C Program to Find the Largest of three Numbers

In this tutorial, we will write a basic C Program to find the greatest of three numbers. You may go through the following topics in order to understand the C program.

Algorithm to find the largest among three numbers

  1.  Start.
  2. Read num1, num2 and num3 from user.
  3. Check num > num2, if true go to step 4 else go to step 5
  4. Check num1 > num3.
    • If true, print ‘num1 is the greatest number’.
    • If false, then print ‘num3 as the greatest number’.
    • go to step 6
  5. check if num2 > num3.
    1. If true, print ‘num2 as the greatest number’.
    2. If false, print ‘num3 as the greatest number’.
  6. Stop

C Program to find the Largest among three Numbers

We will find the greatest of three using if..else and if…else-if statement.

//C program to find the biggest of three numbers using if else if statement

#include <stdio.h>
int main()
{
    int num1, num2, num3;
    
    printf("Enter three numbers to compare.\n");
    
    printf("First Number: ");
    scanf("%d", &num1);
    printf("Second Number: ");
    scanf("%d", &num2);
    printf("Third Number: ");
    scanf("%d", &num3);
    
    if (num1 > num2)
    {
        if (num1 > num3)
        {
            printf("\nLargest number: %d \n",num1);
        }
        else
        {
            printf("\nLargest number: %d \n",num3);
        }
    }
    else if (num2 > num3)
    {
        printf("\nLargest number: %d \n",num2);
    }
    else
    {
        printf("\nLargest number: %d \n",num3);
    }
    return 0;
}

Output:

Enter three numbers to compare.
First Number: 32
Second Number: 65
Third Number: 19

Largest number: 65


Using Ternary operator

The ternary operator works like an if..else statement in C. Syntax of the ternary operator. (?:)

variable num1 = (expression) ? value if true : value if false

//Using ternary Operator

#include <stdio.h>
int main()
{
    int num1, num2, num3;
    
    printf("Enter three numbers to compare.\n");
    
    printf("First Number: ");
    scanf("%d", &num1);
    printf("First Number: ");
    scanf("%d", &num2);
    printf("First Number: ");
    scanf("%d", &num3);
    
    int greatestNum = ((num1>num2 && num1>num3) ? num1 : (num2>num3)?num2:num3);
    printf("\nLargest of three is: %d.", greatestNum);
    
    return 0;
}

Output:

Enter three numbers to compare.
First Number: 45
Second Number: 98
Third Number: 66

Largest of three is: 98