Find Largest Element in C Array

One common method in C language to find the largest element in an array is by using a loop to iterate through the array.

#include <stdio.h>

int main() {
    int arr[] = {5, 10, 3, 8, 2};
    int size = sizeof(arr) / sizeof(arr[0]);
  
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
  
    printf("最大元素是:%d\n", max);
  
    return 0;
}

In the code above, we define an integer array arr and initialize some elements. The size variable represents the size of the array. Then, we use a loop to iterate through the array, comparing each element to max. If the current element is greater than max, we update max to be the current element. Finally, we print the value of the maximum element.

Executing the above code will produce:

最大元素是:10

This indicates that the largest element in the array is 10.

bannerAds