C Program: Largest Element in an Array
Finding the largest element in an array is applicable on arrays of
type int,
float and
double since the greater-than or less-than
operations can be performed on numbers.
For the purpose of example here, we pick an array of typeint. But the algorithm works for arrays of type
float and
double also. You can replace the array
n[] in the program below with elements of
type float or
double, and the program would still work.
We first find the number of elements in the given array using the
sizeof() operator as done
here. The maximum number or
max in the below C program is first
assigned to the first element. The logic is simple. Comparisons then
start from the first to the last element of the array, assigning
max with the greater of the two whenever
applicable.
#include <stdio.h>
int main() {
int max, n[] = {70, 89, -32, 12, 9, 73, 12, 88, 19};
unsigned short length, i = 0;
length = sizeof(n)/sizeof(int);
max = n[0];
while(i < length) {
if(n[i] > max)
max = n[i];
i++;
}
printf("Largest element in the array is: %d", max);
return 0;
}
The output of the above program would be
Largest element in the array is: 89