C Ternary Operator
C Ternary Operator
C Ternary Operator
C Ternary Operator
C Ternary Operator allows to choose one of the two values based on a condition.
In this tutorial, we will learn its syntax, usage and nesting of ternary operators with examples.
start
return return
value_1 value_2
www.tutorialkart.com
So, ternary operator has three operands. From the above syntax, they are condition, value_1 and value_2.
where
condition is a boolean value or an expression that evaluates to boolean value. The condition is generally formed
condition is a boolean value or an expression that evaluates to boolean value. The condition is generally formed
using comparison operators and logical operators.
If the condition is true, Ternary Operator returns value_1. If the condition is false, Ternary Operator returns
value_2. The returned value can be stored in a variable, say x.
if (condition) {
x = value_1;
} else {
x = value_2;
}
In the following example, we use Ternary Operator to find the maximum of two integers. The condition is if value
in a is greater than that of b. If yes, we assign a to the variable max, else we assign b. After executing this
ternary operator, variable max will end up with largest of a and b.
C Program
#include <stdio.h>
void main() {
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("%d", max);
}
Output
In the following example program, for ternary operator, we provide expressions for the value to be returned
when the condition is true or false.
C Program
#include <stdio.h>
void main() {
void main() {
int a = 5;
int b = 2;
int c = (a > b) ? (a*a + 2) : (b*9);
printf("%d", c);
}
Output
We know that Ternary Operator is an expression that returns a value. So, for the values (second and third
operands), you can give a Ternary Operator.
In the following example, we shall use nested Ternary Operator to find the maximum of three numbers.
C Program
#include <stdio.h>
void main() {
int a = 5;
int b = 2;
int c = 7;
int max = (a > b) ? ((a>c) ? a : c) : ((b > c) ? b : c);
printf("%d", max);
}
Output
Conclusion
In this C Tutorial, we learned what a Ternary Operator is in C programming language, how its execution
happens, and how it works with example programs.
C Programming
✦ C Tutorial
✦ C Data Types
✦ C Variables
✦ C Variables
✦ C Constants
✦ C if
✦ C if else
➩ C Ternary Operator
✦ C loops
✦ C While Loop
✦ C For Loop
✦ C Structures
✦ C Unions
✦ C typedef
C String Operations
✦ C Reverse String
✦ C String Length
✦ C Compare Strings
C FileOperations
✦ C Write to File
✦ C Delete File
✦ C Concatenate Files