find max and min in array in csharp

To find the maximum and minimum values in an array in C#, you can use a loop to iterate through the elements of the array and compare each element with the current maximum or minimum value. Here's an example:

main.cs
int[] arr = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 };
int max = arr[0];
int min = arr[0];

for (int i = 1; i < arr.Length; i++)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
    if (arr[i] < min)
    {
        min = arr[i];
    }
}

Console.WriteLine("Max: " + max);
Console.WriteLine("Min: " + min);
305 chars
19 lines

In this example, we initialize max and min to the first element of the array arr. We then loop through the rest of the array and update max and min if we find a larger or smaller element.

At the end of the loop, max and min will contain the maximum and minimum values in the array, respectively. We can then print these values to the console.

gistlibby LogSnag