Here is a program to find biggest of 3 numbers using ternary operator with output and explanation in C programming language.
# include <stdio.h> # include <conio.h> void main() { int a, b, c, big ; clrscr() ; printf("Enter three numbers : ") ; scanf("%d %d %d", &a, &b, &c) ; big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ; printf("\nThe biggest number is : %d", big) ; getch() ; }
Output of above program
Enter three numbers : 20 30 10
The biggest number is : 30
Explanation of above program
Note: If you don't know about ternary operator first read it here. Ternary Operator in C.
To understand this program lets convert this ternary operator into its equivalent if else.
big = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c) ;
If else equivalent of above ternary expression
Now once ternary operator's expression is converted into simple if else it is easy to understand the program. So I let you to it.
if(a > b){ if(a > c){ big = a; }else{ big = c; } } else{ if(b > c){ big = b; }else{ big = c; } }
Now once ternary operator's expression is converted into simple if else it is easy to understand the program. So I let you to it.
Algorithm to find maximum of three numbers using conditional operator
Let A, B and C are three numbers.
We will first find the largest of A and B using conditional operator. Let it be X.
Then we will compare X with third number C to get the overall largest number.
find it using single ternary
Hello There,
I’ve often thought about this Biggest of 3 Numbers Using Ternary Operator in C. Nice to have it laid out so clearly. Great eye opener.
How can milli second / micro second / nano second be used in gcc platform? What is the process, syntax?
It was cool to see your article pop up in my google search for the process yesterday. Great Guide.
Keep up the good work!
Ciao,
Preethi.