C++ Ternary Conditional Operator ?:

In this tutorial of our C++ course, we will learn what it is, what it is for, and how to use the ternary conditional operator ?:

Conditional Operator ?: in C++

The ?: operator is the only ternary in the language, that is, the only one that accepts three operands.

The syntax of this ternary conditional operator is:

  • condition ? statement1 : statement2 ;

Its operation is quite simple, the condition condition is tested.
If it is true, instruction statement1 is executed.
If the condition is false, statement2 that is executed.

It's basically an IF ELSE conditional test, but a simple, short one for executing single-line statements.

Let's redo some program examples we made using IF and ELSE, but now using the ternary operator?:

How to use the Ternary Operator ?:

You were hired to make a show for a concert hall. In a certain piece of code, you will ask the age of the customer. If you are of legal age (21 years or older), please let him know that he can buy the ticket. If you have less, your program should state that it cannot enter the house.

Our code looks like this:

#include <iostream>
using namespace std;

int main()
{
    int age;

    cout << "Your age: ";
    cin >> age;

    age>=21 ? (cout << "Ok you can come in!") :
              (cout << "You cannot buy tickets!") ;

    return 0;
}

Pretty simple, isn't it?

Ternary Operator ?: How to use it in C ++

Your teacher hired you to create a program that gets the student's grade. If it is 7.0 or higher, it has been approved. Otherwise, he is failed.

Using the ternary operator:

#include <iostream>
using namespace std;

int main()
{
    float grade;

    cout << "Your grade: ";
    cin >> grade;

    grade>=7 ? (cout << "Approved"):(cout << "Failed");

    return 0;
}

Much cleaner code.

Example of using ?:

Write a program that asks a person's salary. If it is greater than 3,000, you have to pay 20% tax. If it is smaller, it has to pay 15%. Display the amount of tax the person has to pay. Tax is theft?

#include <iostream>
using namespace std;

int main()
{
    float sal, tax;

    cout << "Your paycheck: ";
    cin >> sal;

    tax = sal>3000 ? 0.20 : 0.15;
    cout << "Taxes $ " << tax*sal <<endl;

    return 0;
}
This solution has become much more genius.
The tax variable will receive the return value from the conditional operator, which is 0.20 or 0.15.

Using the ternary operator ?: in C++

Write, using the ternary conditional operator, a program that takes an integer and tells you if it is even or odd.

#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Type a number ";
    cin >> num;

    num%2==0 ? cout <<"Even" : cout <<"Odd";

    return 0;
}

No comments:

Post a Comment