Program to Find the Greatest of Three Numbers in C

Finding the Greatest of Three Numbers

Given three integer inputs num1, num2, and num3, the objective is to determine which number is the greatest using C programming.

We will explore different methods to achieve this.

Method 1: Using if-else Statement

We use an if-else statement to compare three numbers and determine the greatest one.

#include <stdio.h>

int main() {
    int num1, num2, num3;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);
    
    if (num1 >= num2 && num1 >= num3) {
        printf("%d is the greatest number", num1);
    } else if (num2 >= num1 && num2 >= num3) {
        printf("%d is the greatest number", num2);
    } else {
        printf("%d is the greatest number", num3);
    }
    return 0;
}
            

Output:

Enter three numbers: 5 10 7
10 is the greatest number

Method 2: Using Ternary Operator

We use the ternary operator to find the greatest number in a single line.

#include <stdio.h>

int main() {
    int num1, num2, num3;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);
    
    int greatest = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
    printf("%d is the greatest number", greatest);
    
    return 0;
}
            

Output:

Enter three numbers: 7 3 9
9 is the greatest number

Method 3: Using Function

We create a function to compare three numbers and return the greatest one.

#include <stdio.h>

int findGreatest(int a, int b, int c) {
    return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
}

int main() {
    int num1, num2, num3;
    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);
    
    printf("%d is the greatest number", findGreatest(num1, num2, num3));
    
    return 0;
}
            

Output:

Enter three numbers: 4 9 2
9 is the greatest number
Easy aceess next quctions
Getting Started

Positive or Negative number: C C++ Java Python

Even or Odd number: C C++ Java Python

Sum of First N Natural numbers: C C++ Java Python

Sum of N natural numbers: C C++ Java Python

Sum of numbers in a given range: C C++ Java Python

Greatest of two numbers: C C++ Java Python

Greatest of the Three numbers: C C++ Java Python

Leap year or not: C C++ Java Python

Prime number: C C++ Java Python

Prime number within a given range: C C++ Java Python

Sum of digits of a number: C C++ Java Python

Reverse of a number: C C++ Java Python

Palindrome number: C C++ Java Python

Armstrong number: C C++ Java Python

Armstrong number in a given range: C C++ Java Python

Harshad number: C C++ Java Python

Abundant number: C C++ Java Python

Friendly pair: C C++ Java Python