pointers-memory · beginner · ~15 min

Is an index in bounds?

Write the bounds check that prevents dangling/out-of-range access.

Challenge

Check whether an index is a valid position in an array of a given length — the bounds check that prevents out-of-range reads.

Task

Implement int index_in_bounds(int idx, int len) that returns 1 if 0 <= idx < len, else 0. No main — the grader calls it.

Input

idx — the candidate index (may be negative). len — the array length.

Output

Returns 1 if idx is a valid index into a len-element array, else 0.

Example

index_in_bounds(2, 5)    ->   1
index_in_bounds(5, 5)    ->   0   (one past the end)
index_in_bounds(-1, 5)   ->   0
index_in_bounds(0, 1)    ->   1

Edge cases

  • idx == len (one past the end): 0.
  • Negative idx: 0.

Input format

idx — candidate index (may be negative); len — array length.

Output format

1 if 0 <= idx < len, else 0.

Starter code

int index_in_bounds(int idx, int len) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.