Problem : Given an array of integers ,find the largest
element in it.
Examples:
Input :
array[]={12,34,65,98,15,34}
Output :
98
Input :
array[]={22,30,95,90,12,54}
Output :
95
Solution:
- We assume that first element of the array is the largest one.
- Then iterate the array and compare each element with the assumed largest element.
- If current element is larger than assumed largest element, we update the assumed largest element to current element. This process continues till all elements are checked.
// C program to find the largest element in an array
#include<stdio.h>
int
main(){
int array[]={76,90,87,98,56,77,91};
int max,arraySize=0;
//function declaration
int maxElement(int array[],int n);
//finding the size(no of elements) of array
arraySize = sizeof(array)/ sizeof(int);
//function calling
max=maxElement(array,arraySize);
printf("Maximum Element is %d.\n",max);
return 0;
}
//function
definition
int maxElement(int array[],int n){
int
max,i;
max=array[0]; //assume that first element is the largest
one
for (i = 1; i < n; i++){
if (array[i]>max){
max=array[i];
}
}
return max;
}
Output:
Please
comment if you find anything incorrect, or you want to improve the topic
discussed above.