OneBite.Dev - Coding blog in a bite size

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:

  1. The function FindMinMax takes an array of integers as input.
  2. Inside the function, two variables min and max are initialized to the first element of the array. These variables will hold the minimum and maximum values of the array respectively.
  3. A for loop is initiated that iterates from the second element of the array till the last one.
  4. 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, the max value is updated to the current element.
  5. Another if condition checks whether the current element is less than the current minimum value min. If it is, the min value is updated to the current element.
  6. This process continuously updates the values of min and max as required, effectively finding the minimum and maximum values in the array.
  7. Once all elements of the array have been checked, the min and max values are printed using Console.WriteLine.
  8. In this way, you can find the minimum and maximum element in an array in C#.
c-sharp