Customizable training materials to learn C++

Nano teach C++ found result for your search here:

C++ Program to demonstrate the 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.
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;
    system("pause");
    return 0; 

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

No comments:

Post a Comment