Thursday, 9 June 2016

Smallest number in array

Take 1st element of array as min.Now for all elements in array,if an element is smaller than min then update the min else proceed.Atlast when all elements are traversed you will get the min element.


Code 

#include<stdio.h>

int main()
{
    int n,a[10],min,i;

    printf("Enter no of elements in array ");
    scanf("%d",&n);

    printf("\nEnter elements ");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    //calculate smallest element

    min = a[0];

    for(i=0;i<n;i++)
        if(a[i]<min)
            min = a[i];

    printf("\nSmallest element = %d",min);

    return 0;
}


O/P



Code Tracing

i = 0    |   i = 1      |   i = 2      |   i = 3     |   i = 4
min = 9  |   8 < 9 ?    |   6 < 8 ?    |   2 < 6 ?   |   5 < 2 ?
         |   min = 8    |   min = 6    |   min = 2   |   min = 2

No comments:

Post a Comment