
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Largest Number Using Ternary Operator in C++
In this problem, we are given some numbers. Our task is to create a Program to Find the Largest Number using Ternary Operator in C++.
The elements can be −
- Two Numbers
- Three Numbers
- Four Numbers
Code Description − Here, we are given some numbers (two or three or four). We need to find the maximum element out of these numbers using a ternary operator.
Let’s take a few examples to understand the problem,
Two Numbers
Input − 4, 54
Output − 54
Three Numbers
Input − 14, 40, 26
Output − 40
Four Numbers
Input − 10, 54, 26, 62
Output − 62
Solution Approach
We will use ternary Operator, for two, three and four element for finding the maximum element of the four.
Implementing Ternary operator for
Two numbers (a, b),
a > b ? a : b
Three numbers (a, b, c),
(a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c)
Four numbers (a, b, c, d),
(a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d
Program to illustrate the working of our solution for two numbers −
Example
#include <iostream> using namespace std; int main() { int a = 4, b = 9; cout<<"The greater element of the two elements is "<<( (a > b) ? a :b ); return 0; }
Output
The greater element of the two elements is 9
Program to illustrate the working of our solution for three numbers −
Example
#include <iostream> using namespace std; int findMax(int a, int b, int c){ int maxVal = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c); return maxVal; } int main() { int a = 4, b = 13, c = 7; cout<<"The greater element of the two elements is "<<findMax(a, b,c); return 0; }
Output
The greater element of the two elements is 13
Program to illustrate the working of our solution for four numbers −
Example
#include <iostream> using namespace std; int findMax(int a, int b, int c, int d){ int maxVal= ( (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d ); return maxVal; } int main() { int a = 4, b = 13, c = 7, d = 53; cout<<"The greater element of the two elements is "<<findMax(a, b, c, d); return 0; }
Output
The greater element of the two elements is 53