Sunday, July 20, 2014

Conditional Execution Using Operator (?:)

Conditional Execution Using Operator (?:)
C++ has an interesting and powerful operator called the conditional operator that is similar to a compacted if-else construct.
Syntax:
(conditional expression evaluated to bool) ? expression1 if true : expression2 if false;

Such an operator can be used in compactly evaluating the greater of two given numbers,
as seen here:
int a=8, b=12, max;
max = (a > b)? a : b; // max contains greater of a and b

Example:
#include <iostream>
using namespace std;
int main(){
    cout << “Enter two numbers: ” << endl;
    int a = 8, b = 0;
    cin >> a;
    cin >> b;
    int max = (a > b)? a : b;
    cout << “The greater of “ << a << “ and  "<< b << “ is: “ << max << endl;
    return 0;

    getch();
}
Output:
Enter two numbers: 
123
27
The greater of 123 and 27 is: 123 

No comments:

Post a Comment