c program to find maximum and minimum number in an array

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;
}

output

enter the size of array:6
enter element in array:1 4 6 3 2 5
largest number: 6
smallest number: 1

explanation of finding a maximum or minimum element in an array

  1. Take the size of an array from a user and stored it in variable n.
  2. Take n element from the user and store it in an array a.
  3. declare first array element max and min.
  4. iterate the for loop from 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.
  5. similarly, you will find the min element value in the array by comparing and storing the minimum value in the min variable.