Thursday, December 9, 2010

Conditional (Ternary) Operator in c++ [? :]


Conditional (Ternary) Operator in c++ [? :]


The condional 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 ternary operator.

For example, consider the assignment statement :
x = y > 3 ? 2 : 4;
If y is greater than 3 then 2 will be assigned to variable x or else the value 4 will be assigned to x.

/* A simple c++ program example to demonstrate the use of ternary operator. */


// Program 1


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "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;
}


Compare the above "Program 1" and below "Program 2" with "Program 2" and "Program 3" of Selection Statement (if-else if-else) in c++ respectively, for better understanding.

/* A c++ program example to demonstrate the use ternary operator.*/


// Program 2


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "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 < second ? "first is less than second" :
                                "first and second are equal";

    cout << message << endl;

    return 0;
}

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters

7 comments:

  1. This is a great blog. You helped me study for my test today :)

    You should keep writing more posts, most of your explanations were a lot clearer than my professors!

    ReplyDelete
  2. Thanks for the tip! Now I can program even faster

    ReplyDelete
  3. can I PLEASE have your e-mail mr. HOMAM,THANKS 4 THE BLOG IT REALLY WORKS 4 ME

    ReplyDelete
  4. I really love your write-ups guys continue the good work.
    tutorial on c++

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete