C Program to Find Largest & Smallest Number in Array with Position

C Program to Find the Largest and Smallest Number in Array with their Position | Here we will find the smallest and largest Array element with their position. Prerequisites:- Array in C

Find Smallest and Largest Number with their Position in Array using C

#include<stdio.h>
int main()
{
   int a[100], n, i, max, min, maxPos, minPos;

   printf("Enter array size [1-100]: ");
   scanf("%d",&n);
   maxPos=minPos=0;

   //Take array elements and find min and max
   printf("Enter array elements: ");
   scanf("%d",&a[0]);
   max=min=a[0];
   for(i=1; i<n; i++)
   {
      scanf("%d",&a[i]);
      if(max<a[i])
      {
         min=a[i];
         minPos=i;
      }
      if(min>a[i])
      {
         min=a[i];
         minPos=i;
      }
   }

   printf("Largest element is %d at %d position.\n", max,maxPos);
   printf("Smallest element is %d at %d position.", min,minPos);
   return 0;
}

Output:-

Enter array size [1-100]: 5
Enter array elements: 1 2 3 4 5
Largest element is 5 at 4 position.
Smallest element is 1 at 0 position.

Enter array size [1-100]: 4
Enter array elements: 50 9 5 10
Largest element is 50 at 0 position.
Smallest element is 5 at 2 position.

In this program initially, we assigned min and max element to the first element of the array. If there was only one element in the array then for loop will not be executed and that element becomes both min and max element. If array has more than one element than for loop executed. Inside for loop, when any element found bigger than max element than that element becomes max. Similarly happens with min also, if any element found lesser than min than that element becomes min. Finally, min and max displayed with their position.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Similar C programming examples on Arrays

2 thoughts on “C Program to Find Largest & Smallest Number in Array with Position”

  1. Shouldn’t it be the minPoz return 0? Since we start indexing from 0. So.. in array let’s say 1,2,3,4,5 Smallest element is 1 at position 0.

Leave a Comment

Your email address will not be published. Required fields are marked *