C++

How to Use min() Function in C++

C++ includes many functions for performing mathematical operations on numbers like sqrt, pow, cmp, max, min, and so on. These functions perform their own task according to their functionality. The min() is one of the widely used mathematical functions which is used in the comparison of multiple numbers. This article will briefly describe the min() function in C++.

What is the min() Function and How it Works in C++?

The min() function compares passed parameters to determine their minimum. If the two values are equivalent, the first value is returned. The min() function has many variations that apply to values as well as initializer lists. The header <algorithm> is required for this function. One can find the syntax to declare the min() function in C++ as follows:

Syntax

min(num_1, num_2)

Here num_1 and num_2 are numbers that are used to being compared. It gives the smaller of the two values num_1 and num_2.

Example 1

Let’s consider some examples that describe the working of the min() function.

#include <algorithm>

#include <iostream>

#include <string>

using namespace std;

int main()

{

cout << "minimum of 5 and 54 is: " << min(5, 54)<<endl;

cout << "minimum of 0.7 and 0.9 is: "<< min(0.7,0.9)<<endl;

cout << "minimum of 10 and -10 is: " << min(10,-10)<<endl;

cout << "minimum of x and a is: " << min('x','a')<<endl;

  return 0;

}

In the above example, we demonstrate the use of the min() function in C++ on different data types like int, char and float values. We also compared the numbers having opposite signs like 10 and -10.

Output

Example 2

This min() function additionally has the ability to identify the smallest element in a list. The following is an example of code:

#include <iostream>

#include<algorithm>

using namespace std;

int main()

{

int small_num=min({349,54,78});

cout<<"The smallest value is: "<<small_num;

return 0;

}

The result has been printed to the console.

Output

Conclusion

The min() function is a useful function in C++ that allows you to find the minimum value among a set of values. It is a pre-built function in C++ standard library that users can use by declaring the <algorithm> header file. The above guide presents simple examples to use min() function in C++. It will help the beginners to learn basics of this function.

About the author

Komal Batool Batool

I am passionate to research technologies and new ideas and that has brought me here to write for the LinuxHint. My major focus is to write on programming languages and computer science related topics.