OneBite.Dev - Coding blog in a bite size

Find The Minimum And Maximum Element In An Array In C++

Code snippet for how to Find The Minimum And Maximum Element In An Array In C++ with sample and detail explanation

In this article, we are going to learn how to find the minimum and maximum elements in an array in C++. This is a fundamental concept in array manipulation and is widely used in data processing tasks.

Code snippet for Finding Minimum and Maximum Element in Array

Here is a simple C++ program that will find the minimum and maximum elements in an array.

#include<iostream>
using namespace std;

int main(){
   int arr[5] = {5, 10, 1, 20, 15}; 
   int size = sizeof(arr)/sizeof(arr[0]);

   int max = arr[0]; 
   int min = arr[0];

   for(int i = 1; i < size; i++){
      if(arr[i] > max)
         max = arr[i]; 
      
      if(arr[i] < min)
         min = arr[i]; 
   }

   cout << "Maximum Element: " << max << endl;
   cout << "Minimum Element: " << min << endl;
   
   return 0;
}

This program will output:

Maximum Element: 20
Minimum Element: 1

Code Explanation for Finding Minimum and Maximum Element in Array

In the above code snippet, we first initialize an array arr with five elements and find its size using sizeof(arr)/sizeof(arr[0]).

We initially assume that the first element of the array is the minimum and the maximum. Therefore, we assign the first element of the array to both min and max.

We then run a for loop from the second element of the array (i.e., i=1) to the last element.

Inside the loop, we compare each array element with max. If the array element is greater than max, that array element becomes the new max. This process is repeated for the entire array, so by the end of the for loop, max contains the maximum value in the array.

Similarly, we compare each array element with min. If the array element is less than min, that array element becomes the new min. By the end of the loop, min contains the minimum value in the array.

Finally, we print out the maximum and minimum elements in the array using cout.

That’s it! You can now find the minimum and maximum values in an array in C++. This method can be used for any size of the array. Just make sure to update the array and its size accordingly.

c-plus-plus