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.

Find Maximum of Three Number 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

Find Maximum of Three Number 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

Find Maximum of Three Number using Simple If

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

Find Maximum of Three Number 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++.