How to find max and min element of array in C++

In this article, we will learn How to find max and min element of array in C++. We will iterate on a C++ array and try to find the maximum and minimum elements in the array.

Explanation:How to find max and min element of array in C++


  • We first accept the size of the array from the user.
  • Next, we will ask the user to enter the elements as per the size given.
  • We assume the first elements of the array is MaxElement and MinElement. This is just an assumption.
  • Next, we will apply the logic to find the actual maximum and minimum elements in the array.
  • To find the maximum element we will compare each element with our assumed maximum element and update it if a higher value is found.
  • To find the minimum element we will compare each element with our assumed minimum element and update it if a lower value is found.

split Pandas DataFrame column by single Delimiter


#define MAX_SIZE 250 

#include <iostream>
using namespace std;
 
int main()
{
   int Array[MAX_SIZE];
   int Size;
   int MaxElement, MinElement;
 
    cout<<"Please enter Size of the array (Max 250): ";
    cin>>Size;
	
     cout<<"Please enter elements in array: ";
    for(int i=0; i<Size; i++)
    {
        cin>>Array[i];
    }
 
    MaxElement = Array[0];
    MinElement = Array[0];
 

    for(int i=1; i<Size; i++)
    {
        if(Array[i] > MaxElement)
        {
            MaxElement = Array[i];
        }
 
        if(Array[i] < MinElement)
        {
            MinElement = Array[i];
        }
    }
    
 
    cout<<"The Maximum element in the Array is: "<<MaxElement<<endl;
    cout<<"The Minimum element in the Array is: "<<MinElement<<endl;
    return 0;
}

Output

Please enter Size of the array (Max 250): 9
Please enter elements in array: 12
13
14
50
60
70
100
90
30
20
The Maximum element in the Array is: 100
The Minimum element in the Array is: 12