How to use min() function in C++

The min() function in C++ accepts two values and returns the smaller one. This function is available in <algorithm.h>.

Parameters

The min() 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 the two values of 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 min() function returns the minimum 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 = min(10, 20);
cout << "Minimum is: " << int_result << endl;
char char_result = min('a', 'b');
cout << "Minimum is: " << char_result;
return 0;
}

Explanation

  • In lines 1 and 2, we import the required header files.
  • In line 6, we call the min() function and pass two integer values.
  • In line 7, we print the minimum of the two integers.
  • In line 9, we again call the min() function, but here we pass two character values.
  • In line 10, we print the minimum of the two character values.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources