In this C++ tutorial, you will learn how to write a C++ program to find the largest or maximum of given three numbers.
C++ – Find the Maximum of Three Numbers
You can find the maximum of three numbers in C++ in many ways. In this tutorial, we shall go through some of the processes using conditional statements.
1. Find maximum of three numbers using If-Else-If
In this example program, we shall use C++ If Else If statement to find the maximum of three numbers.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 55;
int c = 23;
int max;
if (a>b && a>c) {
max = a;
} else if (b>c) {
max = b;
} else {
max = c;
}
cout << max << endl;
}
Output
55
2. Find maximum of three numbers using Nested If-Else
In this example program, we shall use C++ Nested If Else statement to find the maximum of three numbers.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c = 2;
int max;
if (a > b) {
if (a > c) {
max = a;
} else {
max = c;
}
} else {
if (b > c) {
max = b;
} else {
max = c;
}
}
cout << max << endl;
}
Output
11
3. Find maximum of three numbers using simple If statement
In this example program, we shall use simple C++ If statement to find the maximum of three numbers.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c = 32;
int max;
if (a > b && a > c) {
max = a;
}
if (b > a && b > c) {
max = b;
}
if (c > a && c > b) {
max = c;
}
cout << max << endl;
}
Output
11
4. Find maximum of three numbers using Ternary Operator
In this example program, we shall use C++ Ternary Operator to find the maximum of three numbers.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c = 23;
int max = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) ;
cout << max << endl;
}
Output
23
Conclusion
In this C++ Tutorial, we learned how to find the maximum number of given three numbers using different conditional statements in C++.