C Program to find largest element of array

Simple C program to find largest element of array. Here is simple C program to find largest element. First we initialize largest element (max) as arr[0]. Then compare it with all elements of array. If we find element greater than max we update it with that element other we do not update.
/*C program to find largest element of array */ 
#include<stdio.h>
#include<stdlib.h>
int main()
{
 int arr[6]={6,12,9,20,5,1};
 int i=0,max=arr[0];
 /* Here 6 is array size */
 for(i=0;i<6;i++)
 {
  if(max<arr[i])
  max=arr[i];
 }
 printf("Largest element of array = %d\n",max);
 return 0;
}
/* End of program */ 
Another C program to find largest element using while loop
/* C program to find largest element of array */ 
#include<stdio.h>
#include<stdlib.h>
int main()
{
 int arr[7]={12,56,32,90,12,4,28};
 int max=arr[0],i=0;
 while(i<7)
 {
  if(max<arr[i])
  {
  max=arr[i];
 }
  i++;
 }
 printf("Largest element of array = %d\n",max);
 return 0;
}
Another C program to find largest element of array using limits.h library 
Here INT_MIN is the minimum value that an integer can get in limits.h library. So if array element value is greater than max then we update max to array element.
/* C program to find largest element of array using limits.h library */ 
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int main()
{
 int arr[7]={20,5,32,9,12,4,28};
 int max=INT_MIN,i;
 for(i=0;i<7;i++)
 {
  if(max<arr[i])
  max=arr[i];
 }
 printf("Largest element of array = %d\n",max);
 return 0;
}



Popular posts from this blog