0
0
CsharpProgramBeginner · 2 min read

C# Program to Find Second Largest Number in Array

You can find the second largest number in an array in C# by iterating through the array and tracking the largest and second largest values using variables, for example: int largest = int.MinValue, secondLargest = int.MinValue; foreach (int num in arr) { if (num > largest) { secondLargest = largest; largest = num; } else if (num > secondLargest && num != largest) { secondLargest = num; } }.
📋

Examples

Input[3, 5, 1, 2, 4]
Output4
Input[10, 10, 9, 8]
Output9
Input[5]
OutputNo second largest element
🧠

How to Think About It

To find the second largest number, first think about keeping track of the largest number you see as you look at each number in the array. Then, also keep track of the second largest number by updating it whenever you find a number that is smaller than the largest but bigger than the current second largest. This way, after checking all numbers, you will have the second largest stored.
📐

Algorithm

1
Initialize two variables: largest and secondLargest with the smallest possible integer value.
2
Loop through each number in the array.
3
If the current number is greater than largest, update secondLargest to largest and largest to current number.
4
Else if the current number is greater than secondLargest and not equal to largest, update secondLargest to current number.
5
After the loop, check if secondLargest was updated; if not, there is no second largest element.
6
Return or print the secondLargest value.
💻

Code

csharp
using System;
class Program {
    static void Main() {
        int[] arr = {3, 5, 1, 2, 4};
        int largest = int.MinValue, secondLargest = int.MinValue;
        foreach (int num in arr) {
            if (num > largest) {
                secondLargest = largest;
                largest = num;
            } else if (num > secondLargest && num != largest) {
                secondLargest = num;
            }
        }
        if (secondLargest == int.MinValue) {
            Console.WriteLine("No second largest element");
        } else {
            Console.WriteLine(secondLargest);
        }
    }
}
Output
4
🔍

Dry Run

Let's trace the array [3, 5, 1, 2, 4] through the code to find the second largest number.

1

Initialize variables

largest = -2147483648, secondLargest = -2147483648

2

Check first element 3

3 > largest (-2147483648), so largest = 3, secondLargest = -2147483648

3

Check second element 5

5 > largest (3), so secondLargest = 3, largest = 5

4

Check third element 1

1 > secondLargest (3)? No, no change

5

Check fourth element 2

2 > secondLargest (3)? No, no change

6

Check fifth element 4

4 > secondLargest (3) and 4 != largest (5), so secondLargest = 4

7

End of loop

largest = 5, secondLargest = 4

IterationCurrent NumberLargestSecond Largest
133-2147483648
2553
3153
4253
5454
💡

Why This Works

Step 1: Track largest and second largest

We keep two variables to remember the biggest and second biggest numbers found so far as we look through the array.

Step 2: Update when bigger number found

If a number is bigger than the current largest, we move the largest to second largest and update largest to this new number.

Step 3: Update second largest carefully

If a number is not bigger than largest but bigger than second largest and not equal to largest, we update second largest to this number.

🔄

Alternative Approaches

Sort and pick second last
csharp
using System;
using System.Linq;
class Program {
    static void Main() {
        int[] arr = {3, 5, 1, 2, 4};
        var distinctSorted = arr.Distinct().OrderByDescending(x => x).ToArray();
        if (distinctSorted.Length < 2) {
            Console.WriteLine("No second largest element");
        } else {
            Console.WriteLine(distinctSorted[1]);
        }
    }
}
This method is simpler but slower because sorting takes more time, especially for large arrays.
Use LINQ Max and remove largest
csharp
using System;
using System.Linq;
class Program {
    static void Main() {
        int[] arr = {3, 5, 1, 2, 4};
        int max = arr.Max();
        var filtered = arr.Where(x => x != max);
        if (!filtered.Any()) {
            Console.WriteLine("No second largest element");
        } else {
            Console.WriteLine(filtered.Max());
        }
    }
}
This approach uses LINQ for clarity but iterates multiple times, which can be less efficient.

Complexity: O(n) time, O(1) space

Time Complexity

The program loops through the array once, so the time grows linearly with the number of elements, making it O(n).

Space Complexity

Only a few variables are used to track values, so the extra space is constant, O(1).

Which Approach is Fastest?

The single pass method is fastest because it only loops once. Sorting or multiple LINQ calls take more time.

ApproachTimeSpaceBest For
Single pass trackingO(n)O(1)Large arrays, best performance
Sort and pick second lastO(n log n)O(n)Small arrays or when sorting needed anyway
LINQ Max and filterO(n)O(n)Readable code, small to medium arrays
💡
Always check if the array has at least two distinct elements before finding the second largest.
⚠️
Beginners often forget to handle cases where all elements are equal or the array has less than two elements.