Customizable training materials to learn C++

Looking for C++ Tutorial Visit Nano teach c++!
  • C++ Program to find Perfect Number
    04/07/2014 - 0 Comments
    Perfect number is a positive number which sum of all positive divisors excluding that number. For example: 6 is Perfect Number since divisor of 6 are 1, 2 and 3. Sum of its…
  • C++ Loops, Creating a Pyramid
    05/07/2014 - 0 Comments
    C++ program to create a pyramid using for loop and if condition. Example: #include<iostream> using namespace std; int main() { int i,j,k,space=10; // to print the…
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