How to use Ternary Operator In C++
Ternary operators are simply the replacement of if-else statements. In this approach, we compare numbers as the two pairs of two numbers. Then, the bigger numbers from each of these comparisons are compared and the greater number among them is the largest number among the four numbers.
Algorithm
- Greater among a and b is Max1.
- Greater among c and d is Max2.
- Greater among Max1 and Max2 is Max3.
- Print Max3 as it is greatest.
Program to Check Largest Number among Four Number using Ternary Operator
C++
// C++ program to Check Largest Number among Four Number // using Ternary Operator #include <iostream> using namespace std; int main() { double a = 1, b = 2, c = 4, d = 3; double Max1, Max2, Max3; // bigger number among a and b Max1 = (a > b) ? a : b; // bigger number among c and d Max2 = (c > d) ? c : d; // comparing the numbers from first and second // comparison to get the max among all four numbers Max3 = (Max1 > Max2) ? Max1 : Max2; cout << Max3 << endl; // Another way but it is too long // cout << (a < b ? ((b > c)? ((b > d)? b:d) :((c > d)? // c: d)) : ((a < c)? ((c > d)? c: d) : ((a > d) ? a : // d))) << endl; return 0; } |
4
C++ Program to Find Largest Among Four Numbers
In this article, we will see how to find the largest among four numbers in a C++ program.
Examples:
Input: a = 1, b = 2, c = 4, d = 3
Output: 4
Input: a = 0, b = -1, c = -3, d = -2
Output: 0