Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
math
communitycreator

How to use the max() function in C++

Harsh Jain

The max() function in C++ accepts two values and returns the larger one. This function is available in <algorithm.h>. The max() function helps during coding contests when you want to find the maximum of two values in the logic. Instead of writing this logic explicitly, you can thus use this function as-is.

Parameters

The max() function accepts the following parameters.

  • first_value: This is the first value that we want to compare.

  • second_value: This is the second value to compare with the first one.

    You need to pass two values of the same type.

  • comparator: This is an optional parameter that specifies the condition when the first value should come and when the second value should come. In other words, you can pass a function that returns a Boolean value that denotes which value to pick out of the two given values.

Return

The max() function returns the maximum value from the two given values.

Code

Let’s look at the code now.

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
  int int_result = max(10, 20);
  cout << "Maximum is: " << int_result << endl;

  char char_result = max('a', 'b');
  cout << "Maximum is: " << char_result;
  return 0;
}
Use max() function in C++

Explanation

  • In lines 1 and 2, we import the required header files.
  • In line 6, we call the max() function and pass two integer values.
  • In line 7, we print the maximum of the two integers.
  • In line 9, we again call the max() function, but here we pass two character values.
  • In line 10, we print the maximum of the two character values.

RELATED TAGS

c++
math
communitycreator
RELATED COURSES

View all Courses

Keep Exploring