Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
math
communitycreator

How to use min() function in C++

Harsh Jain

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;
}
Use min() function in C++

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.

RELATED TAGS

c++
math
communitycreator
RELATED COURSES

View all Courses

Keep Exploring