Example 1 — Print children by index
Show each parent with its children, or "none".
#include <stdio.h>
int main(void) {
int a[] = {2, 5, 3, 9, 6, 4};
int n = 6;
for (int i = 0; i < 3; i++) {
int l = 2 * i + 1, r = 2 * i + 2;
printf("index %d: value %d, left ", i, a[i]);
if (l < n) printf("%d", a[l]); else printf("none");
printf(", right ");
if (r < n) printf("%d", a[r]); else printf("none");
printf("\n");
}
return 0;
} How It Works
- Index 2 has a left child at index 5 (value 4).
- Its right child would be index 6, which is not less than 6, so it prints "none".
- Always bounds-check child indexes against
n.
