Dremendo Tag Line

Conditional Operator in C++ Programming

Decision Making in C++

In this lesson, we will understand what is Conditional Operator, and how to use it in C++ programming.

Conditional Operator

Conditional Operator in C++ return one value if the condition is true and returns another value if the condition is false. This operator is also called a Ternary Operator.

video-poster

Conditional Operator Syntax

(condition)  ?  true_value  :  false_value;

In the above syntax, we will write our condition in place of the condition if the condition is true then the true value will execute and if the condition is false then the false value will execute.

Now let's see an example for more understanding.

Example

C++ program to find the greatest number among two integer variable's value using the conditional operator.

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int a=10,b=5,c;

    c=(a>b) ? a : b;
    cout<<"Greatest number is "<<c;
    return 0;
}

Output

Greatest number is 10

Here you can see that the condition (a>b) is true so, the statement that is written just after the ? marks will execute and the value of a gets stored in c.

Nested Conditional Operator

Nested Conditional Operators are possible by including conditional expression as a second (after ?) or third part (after :) of the ternary operator.

Nested Conditional Operator Syntax

(condition)  ?  ((condition)  ? true_value :  false_value) : false_value;
(condition)  ?  true_value : ((condition)  ? true_value :  false_value);

In the above two syntaxes, on line number 1 you can clearly see that if the first condition is true then we are checking another condition just after the ? mark of the first condition. In the same way on line number 2 if the first condition is true then the true value will execute and if it is false then we are checking another condition just after the : mark of the first condition.

Now let's see an example for more understanding.

Example

C++ program to find the greatest number among 3 integer variable's value using the nested conditional operator.

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int a=10,b=50,c=26,g;

    c=(a>b && a>c) ? a : ((b>a && b>c) ? b : c);
    cout<<"Greatest number is "<<c;
    return 0;
}

Output

Greatest number is 50

Here you can see that the condition (a>b && a>c) is false so, we are checking another condition (b>a && b>c) that is written just after the : marks of the first condition and this time the condition is true so the value of b gets stored in c.