How do you use foreach to loop through an array in C# to find the maximum value?
In C#, you can iterate through an array using a foreach loop and then check the size of each element to find the maximum value in the array. Here is an example code:
int[] array = { 1, 5, 3, 7, 2, 9 };
int max = array[0];
foreach (int num in array)
{
if (num > max)
{
max = num;
}
}
Console.WriteLine("The maximum value in the array is: " + max);
In the code above, we started by defining an integer array called array, and then initialized some elements. Next, we defined a variable max with the initial value being the first element of the array. We then used a foreach loop to iterate through each element in the array, and if any element’s value is greater than the current maximum value max, we updated max to be that element’s value. Finally, the output of max is the maximum value in the array.