C# - Array Finding Maximum, Minimum
To find the maximum and minimum elements in an array, you can iterate through the array and keep track of the maximum and minimum values found so far. Here's how you can do it in C#:
public static void FindMaxAndMin(int[] arr, out int max, out int min)
{
if (arr == null || arr.Length == 0)
{
// Handle the case when the array is empty or null
throw new ArgumentException("The array is empty or null.");
}
max = arr[0]; // Assume the first element is the maximum
min = arr[0]; // Assume the first element is the minimum
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] > max)
{
// Update the maximum value
max = arr[i];
}
else if (arr[i] < min)
{
// Update the minimum value
min = arr[i];
}
}
}
Usage example:
int[] numbers = { 10, 5, 8, 15, 3, 20 };
int maximum, minimum;
FindMaxAndMin(numbers, out maximum, out minimum);
Console.WriteLine($"Maximum: {maximum}"); // Output: Maximum: 20
Console.WriteLine($"Minimum: {minimum}"); // Output: Minimum: 3
The FindMaxAndMin method iterates through the array, comparing each element with the current maximum and minimum values found so far. If an element is greater than the current maximum, it updates the max variable. If an element is less than the current minimum, it updates the min variable. By the end of the loop, you will have the maximum and minimum elements in the max and min variables, respectively.