HomeCSharpC# Program to Find Minimum and Maximum of Numbers in an Array

C# Program to Find Minimum and Maximum of Numbers in an Array

This C# program is designed to determine the minimum and maximum values within an array of integers. Finding the minimum and maximum values in a dataset is a common task in programming and data analysis. These values can provide essential insights into the data’s range and characteristics.

Problem statement

You are given an array of integers. Write a C# program that finds the minimum and maximum numbers in the array.

C# Program to Find Minimum and Maximum of Numbers in an Array

using System;

class Program
{
    static void FindMinMax(int[] arr, out int min, out int max)
    {
        if (arr.Length == 0)
        {
            throw new ArgumentException("The array cannot be empty");
        }

        min = max = arr[0];

        foreach (int num in arr)
        {
            if (num < min)
            {
                min = num;
            }

            if (num > max)
            {
                max = num;
            }
        }
    }

   static void Main()
    {
        int[] numbers = { 4, 2, 9, 7, 5, 1, 8, 3, 6 };

        int min, max;

        FindMinMax(numbers, out min, out max);

        Console.WriteLine("Minimum number: " + min);
        Console.WriteLine("Maximum number: " + max);
    }
}

How it works

The program is written in C# and is designed to find the minimum and maximum numbers in an array of integers. Here’s how it works:

  1. Method Definition (FindMinMax):
    • The program defines a method named FindMinMax that takes three parameters: an array of integers (arr), and two out parameters (min and max) which will be used to store the minimum and maximum values.
    • If the array is empty, it throws an ArgumentException with the message “The array cannot be empty”.
  2. Variable Initialization:
    • Within FindMinMax, min and max are initially set to the first element of the array (arr[0]). This provides a starting point for comparison.
  3. Iterating Through the Array:
    • A foreach loop is used to iterate through each element (num) in the array arr.
  4. Comparing and Updating:
    • For each element, the program checks if num is less than min. If so, it updates min to be equal.

Input/Output

C# Program to Find Minimum and Maximum of Numbers in an Array

Share:

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...