How to find the maximum and minimum values of an array in the C language?
One way to find the maximum and minimum values of an array is by using the following method:
- Define two variables, max and min, and initialize them with the first element of the array.
- Traverse the array, compare each element with max and min, and update the values of max and min.
- After the traversal is completed, the values of max and min will be the maximum and minimum values of the array.
Here is a sample code:
#include <stdio.h>
int main() {
int array[] = {5, 2, 9, 1, 7, 6, 3, 8, 4};
int size = sizeof(array) / sizeof(array[0]);
int max = array[0];
int min = array[0];
for (int i = 1; i < size; 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;
}
Executing the above code will result in:
最大值:9
最小值:1