C# Program to find the largest element from an array

Finding the largest element in an array is a common programming task in C#. There are multiple approaches to achieve this, ranging from using built-in LINQ methods to implementing custom logic with loops.

Using LINQ Max() Method

The simplest approach is to use the Max() method from the System.Linq namespace −

using System;
using System.Linq;

class Demo {
    static void Main() {
        int[] arr = { 20, 50, -35, 25, 60 };
        int largest = arr.Max();
        Console.WriteLine("Largest element: " + largest);
    }
}

The output of the above code is −

Largest element: 60

Using Traditional Loop Approach

You can also find the largest element using a for loop without LINQ −

using System;

class Demo {
    static void Main() {
        int[] arr = { 20, 50, -35, 25, 60 };
        int largest = arr[0];
        
        for (int i = 1; i < arr.Length; i++) {
            if (arr[i] > largest) {
                largest = arr[i];
            }
        }
        
        Console.WriteLine("Largest element: " + largest);
    }
}

The output of the above code is −

Largest element: 60

Using foreach Loop

A foreach loop provides a cleaner approach for iterating through array elements −

using System;

class Demo {
    static void Main() {
        int[] arr = { 20, 50, -35, 25, 60 };
        int largest = arr[0];
        
        foreach (int element in arr) {
            if (element > largest) {
                largest = element;
            }
        }
        
        Console.WriteLine("Largest element: " + largest);
        Console.WriteLine("Array: [" + string.Join(", ", arr) + "]");
    }
}

The output of the above code is −

Largest element: 60
Array: [20, 50, -35, 25, 60]

Comparison of Methods

Method Pros Cons
LINQ Max() Simple, one-line solution Requires System.Linq, slightly slower
For Loop Fast, no external dependencies More verbose code
Foreach Loop Clean syntax, readable Slightly more code than LINQ

Conclusion

Finding the largest element in an array can be accomplished using LINQ's Max() method for simplicity, or with traditional loops for better performance. The LINQ approach is preferred for readability, while manual loops offer more control over the process.

Updated on: 2026-03-17T07:04:35+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements