cybersecurity · beginner · ~15 min
Write the canonical bounds check.
Write the canonical bounds check that keeps an array index from reading off either end.
Implement int in_bounds(int idx, int n) that returns 1 if idx is a valid index into an n-element array, else 0.
idx: the index to check.n: the array length.Returns int: 1 if 0 <= idx < n, else 0.
in_bounds(3, 5) -> 1
in_bounds(5, 5) -> 0 (one past the end)
in_bounds(-1, 5) -> 0
idx == n is out of bounds (the off-by-one that reads one past the end).Two ints: idx and n.
An int: 1 if 0 <= idx < n, else 0.
idx == n is out of bounds.
int in_bounds(int idx, int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.