Example 1 — Forward, backward, and maximum
Three traversals over one array.
#include <stdio.h>
int main(void) {
int a[] = {3, 8, 1, 9, 4};
int n = sizeof a / sizeof a[0];
int max = a[0], at = 0;
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
for (int i = n - 1; i >= 0; i--) printf("%d ", a[i]);
printf("\n");
for (int i = 1; i < n; i++) {
if (a[i] > max) { max = a[i]; at = i; }
}
printf("max=%d at index %d\n", max, at);
return 0;
} How It Works
- The first loop prints in order, the second in reverse.
- The maximum search starts from index 1 because
a[0]seedsmax. - Use a signed
intfor reverse loops; anunsignedcounter would wrap around.
