C Program to Find Largest Element in Array
for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; }.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int arr[] = {3, 5, 1, 9, 2}; int n = sizeof(arr) / sizeof(arr[0]); int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } printf("Largest element is %d\n", max); return 0; }
Dry Run
Let's trace the array {3, 5, 1, 9, 2} through the code to find the largest element.
Initialize max
max = 3 (first element)
Compare arr[1] = 5 with max = 3
5 > 3, so max = 5
Compare arr[2] = 1 with max = 5
1 > 5? No, max stays 5
Compare arr[3] = 9 with max = 5
9 > 5, so max = 9
Compare arr[4] = 2 with max = 9
2 > 9? No, max stays 9
End of array
Largest element found is 9
| Index | Current Element | Current Max |
|---|---|---|
| 0 | 3 | 3 |
| 1 | 5 | 5 |
| 2 | 1 | 5 |
| 3 | 9 | 9 |
| 4 | 2 | 9 |
Why This Works
Step 1: Initialize max
We start by assuming the first element is the largest using max = arr[0] so we have a baseline to compare others.
Step 2: Compare each element
We use a loop to check each element with if (arr[i] > max) to find if there's a bigger number.
Step 3: Update max when needed
If a bigger element is found, we update max to that value, ensuring it always holds the largest found so far.
Step 4: Result after loop
After checking all elements, max contains the largest element, which we print.
Alternative Approaches
#include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {3, 5, 1, 9, 2}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), compare); printf("Largest element is %d\n", arr[n-1]); return 0; }
#include <stdio.h> int findMax(int arr[], int n) { if (n == 1) return arr[0]; int max = findMax(arr, n - 1); return (arr[n - 1] > max) ? arr[n - 1] : max; } int main() { int arr[] = {3, 5, 1, 9, 2}; int n = sizeof(arr) / sizeof(arr[0]); printf("Largest element is %d\n", findMax(arr, n)); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once in a single loop, so time grows linearly with array size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is constant O(1).
Which Approach is Fastest?
The simple loop approach is fastest and most memory efficient compared to sorting (O(n log n)) or recursion (extra call stack).
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Most efficient for all array sizes |
| Sorting | O(n log n) | O(1) | When array needs sorting anyway |
| Recursion | O(n) | O(n) | Elegant but uses more memory |