C++ Program to Find Largest Element in Array
for (int i = 1; i < n; i++) if (arr[i] > largest) largest = arr[i];.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int arr[] = {3, 5, 1, 9, 2}; 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]; } } cout << "Largest element is: " << largest << endl; return 0; }
Dry Run
Let's trace the array {3, 5, 1, 9, 2} through the code
Initialize largest
largest = 3 (first element)
Compare with second element
arr[1] = 5 > largest (3), update largest = 5
Compare with third element
arr[2] = 1 <= largest (5), no change
Compare with fourth element
arr[3] = 9 > largest (5), update largest = 9
Compare with fifth element
arr[4] = 2 <= largest (9), no change
End of loop
largest = 9 is the largest element
| Iteration | Current Element | Largest So Far |
|---|---|---|
| 1 | 5 | 5 |
| 2 | 1 | 5 |
| 3 | 9 | 9 |
| 4 | 2 | 9 |
Why This Works
Step 1: Start with first element
We assume the first element is the largest because we need a starting point to compare others.
Step 2: Compare each element
We check every other element to see if it is bigger than the current largest.
Step 3: Update largest when 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 <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {3, 5, 1, 9, 2}; int n = sizeof(arr) / sizeof(arr[0]); int largest = *max_element(arr, arr + n); cout << "Largest element is: " << largest << endl; return 0; }
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {3, 5, 1, 9, 2}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n); cout << "Largest element is: " << arr[n - 1] << endl; return 0; }
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?
The simple loop is fastest for this task; using sorting is slower (O(n log n)) and built-in max_element is efficient and clean.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Finding largest quickly with minimal code |
| std::max_element | O(n) | O(1) | Cleaner code using standard library |
| Sorting | O(n log n) | O(1) | When sorted data is also needed |