How to use a for loop to find the minimum value in C language?

You can use a for loop to iterate through an array and find the minimum value by comparing each element. Here is an example code using a for loop to find the minimum value.

#include <stdio.h>

#define SIZE 5  // 数组的大小

int main() {
    int arr[SIZE] = {10, 5, 8, 3, 15};
    int min = arr[0];  // 假设第一个元素为最小值

    for (int i = 1; i < SIZE; i++) {
        if (arr[i] < min) {
            min = arr[i];  // 找到更小的值,更新最小值
        }
    }

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

    return 0;
}

The code above first defines an integer array arr with a size of 5, assuming the first element arr[0] in the array is the minimum value. Next, it iterates through the array starting from the second element using a for loop, updating the minimum value if a smaller element is encountered. Finally, it outputs the minimum value. When running the above code, the result printed is the minimum value is: 3.

bannerAds