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):
- First compare
aandb. - Store the larger value in a variable.
- 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 > bis true, then compareaandc. - If
a > cis true → largest = a - Otherwise → largest = c
- If
a > bis false, then comparebandc. - If
b > cis 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).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন