OverIQ.com

C Program to find the maximum and minimum element in the array

Last updated on September 23, 2020


The following is a C program to find the maximum and minimum element in the array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*********************************************************
 Program to find maximum and minimum element in the array 
 *********************************************************/

#include<stdio.h> // include stdio.h library
#define MAX 5

int main(void)
{    
    int arr[MAX] = {50, -100, 20, 245, 0},
            min, max;

    min = max = arr[0]; // assign the first element to max and min

    for(int i = 0; i < MAX; i++)
    {
        if(arr[i] < min)
        {
            min = arr[i];
        }

        if(arr[i] > max)
        {
            max = arr[i];
        }
    }        

    printf("Min = %d\n", min);
    printf("Max = %d", max);

    return 0; // return 0 to operating system
}

Try it now

Expected Output:

1
2
Min = -100
Max = 245

How it works #

We use the for loop to iterate over the elements in the array. If the current element in the array is smaller than the min , we assign that value to min. Similarly, if the current element is larger than max, we assign that value to the max. When the loop terminates we print the value of min and max variable:

The following table demonstrates what happens at each iteration of the for loop:

Iteration Condition 1 Condition 2 min max
1 arr[0]<min=>50<50=>0 arr[0]>max=>50>50=>0 min=50 max=50
2 arr[1]<min=>-100<50=>1 arr[1]>max=>-100>50=>0 min=-100 max=50
3 arr[2]<min=>20<-100=>0 arr[2]>max=>20>50=>0 min=-100 max=50
4 arr[3]<min=>245<-100=>0 arr[2]>max=>245>50=>1 min=-100 max=245
5 arr[4]<min=>0<-100=>0 arr[4]>max=>0>50=>0 min=-100 max=245