Customizable training materials to learn C++

Looking for C++ Tutorial Visit Nano teach c++!
  • C++ Program Structure
    13/07/2014 - 0 Comments
    This tutorial will explain you about the C++ program structure. Basically a C++ program involves the following section. Documentations Preprocessor Statements Global…
  • C++ Program to find Prime Number
    02/07/2014 - 0 Comments
    A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. Example: #include<iostream> #include<math.h>…
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