C++ Conditional Operator
Conditional Operator [?:] : Ternary Operator in C++
- Conditional operators are also called as Ternary Operator.
- They are represented by ?:
- Ternary Operator takes on 3 Arguments.
Syntax of Ternary Operator:
Expression_1 ? Expression_2 : Expression_3
where
Explanation of syntax:
- Expression_1 is a condition so it will return the result either True or False.
- If result of expression_1 is True that is NON-ZERO, then Expression_2 is Executed.
- If result of expression_1 is False that is ZERO, then Expression_3 is Executed.
Program 1#: Conditional Operator Program
Let us take the simple example of finding greater number from two given numbers using Conditional Operator.
#include<iostream> using namespace std; int main() { int num1=10; int num2=20; num1>num2 ? cout << "num1 is greater than num2" : cout<< "num2 is greater than num1" ; return 0; }
Output:
num2 is greater than num1