Find Max and Min Values in C: Code Example

To find the maximum and minimum values in an array, you can traverse through the array to locate them.

The following is an example code:

#include <stdio.h>

int main() {
    int arr[] = {5, 3, 8, 1, 9, 2, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
    int max = arr[0];
    int min = arr[0];
    
    for(int i = 1; i < n; i++) {
        if(arr[i] > max) {
            max = arr[i];
        }
        if(arr[i] < min) {
            min = arr[i];
        }
    }
    
    printf("最大值为:%d\n", max);
    printf("最小值为:%d\n", min);
    
    return 0;
}

In this code, first initialize an array arr and iterate through the elements in the array, updating the maximum and minimum values by comparing them with the current maximum and minimum values. Eventually, output the found maximum and minimum values.

bannerAds