Program to find Maximum and Minimum element in Array C++

Today we will a program to find the maximum and minimum element in array c++, let’s start how it works

How it Works:

  • Declare array of size 10
  • Using for loop assign array indexes with random values between 1 and 1000.
  • Call the function and pass array and its size as argument.
  • Function declares two integers max and min and assign both integers with arrays first index value.
  • Then with in for loop there are two if condition first check is for minimum number and second check is for maximum number.
  • Finally program display the output values of both integers min and max.

Following is the program to find maximum and minimum element in array:

#include <iostream>
#include <stdlib.h>
using namespace std;
void FindMaxMin(int *array, int size)
{        int min,max;
         min=max=array[0];
         for(int i=0;i<size;i++)
         {
             if(array[i]<min)
               min=array[i];
            else if(array[i]>max)
               max=array[i];
         }
 cout<<"Minimum Number  = "<<min<<endl;
 cout<<"Maximum Number = "<<max<<endl;
}
int main()
{
    int array[10];
    for(int i=0;i<=9;i++)
        {
         array[i]=rand()%1000+1;
         cout<<"array ["<<i<<"]"<<"= "<<array[i]<<endl;
        }
    FindMaxMin(array,10);
return 0;
}

 

OUTPUT:

array [0]= 42
array [1]= 468
array [2]= 335
array [3]= 501
array [4]= 170
array [5]= 725
array [6]= 479
array [7]= 359
array [8]= 963
array [9]= 465
Minimum Number  = 42
Maximum Number = 963

--------------------------------
Process exited after 0.01545 seconds with return value 0
Press any key to continue . . .

 

1 thought on “Program to find Maximum and Minimum element in Array C++”

Leave a Comment