Arrays and Iteration
Find Maximum
Scan the array once, keeping the largest value seen so far. The replay highlights when a candidate replaces the running maximum.
Algorithm
Basic Implementation
basic.c
#include <stdio.h>
int main(void) {
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6};
int n = (int)(sizeof(arr) / sizeof(arr[0]));
int best = arr[0];
for (int i = 1; i < n; ++i) {
if (arr[i] > best) {
best = arr[i];
}
}
printf("%d\n", best);
return 0;
}
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- C stores
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6}as a fixed local array inmain, withbestinitialized fromarr[0]. nis computed before any pointer decay with(int)(sizeof(arr) / sizeof(arr[0])), so the loop bounds arei = 1throughi < n.- The
for (int i = 1; i < n; ++i)loop readsarr[i]by index and mutates only the scalarbestwhenarr[i] > best; the array contents are never changed. - The trace shows replacements at
i=2(3 -> 4),i=4(4 -> 5), andi=5(5 -> 9), then no replacement for values2and6. printf("%d\n", best)formats the finalintas9. Visible memory is the stack array plus scalar locals; there is no heap allocation or helper function taking an array pointer in this source.
execution replay
The checked-in replay follows the language-neutral state table for `array-find-max`.
cross-language comparison
This C DSA version keeps the same data and final output as every other DSA book in this wave.