C Program to Find Largest Element in an Array
for (int i = 1; i < n; i++) if (arr[i] > largest) largest = arr[i];.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int arr[] = {5, 3, 9, 1, 6}; int n = sizeof(arr) / sizeof(arr[0]); int largest = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > largest) { largest = arr[i]; } } printf("Largest element is %d\n", largest); return 0; }
Dry Run
Let's trace the array {5, 3, 9, 1, 6} through the code to find the largest element.
Initialize largest
largest = 5 (first element)
Compare with second element
arr[1] = 3; 3 > 5? No; largest stays 5
Compare with third element
arr[2] = 9; 9 > 5? Yes; largest updated to 9
Compare with fourth element
arr[3] = 1; 1 > 9? No; largest stays 9
Compare with fifth element
arr[4] = 6; 6 > 9? No; largest stays 9
End of loop
largest = 9 is the largest element
| Iteration | Current Element | Largest |
|---|---|---|
| 1 | 3 | 5 |
| 2 | 9 | 9 |
| 3 | 1 | 9 |
| 4 | 6 | 9 |
Why This Works
Step 1: Start with first element
We assume the first element is the largest to have a starting point for comparison.
Step 2: Compare each element
Each element is checked to see if it is bigger than the current largest value.
Step 3: Update largest if needed
If a bigger element is found, we update the largest variable to hold this new value.
Step 4: Result after loop
After checking all elements, the largest variable holds the biggest number in the array.
Alternative Approaches
#include <stdio.h> int findLargest(int arr[], int n) { int largest = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > largest) { largest = arr[i]; } } return largest; } int main() { int arr[] = {5, 3, 9, 1, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Largest element is %d\n", findLargest(arr, n)); return 0; }
#include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {5, 3, 9, 1, 6}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), compare); printf("Largest element is %d\n", arr[n-1]); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once in a single loop, so it runs in linear time O(n), where n is the number of elements.
Space Complexity
It uses only a few extra variables, so the space used is constant O(1), regardless of input size.
Which Approach is Fastest?
The direct loop method is fastest and simplest. Sorting is slower (O(n log n)) and uses more resources, so it's not ideal just to find the largest.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct loop | O(n) | O(1) | Finding largest quickly with minimal memory |
| Function abstraction | O(n) | O(1) | Code reuse and clarity |
| Sorting | O(n log n) | O(1) | When array needs to be sorted anyway |