# Program to find the Largest Number using Ternary Operator in C++

C++Server Side ProgrammingProgramming

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,

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

Live Demo

#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

Live Demo

#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

Live Demo

#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