Lets find biggest of 3 numbers using ternary operator / conditional operator. This program is an example for nested ternary operator.
Related Read:
Ternary Operator / Conditional Operator In C
Logical Operators In C
To find biggest of Three numbers using if-else control structure:
Biggest of 3 Numbers: C
Source Code: Biggest of Three Numbers using ternary operator: C
#include < stdio.h > int main() { int a, b, c, big; printf("Enter 3 numbers\n"); scanf("%d%d%d", &a, &b, &c); big = (a>b && a>c) ? (a) : ( (b>c)?(b):(c) ); printf("Biggest is %d\n", big); return 0; }
Output 1:
Enter 3 numbers
1
2
3
Biggest is 3
Output 2:
Enter 3 numbers
1
3
2
Biggest is 3
Output 1:
Enter 3 numbers
3
2
1
Biggest is 3
In above source code, if a is bigger than b as well as c, then value of a is returned and stored in variable big orelse exression3 gets executed – where we check if b is greater than c.
(expression_1) ? (expression_2) : (expression_3);
expression_1 is a comparison/conditional argument. expression_2 is executed/returned if expression_1 results in true, expression_3 gets executed/returned if expression_1 is false.
In our source code, we nest Ternary Operator inside expression3 to find biggest among b and c.
Note:
if ( a > b && a > c ) is true, then value of a will be stored in variable big; else ( b > c ? b : c ) will be evaluated. Here, if value of b is greater than c, value of b will be stored in variable big else value of c will be stored in the variable big.
Biggest of 3 Numbers Using Ternary Operator: C Program
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert