OneBite.Dev - Coding blog in a bite size

find the minimum and maximum element in an array in C

Code snippet on how to find the minimum and maximum element in an array in C

  #include<stdio.h>
  int main(){
      int arr[]={1, 5, 3, 4, 10};
      int size=5;
      int max, min; 
      int i; 
      min=arr[0];
      max=arr[0];
      for(i=0; i<size; ++i){
         if(arr[i]<min){
            min=arr[i]; 
         }
         if(arr[i]>max){
            max=arr[i];
         }
      }
      printf("Minimum element in array is %d\n",min);
      printf("Maximum element in array is %d\n",max);
      return 0;
   }

This code finds the minimum and maximum element from an array of integers. First, the size of the array is declared and a few variables are initialized. The min and max variables are set to the value of the first array element. Then, a for loop is initialized. The loop continues until the size of the array is reached. In the loop, if statements are used to compare the current array element value with the stored min and max values. If the array element is larger than the stored max value, the new max value is updated. Similarly, if the array element is smaller than the stored min value, the new min value is updated. Finally, the min and max values are printed out.

c