Find the Largest of Three Numbers Using Ternary Operator in C

Find the Largest of Three Numbers Using Ternary Operator in C

In this tutorial, we will write a C program to determine the largest of three numbers using the ternary (conditional) operator.

What is a Ternary Operator?

The ternary operator in C is a shorthand form of the if-else statement.


(condition) ? expression1 : expression2;

If the condition is true, expression1 executes; otherwise, expression2 executes.

Logic to Find the Largest Number

To find the largest of three numbers (a, b, c):

  1. First compare a and b.
  2. Store the larger value in a variable.
  3. Then compare that result with c.

C Program


#include <stdio.h>

int main() {
    int a, b, c, largest;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    // Using nested ternary operator
    largest = (a > b) ? 
              ((a > c) ? a : c) : 
              ((b > c) ? b : c);

    printf("The largest number is: %d\n", largest);

    return 0;
}

Explanation

Step 1: Input

The program takes three integers from the user.

Step 2: Nested Ternary Operator


largest = (a > b) ? 
          ((a > c) ? a : c) : 
          ((b > c) ? b : c);
  • If a > b is true, then compare a and c.
  • If a > c is true → largest = a
  • Otherwise → largest = c
  • If a > b is false, then compare b and c.
  • If b > c is true → largest = b
  • Otherwise → largest = c

Sample Input

Enter three numbers: 10 25 15

Output

The largest number is: 25

Time Complexity

The program performs a constant number of comparisons. So the time complexity is O(1).

C program largest of three numbers, ternary operator in C, conditional operator example in C, nested ternary operator program, C programming basic problems with solution

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন