C++ program to find greatest of four numbers
In this tutorial, we will write a C++ program to find the greatest of four numbers.
For example
a = 10, b = 50, c = 20, d = 25
The greatest number is b 50
a = 35, b = 50, c = 99, d = 2
The greatest number is c 99
Approach 1
The approach is the traditional way of searching for the greatest among four numbers. The if condition checks whether a is greater and then use if-else to check for b, another if-else to check for c, and the last else to print d as the greatest.
Algorithm
- START
- INPUT FOUR NUMBERS A, B, C, D
- IF A > B THEN
IF A > C THEN
IF A > D THEN
A IS THE GREATEST
ELSE
D IS THE GREATEST - ELSE IF B > C THEN
IF B > D THEN
B IS THE GREATEST
ELSE
D IS THE GREATEST - ELSE IF C > D THEN
C IS THE GREATEST - ELSE
D IS THE GREATEST
C++ Code
Output
a=10 b=50 c=20 d=25 b is greatest a=35 b=50 c=99 d=2 c is greatest
Approach 2
This approach uses the inbuilt max function.
Here is the syntax of max function
template constexpr const T& max (const T& a, const T& b);
Here, a and b are the numbers to be compared.
Return: Larger of the two values.
For example
std :: max(2,5) will return 5
So, to find out the maximum of 4 numbers, we can use chaining of a max function as follows –
int x = max(a, max(b, max(c, d)));
C++ code
Output
a=10 b=50 c=20 d=25 b is greatest a=35 b=50 c=99 d=2 c is greatest