Find The Minimum And Maximum Element In An Array In C#
Code snippet for how to Find The Minimum And Maximum Element In An Array In C# with sample and detail explanation
Finding the minimum and maximum elements in an array in C# is a common problem that can be easily solved. This article will guide you through the steps of implementing a solution for this problem in a simplified way.
Code snippet: Finding Min and Max in an Array in C#
Here is a basic code snippet for finding the minimum and the maximum element in an array in C# :
public void FindMinMax(int[] array)
{
int min = array[0];
int max = array[0];
for (int i = 1; i < array.Length; i++)
{
if (array[i] > max)
{
max = array[i];
}
if (array[i] < min)
{
min = array[i];
}
}
Console.WriteLine("Minimum Value = "+min);
Console.WriteLine("Maximum Value = "+max);
}
Code Explanation: Finding Min and Max in an Array in C#
Here’s a step by step explanation of what the code is doing:
- The function
FindMinMax
takes an array of integers as input. - Inside the function, two variables
min
andmax
are initialized to the first element of the array. These variables will hold the minimum and maximum values of the array respectively. - A for loop is initiated that iterates from the second element of the array till the last one.
- Inside the loop, an if condition checks whether the current element in the array is greater than the current maximum value
max
. If it is, themax
value is updated to the current element. - Another if condition checks whether the current element is less than the current minimum value
min
. If it is, themin
value is updated to the current element. - This process continuously updates the values of
min
andmax
as required, effectively finding the minimum and maximum values in the array. - Once all elements of the array have been checked, the
min
andmax
values are printed usingConsole.WriteLine
. - In this way, you can find the minimum and maximum element in an array in C#.