# 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 // include stdio.h library #define MAX 5 int main(void) { int arr[MAX] = {50, -100, 20, 245, 0}, min, max; min = max = arr; // 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 } 

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<min=>50<50=>0 arr>max=>50>50=>0 min=50 max=50
2 arr<min=>-100<50=>1 arr>max=>-100>50=>0 min=-100 max=50
3 arr<min=>20<-100=>0 arr>max=>20>50=>0 min=-100 max=50
4 arr<min=>245<-100=>0 arr>max=>245>50=>1 min=-100 max=245
5 arr<min=>0<-100=>0 arr>max=>0>50=>0 min=-100 max=245