Ternary Operator for Quick Decisions

Ternary Operator for Quick Decisions

Medium C++ Operators 46 views
Explanation Complexity

Problem Statement

Use ternary operator (? :) as shorthand if-else.
Real Life: Quick one-line decisions in code.

Input Format

An integer N.

Output Format

Print

• Positive
OR

• Negative

Example

5
Positive

Constraints

• Integer value

Concept Explanation

The ternary operator (? :) is a short form of if-else.
It makes quick one-line decisions in code.

Step-by-Step Explanation

1.Take input number N.

2.Write condition using ternary operator:

• (N >= 0) ? "Positive" : "Negative"

3.If condition is true, first value is chosen.

4.If condition is false, second value is chosen.

5.Print the result.

Concept Explanation

The ternary operator (? :) is a short form of if-else.
It makes quick one-line decisions in code.

Step-by-Step Explanation

1.Take input number N.

2.Write condition using ternary operator:

• (N >= 0) ? "Positive" : "Negative"

3.If condition is true, first value is chosen.

4.If condition is false, second value is chosen.

5.Print the result.

Input / Output Format

Input Format
An integer N.
Output Format
Print

• Positive
OR

• Negative
Constraints
• Integer value

Examples

Input:
5
Output:
Positive

Example Solution (Public)

C++
void operator_q8_ternary() {
    int age = 20;
    
    string result = (age >= 18) ? "Adult" : "Minor";
    cout << "Age " << age << " is: " << result << endl;
    
    int a = 15, b = 25;
    int max = (a > b) ? a : b;
    cout << "Maximum of " << a << " and " << b << " is: " << max << endl;
}

Official Solution Code

void operator_q8_ternary() {
    int age = 20;
    
    string result = (age >= 18) ? "Adult" : "Minor";
    cout << "Age " << age << " is: " << result << endl;
    
    int a = 15, b = 25;
    int max = (a > b) ? a : b;
    cout << "Maximum of " << a << " and " << b << " is: " << max << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.