cybersecurity · beginner · ~15 min

Index in bounds?

Write the canonical bounds check.

Challenge

Write the canonical bounds check that keeps an array index from reading off either end.

Task

Implement int in_bounds(int idx, int n) that returns 1 if idx is a valid index into an n-element array, else 0.

Input

  • idx: the index to check.
  • n: the array length.

Output

Returns int: 1 if 0 <= idx < n, else 0.

Example

in_bounds(3, 5)    ->   1
in_bounds(5, 5)    ->   0   (one past the end)
in_bounds(-1, 5)   ->   0

Edge cases

  • idx == n is out of bounds (the off-by-one that reads one past the end).
  • Negative indices are out of bounds.

Input format

Two ints: idx and n.

Output format

An int: 1 if 0 <= idx < n, else 0.

Constraints

idx == n is out of bounds.

Starter code

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.