Find minimum and maximum values in an array in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <climits> #include <algorithm> using namespace std; int main() { int arr[] = { 4, 2, 1, 6, -8, 5 }; int min = INT_MAX, max = INT_MIN; for (int i: arr) { if (i < min) { min = i; } if (i > max) { max = i; } } std::cout << "The min element is " << min << std::endl; std::cout << "The max element is " << max << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = { 4, 2, 1, 6, -8, 5 }; std::pair<int*, int*> minmax = std::minmax_element(std::begin(arr), std::end(arr)); std::cout << "The min element is " << *(minmax.first) << std::endl; std::cout << "The max element is " << *(minmax.second) << std::endl; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = { 4, 2, 1, 6, -8, 5 }; int *min = std::min_element(std::begin(arr), std::end(arr)); int *max = std::max_element(std::begin(arr), std::end(arr)); std::cout << "The min element is " << *min << std::endl; std::cout << "The max element is " << *max << std::endl; return 0; } |
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++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)