Tuesday, 26 February 2019

C program to find minimum and maximum elements in an array

Problem : Given an array of integers ,find the smallest element in it.
Examples:
       Input : array[]={76,90,87,98,56,77,91}
       Output :
          Maximum : 98
          Minimum : 56
Solution:
   Minimum Element:
  1. We assume that first element of the array is the minimum one.
  2. Then iterate the array and compare each element with the assumed minimum element.
  3. If current element is minimum than assumed minimum element, we update the assumed minimum element to current element. This process continues till all elements are checked.

Maximum Element:
  1. We assume that first element of the array is the maximum one.
  2. Then iterate the array and compare each element with the assumed maximum element.
  3. If current element is larger than assumed largest element, we update the assumed maximum element to current element. This process continues till all elements are checked.


// C program to find the minimum and maximum elements in an array
#include<stdio.h>
    int main(){
       int array[]={76,90,87,98,56,77,91};
       int max,min,arraySize=0,i;
      //finding the size(no of elements) of array
       arraySize = sizeof(array)/ sizeof(int);
       max=array[0];  //assume that first element is the maximum one
       min=array[0];  //assume that first element is the minimum one
       for (i = 1; i < arraySize; i++){             
         if (array[i]>max){
            max=i;
         }
        if (array[i]<min){
            min=i;
         }            
       }
       printf("Maximum Element is %d at position %d.\n",array[max],max);
       printf("Minimum Element is %d at position %d.\n",array[min],min);
 return 0;
}
Output:

Please comment if you find anything incorrect, or you want to improve the topic discussed above. 

No comments:

Post a Comment