C++ Program to Demonstrate Use of Ternary Operator

The conditional operator can often be used instead of the if else statement. Since it is the only operator that requires three operands in c++, It is also called the ternary operator.

Example:
X = Y > 5 ? 4 : 8;

If Y is greater than 5 then 4 will be assigned to variable X or else the value 8 will be assigned to X.

Example:
#include <iostream>
#include<iomanip> 
using namespace std;

int main (){

    int first, second;

    cout << "Please enter two integers." << endl;

    cout << "First" << setw (3) << ": ";
    cin >> first;

    cout << "Second" << setw (2) << ": ";
    cin >> second;

    string message = first > second ? "first is greater than second" : "first is less than or equal to second";

    cout << message << endl;
    return 0;
}

or

string message = first > second ? "first is greater than second" :
first < second ? "first is less than second" : "first and second are equal";

Explanation:
This program demonstrates the use of ternary operator using C++. So, first of all, you have to include the iostream header file using the "include" preceding by # which tells that the header file needs to be process before compilation, hence named preprocessor directive. The header <iomanip> is part of the Input/output library of C++. It defines the manipulator functions. Here it is used for using the setw(), which is inside this library. Now, for removing naming conflict you can use namespace statement within a program.

Then the main() function is declared with return type as integer. So, now you have to declare two integer type variables name 'first', 'second'. Then you have to print the message "Please enter two integers" using the cout<<""; statement. The setw() is used to change the width of the next input/output field. The cin statement is used twice which reputedly fetches the input given by the user for the variables first and second.

Then the conditional operator is used where the condition is checked whether the statement 'first > second'. If the condition becomes true, the string -
"first is greater than second" gets initialized to the string variable message and if the condition is false, the string:
"first is less than or equal to second" gets initialized to the variable message. Finally the string of the message gets displayed using the cout statement.



Here are few other related articles for you to read: