Posted By:
21 Jun, 2013 9:12 am PDT

Arrays in C

How to find the maximum and minimum element in a given array?
Attachment:None


We can use a for loop to search through the array and use the if loop to check whether the min or max is that element.

The code for finding the max element is

max = a[0];

for(i=0;i<n;i++)

{

    if(max<a[i])

    {

        max = a[i];

    }

}

 

The code for finding the min element is

min = a[0];

for(i=0;i<n;i++)

{

    if(min>a[i])

    {

        min = a[i];

    }

}

printf("\n Minimum element in given array is %d",min);

getch();

}

 

The entire code is

 #include"stdio.h"

#include"conio.h"

 

int main()

{

int a[20],i,n,max,min;

printf("\n Enter number of elements: ");

scanf("%d",&n);

printf("\n Enter %d elements.\n",n);

for(i=0;i<n;i++)

 scanf("%d",&a[i]);

 

max = a[0];

for(i=0;i<n;i++)

 {

 if(max<a[i])

  {

  max = a[i];

 }

}

printf("\n Maximum element in given array is %d",max);

 

min = a[0];

for(i=0;i<n;i++)

 {

 if(min>a[i])

 {

  min = a[i];

 }

}

printf("\n Minimum element in given array is %d",min);

getch();

}

 

 Please see the video for more details.

Was it useful?  




Please login to reply to this problem.



Related Problems on Fixoncloud