Thursday 9 June 2016

Largest number in array

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


Code 

#include<stdio.h>

int main()
{
    int n,a[10],max,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 largest element

    max = a[0];

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

    printf("\nLargest element = %d",max);

    return 0;
}


O/P



Code Tracing

i = 0    |   i = 1      |   i = 2      |   i = 3     |   i = 4
max = 5  |   6 > 5 ?    |   8 > 6 ?    |   9 > 8 ?   |   2 > 9 ?
         |   max = 6    |   max = 8    |   max = 9   |   max = 9

No comments:

Post a Comment