Ternary operator and Nested Ternary operator
Ternary operator
Ternary operator which is a conditional operator and, as the name suggests, it takes three operands (parts).
Ternary operator is available in most languages, like, C, C++, Java, JavaScript, etc
Syntax:-
variable = condition ? expression1_if_true : expression2_if_false
Explanation:
condition: This is a boolean expression that evaluates to either true or false.
expression1_if_true: This is the value or statement that is executed if the condition is true.
expression2_if_false: This is the value or statement that is executed if the condition is false.
Ternary operator is nothing, just a concise way of writing an if-else statement, i.e. the same operation can be achieved using an if-else block as shown below.
if(condition){
variable = value_if_true
}else{
variable = value_if_false
}
Example 1 :- C program find max number among two given numbers using ternary operator
#include <stdio.h>
int main() {
int a = 15, b = 25;
int max = (a > b) ? a : b; // If a > b is true, max will be assigned a; otherwise max will be assigned b
printf("The maximum value is %d\n", max);
return 0;
}
Output:
The maximum value is 25
We can use a ternary operator anywhere, just like other statements. Let's try ternary operator in the print function itself.
Example 2 :-
#include <stdio.h>
#include <stdbool.h>
int main() {
int a = 15, b = 25;
bool compare = (a < b);
printf("Is a less than b: %s\n", compare ? "true" : "false");
return 0;
}
Output
Is a less than b: true
Nested Ternary operator
We can have Nested Ternary operator as well. Its syntax is shown below.
variable = condition1 ? (condition2 ? expression_if_true2 : expression_if_false2) : expression_if_false1;
Explanation:
The outer ternary checks if a > b.
If true, it evaluates the nested ternary ((a > c) ? a : c). This checks if a > c. If true, it assigns a as the largest, otherwise c.
If false (i.e., b > a), it evaluates the nested ternary ((b > c) ? b : c), which checks if b > c. If true, it assigns b as the largest, otherwise c.
Example:- C program to find the largest number among three given numbers
#include <stdio.h>
int main() {
int a = 12, b = 22, c = 15;
// Nested ternary operator to find the largest among three numbers
int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
printf("The largest value is %d\n", largest);
return 0;
}
Output:
The largest value is 22
Comments
Post a Comment