C program to find smallest of n numbers in a given array

 

C program to find smallest of n numbers in a given array

This C program is to find the smallest element from a given array.For example, if an array a consists of elements a={7,8,12,3} and if we want to find the smallest element then the smallest element would be 3.

Logic

We start to iterate and then compare all the elements with each other and store the smallest element in the variable named ‘small’ and then keep comparing till we find the smallest element.

 Dry Run of the Program

Take input array ‘a’ and no of elements(n) as 4

Let us take elements for array a={7,8,12,3}.

small=a[0] i.e. small=7

1st iteration  for(i=1;i<n;i++) i.e.  for(i=1;1<4;i++)

if(a[i]<small)  i.e. if(a[1]<7) i.e. if(8<7) false

2nd iteration  for(i=2;i<n;i++) i.e.  for(i=2;2<4;i++)

if(a[i]<small)  i.e. if(a[2]<7) i.e. if(12<7) false

3rd iteration  for(i=3;i<n;i++) i.e.  for(i=3;3<4;i++)

if(a[i]<small)  i.e. if(a[3]<7) i.e. if(3<7) true

small=a[i] i.e. small=a[3]  i.e. small=3

Now we come out of the for loop as i(4) is not less than n(4)

Hence, the smallest element we found in the array is 3

Program

#include<stdio.h>

void  main()
{
    int i,n,a[100],small;

    printf("Enter the number of elements:\n") ;
    scanf("%d",&n) ;
 
    printf("Enter the elements\n") ;
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]) ;
    }
    
    small=a[0];
    for(i=1;i<n;i++)   
    {
        if(a[i]<small)
        {
            small=a[i];
        }
    }
    printf("Smallest of %d elements in an array = %d",n,small);
}

Output

Share Me!