In the following program we are initializing a variable (max_element) with the first element of given array and then we are comparing that variable with all the other elements of the array using loop, whenever we are getting an element with the value greater than max_element, we are moving that element to max_element and moving further with the same approach to get the largest element in the max_element variable.
#include <stdio.h> /* This is our function to find the largest * element in the array arr[] */ int largest_element(int arr[], int num) { int i, max_element; // Initialization to the first array element max_element = arr[0]; /* Here we are comparing max_element with * all other elements of array to store the * largest element in the max_element variable */ for (i = 1; i < num; i++) if (arr[i] > max_element) max_element = arr[i]; return max_element; } int main() { int arr[] = {1, 24, 145, 20, 8, -101, 300}; int n = sizeof(arr)/sizeof(arr[0]); printf("Largest element of array is %d", largest_element(arr, n)); return 0; }
Output:
Largest element of array is 300
Leave a Reply