C Program To Find Largest and Smallest of Three Numbers Using Ternary Operator
In this tutorial, we are going to see how to write a C program to find the largest and smallest of three numbers using the ternary operator. The C language comes with a ternary operator that is a bit strange and can be used as an alternative to if-else and has the advantage that it can be embedded in an expression. The following expression <expr1> ? <expr2> : <expr3> is translated like this:
- If <expr1> is not null, then the value of <expr2> is returned as the result.
- Otherwise, the value of <expr3> is returned as the result.
The following instruction:
if (a>b) max=a; else max=b;
Can be replaced by :
max = (a > b) ? a : b;
In the following example, we ask the user to enter 3 numbers using scanf function, and then we consider the first input as the maximum and minimum. Then we compare it with other inputs.
C Program To Find Largest and Smallest of Three Numbers Using Ternary Operator
#include <stdio.h>
int main()
{
int a,b,c;
printf("Enter 1st number: ");
scanf("%d",&a);
printf("Enter 2nd number: ");
scanf("%d",&b);
printf("Enter 3th number: ");
scanf("%d",&c);
int max = a, min = a;
max = (b > max)? b: max;
max = (c > max)? c: max;
printf("\nMax is %d", max);
min = (b < min)? b: min;
min = (c < min)? c: min;
printf("\nMin is %d", min);
return 0;
}
Output:
Enter 1st number: 12 Enter 2nd number: 45 Enter 3th number: 32 Max is 45 Min is 12




