C Program to find greatest among two numbers using ternary operator
Objective
Write a C program to find the greatest of two numbers using the ternary operator.
Algorithm / Approach
- Declare variables
aandb. - Read
aandb. - Use the ternary operator directly inside a statement:
(a > b) ? printf("A is Greatest") : printf("B is Greatest");.
main.c
#include<stdio.h>
int main( ) {
int a, b;
printf("Enter Values for A : ");
scanf("%d",&a);
printf("Enter Values for B : ");
scanf("%d",&b);
(a>b)? printf("A is Greatest\n") : printf("B is Greatest\n");
return 0;
}
Expected Output
Enter Values for A : 62 Enter Values for B : 119 B is Greatest
Explanation of the Program
- The ternary operator does not always have to be assigned to a variable.
- You can place function calls directly inside the true and false branches. The compiler will evaluate the condition (a > b). If it is true, it executes the first
printf. If false, it executes the secondprintf.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)