C# Program to Find Largest Number in Array
int max = arr[0]; foreach (int num in arr) { if (num > max) max = num; }.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int[] arr = {3, 5, 1, 9, 2}; int max = arr[0]; foreach (int num in arr) { if (num > max) { max = num; } } Console.WriteLine(max); } }
Dry Run
Let's trace the array [3, 5, 1, 9, 2] through the code to find the largest number.
Initialize max
max = 3 (first element)
Compare with 5
5 > 3, so max = 5
Compare with 1
1 > 5? No, max stays 5
Compare with 9
9 > 5, so max = 9
Compare with 2
2 > 9? No, max stays 9
Result
Largest number is 9
| Current Number | max Value |
|---|---|
| 3 | 3 |
| 5 | 5 |
| 1 | 5 |
| 9 | 9 |
| 2 | 9 |
Why This Works
Step 1: Start with first element
We assume the first number is the largest to have a starting point for comparison.
Step 2: Compare each element
We check each number using if (num > max) to find if it is bigger than the current largest.
Step 3: Update largest value
When a bigger number is found, we update max to that number to keep track of the largest.
Step 4: Final largest number
After checking all numbers, max holds the largest number in the array.
Alternative Approaches
using System; using System.Linq; class Program { static void Main() { int[] arr = {3, 5, 1, 9, 2}; int max = arr.Max(); Console.WriteLine(max); } }
using System; class Program { static void Main() { int[] arr = {3, 5, 1, 9, 2}; int max = arr[0]; for (int i = 1; i < arr.Length; i++) { if (arr[i] > max) { max = arr[i]; } } Console.WriteLine(max); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so the time grows linearly with the array size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Using a simple loop or LINQ's Max() both run in O(n) time, but LINQ is more concise while loops give more control.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Foreach loop | O(n) | O(1) | Clear logic and beginner-friendly |
| For loop with index | O(n) | O(1) | When index is needed for extra logic |
| LINQ Max() | O(n) | O(1) | Concise code and readability |