C# Foreach Loop: Find Min Array Value

You can use a foreach loop to iterate through the array and find the smallest value. Here’s an example code:

int[] array = { 5, 3, 8, 1, 4 };
int min = array[0]; // 初始化最小值为数组的第一个元素

foreach (int num in array)
{
    if (num < min)
    {
        min = num;
    }
}

Console.WriteLine("最小值为: " + min);

In this example, we start by initializing min as the first element of the array, then use a foreach loop to iterate through each element in the array. If the current element is smaller than min, we update the value of min to that element. Finally, we output the minimum value.

bannerAds