Monday, 20 March 2017

C Program to find Largest Element of Array in O(n) time

Tags

C Program to find the largest element of the array in O(n) time is given below. Approach is simple we traverse through the array and keep track of the largest element at every position. We will compare the largest element with each element of array during traversal and if the largest element is smaller than the element at current index of array, we will update the largest element.

PROGRAM:

#include <stdio.h>
int main()
{
   int n,arr[100],largest=0,i;

   printf("\nEnter the total number of elements: ");
   scanf("%d",&n);

   printf("\nEnter the elements of the array: \n");
   for(i=0;i<n;i++)
   {
          scanf("%d",&arr[i]);
   }

   for(i=0;i<n;i++)
   {
          if(largest<arr[i])
          {
                largest=arr[i];
          }
   }
   printf("\nThe largest element of array is: %d",largest);
   printf("\n");
   return 0;
}

OUTPUT:







EmoticonEmoticon