In this program, you will write how to find the maximum or minimum element in an array.
#include<stdio.h>
int main()
{
int a[50],i,j,max,min,n;
printf("\nenter the size of array:");
scanf("%d",&n);
printf("enter element in array:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
/* Assume first array element as maximum and minimum */
max=a[0];
min=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
printf("largest number: %d",max);
printf("\nsmallest number: %d",min);
return 0;
}
enter the size of array:6 enter element in array:1 4 6 3 2 5 largest number: 6 smallest number: 1
n
.a
.max
and min
.1
to n
. inside the loop check the a[i]> max
. In the beginning, a[i] is your second element and max is your first element. you will compare both elements if your second element i.e a[i]
greater than max
(first array element) then make the max element as the second element, similarly, you will compare your max till n
iteration. in the end, you will get a max element of an array.min
element value in the array by comparing and storing the minimum value in the min variable.