Ternary Operator in C

For Complete YouTube Video: Click Here

In this class, we will try to understand Ternary Operator in C.

We have covered Arithmetic, Assignment, Increment, Bitwise, and shift operators in our previous classes.

Ternary Operator in C

The Ternary Operator is also called a conditional statement.

The symbol used for the ternary operator is [?: ].

The ternary operator is an alternative to a simple if-else statement.

The conditional statements are the decision-making statements that depends upon the output of the expression.

The syntax for the ternary operator is as shown below.

expression1?expression2:expression3

The expression1 in the above expression is the conditional statement of the ternary operator.

Based on the output of the conditional statement, expression2 or expression3 will be executed.

If the conditional statement of the ternary operator evaluates to be true, expression2 will be executed.

Similarly, if the conditional statement of the ternary operator evaluates to be false, expression3 will be executed.

Ternary operator Programming Example

The image below is the program for the ternary operator.

Ternary Operator in C
Ternary Operator in C Program

The above program decides whether the value stored in “a” is an Even or Odd number.

The second line of the code is the use of the ternary operator, as shown below.

((a%b) == 0) ? printf(“EVEN”) : printf(“ODD”);

In the above expression of the ternary operator == is an equality operator.

If the output of the expression a%b evaluates to 0, then 0 equal to 0 is true, then printf(“EVEN”) will be executed.

If the expression evaluates to 1, then one is not equal to 0, then printf(“ODD”) will be executed.