C# - Smallest and Largest Elements of an Array

Here, we are going to learn how to find the smallest and largest elements of an array using predefined methods in C#?
By Nidhi Last updated : August 26, 2023

Problem statement

Given an array, we have to find the largest and smallest elements of the array.

Smallest and Largest Elements of an Array

In C# programming language, the largest element of an array can be found using the .max() method and the smallest element can be found using the .min() method. Both of these .max() and .min() are the methods of the C# Array class.

C# program to find the smallest and largest elements of an array

The source code to find the smallest and largest elements of the array using predefine methods is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to find the smallest and largest 
//elements of an array using predefined methods.

using System;
using System.Linq;

class Sample
{
    static void Main()
    {
        int[] MyArray = { 40,30,20,10,50 };

        int large = MyArray.Max();
        int small = MyArray.Min();

        Console.WriteLine("Largest Element  : " + large);
        Console.WriteLine("Smallest Element : " + small);
    }
}

Output

Largest Element  : 50
Smallest Element : 10
Press any key to continue . . .

Explanation

In the above program, we created a class Sample that contains an array of integers.

int large = MyArray.Max();
int small = MyArray.Min();

In the above code, we find the largest and smallest elements from the array. Here we need to import "System.Linq" namespace into the program.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.