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
#include <bits/stdc++.h>
using namespace std;
void find_greatest(int a, int b, int c, int d)
{
if (a > b) {
if (a > c) {
if (a > d) {
cout << "a is greatest";
}
else {
cout << "d is greatest";
}
}
}
else if (b > c) {
if (b > d) {
cout << "b is greatest";
}
else {
cout << "d is greatest";
}
}
else if (c > d) {
cout << "c is greatest";
}
else {
cout << "d is greatest";
}
}
int main()
{
int a = 10, b = 50, c = 20, d = 25;
cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d;
cout << "\n";
find_greatest(a, b, c, d);
a = 35, b = 50, c = 99, d = 2;
cout << "\n";
cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d;
cout << "\n";
find_greatest(a, b, c, d);
return 0;
}
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
#include <bits/stdc++.h>
using namespace std;
void find_greatest(int a, int b, int c, int d)
{
int x = max(a, max(b, max(c, d)));
if (x == a)
cout << "a is greatest";
if (x == b)
cout << "b is greatest";
if (x == c)
cout << "c is greatest";
if (x == d)
cout << "d is greatest";
}
int main()
{
int a = 10, b = 50, c = 20, d = 25;
cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d;
cout << "\n";
find_greatest(a, b, c, d);
a = 35, b = 50, c = 99, d = 2;
cout << "\n";
cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d;
cout << "\n";
find_greatest(a, b, c, d);
return 0;
}
Output
a=10 b=50 c=20 d=25
b is greatest
a=35 b=50 c=99 d=2
c is greatest