C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Decision Making Programs in C

Find greatest among four numbers (ternary operators)

Introduction

The ternary operator ?: allows us to write simple conditional statements in one line.
It works as:

(condition) ? (true_value) : (false_value);

We can chain multiple ternary operators to compare multiple numbers efficiently.

 

C Program: Find greatest among four numbers (ternary operators)

C

#include <stdio.h>

 

int main() {

    int a, b, c, d, greatest;

 

    // Input four numbers

    printf("Enter four numbers: ");

    scanf("%d %d %d %d", &a, &b, &c, &d);

 

    // Find the greatest using ternary operators

    greatest = (a > b && a > c && a > d) ? a :

               (b > c && b > d) ? b :

               (c > d) ? c : d;

 

    // Output

    printf("%d is the greatest number.\n", greatest);

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter four numbers: 15 20 9 7
20 is the greatest number.

OUTPUT 2 :
Enter four numbers: 50 120 80 300
300 is the greatest number.

OUTPUT 3 :
Enter four numbers: 77 22 11 5
77 is the greatest number.

Explanation

  1. User enters four numbers: a, b, c, d.
  2. Ternary operators are evaluated in order:
    • If a is greater than b, c, and d → a is greatest.
    • Else if b is greater than c and d → b is greatest.
    • Else if c is greater than d → c is greatest.
    • Else → d is greatest.
  3. The result is stored in greatest and printed.