How to Find the highest value of two numbers in C++ ?


There are multiple ways to find the highest value of two numbers in C++. Here are some of them:

  • Using if-else statement:
#include <iostream>
using namespace std;

int main() {
   int num1 = 10, num2 = 20;

   if (num1 > num2) {
      cout << "Highest value is " << num1 << endl;
   } else {
      cout << "Highest value is " << num2 << endl;
   }

   return 0;
}

Output: Highest value is 20

  • Using ternary operator:
#include <iostream>
using namespace std;

int main() {
   int num1 = 10, num2 = 20;
   int highest = (num1 > num2) ? num1 : num2;

   cout << "Highest value is " << highest << endl;

   return 0;
}

Output: Highest value is 20

  • Using std::max function:
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
   int num1 = 10, num2 = 20;
   int highest = max(num1, num2);

   cout << "Highest value is " << highest << endl;

   return 0;
}

Output: Highest value is 20



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.