在下面的程序中,我们使用给定数组的第一个元素初始化变量(max_element),然后我们使用循环将该变量与数组的所有其他元素进行比较,每当我们得到一个值大于max_element的元素时,我们将该元素移动到max_element并使用相同的方法进一步移动以获取数组中的最大元素。
#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;}输出:
Largest element of array is 300
