How to find the maximum and minimum values of an array using the C language?

You can use the following C language code to find the maximum and minimum values in an array.

#include <stdio.h>

int main() {
    int array[] = {5, 9, 2, 4, 7, 1, 8, 6, 3};  // 假设数组为{5, 9, 2, 4, 7, 1, 8, 6, 3}

    int length = sizeof(array) / sizeof(int);  // 计算数组长度
    int max = array[0];  // 假设最大值为数组的第一个元素
    int min = array[0];  // 假设最小值为数组的第一个元素

    for (int i = 1; i < length; i++) {
        if (array[i] > max)  // 如果当前元素大于最大值,则更新最大值
            max = array[i];
        if (array[i] < min)  // 如果当前元素小于最小值,则更新最小值
            min = array[i];
    }

    printf("最大值:%d\n", max);
    printf("最小值:%d\n", min);

    return 0;
}

In the code above, an array is initially provided. The length of the array is calculated, with the assumption that the maximum and minimum values are the first element of the array. The code then iterates through each element of the array, updating the maximum and minimum values through comparison, and finally outputs the maximum and minimum values.

When executing the above code, the output result is:

最大值:9
最小值:1
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds