Nested Ternary Operator in C++

Hello everyone, in this tutorial, we will learn about the nested ternary operator in C++. It is called a ternary operator because it uses three operands for its operation. It is also called a conditional operator. Ternary operator functions the same as an if-else statement.

Syntax of a ternary operator:-

Expression1 ? Expression2 : Expression3

So here the first expression is the condition, if it is true then the Expression2 is executed and if it is false then the Expression3 is executed.

Nested Ternary Operator

We are aware that in any programming language nesting of loops means using one loop in another and it is the same for a nested ternary operator. One ternary operator used in other ternary operators is called nested ternary operator.

Syntax,
a                        (a) ? (b ? c : d) : (e ? f : g)

We can also express it using the nested if else statement to understand it better

if  ( a )
abcif( b )
abcde execute c
abcelse
abcdefexecute d
else
abc if ( e )
abcdefexecute f
abcelse
abcdefexecute g

 

Now, we will try to implement it using C++ program. We will write a program to find the largest number among the three numbers.

#include <iostream>

using namespace std;

int main()
{
  int a,b,c,ans;
 
  std::cout<<"Enter the first number : ";
  std::cin>>a;
  std::cout<<"Enter the second number : ";
  std::cin>>b;
  std::cout<<"Enter the third number : ";
  std::cin>>c;
  
  ans = (a>b) ? ( a>c ? a : c) : ( b>c ? b : c);  //nested ternary operator to calculate highest among 3 nos.
  
  std::cout<<"The highest among all three numbers is : "<<ans;
}

Output:

Enter the first number : 10 
Enter the second number : 7
Enter the third number : 9 
The highest among all three numbers is : 10 

Also read,

 

Leave a Reply