WAP to find greatest among two numbers using ternary number
Objective
Write a C++ program to find the greatest of two numbers using the Ternary Operator.
Algorithm / Approach
- Read two numbers
aandb. - Use the conditional ternary operator:
(a > b) ? cout << "A is Greater" : cout << "B is greater".
main.cpp
#include<iostream>
using namespace std;
int main() {
int a,b;
cout<<"Enter Value for A: ";
cin>>a;
cout<<"Enter Value for B: ";
cin>>b;
(a>b)?cout<<"A is Greater":cout<<"B is greater ";
return 0;
}
Expected Output
Enter Value for A: 10 Enter Value for B: 20 B is Greater
Explanation of the Program
- The Ternary Operator (
? :) is a shorthand replacement for a simple if-else statement. - It evaluates the condition before the question mark. If the condition is true, it executes the code immediately after the question mark. If it is false, it executes the code after the colon.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)