This post will discuss how to find the minimum and maximum element in an array in C++.

1. Naive solution

A naive solution is to write our own routine for this simple task. The idea is to linearly traverse the array using simple for-loop or range-based for-loop. Then for each encountered element, we compare it against the minimum or maximum element found so far, and replace the maximum element found so far by the current element if it is less in value and the minimum element found so far by the current element if it is more in value.

Download  Run Code

Output:

The min element is -8
The max element is 6

2. Using minmax_element() function

The recommended solution is to use the std::minmax_element to find the smallest and largest array elements. It returns a pair of iterators with the first value pointing to the minimum element and the second value pointing to the maximum element. It is defined in the <algorithm> header.

Download  Run Code

Output:

The min element is -8
The max element is 6

3. Using min_element() with max_element() function

C++ standard library also provides individual functions min_element() and max_element() to find smallest and largest elements in array, respectively.

Download  Run Code

Output:

The min element is -8
The max element is 6

That’s all about finding the minimum and maximum values in an array in C++.