pointers-memory · beginner · ~4 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.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

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

Output format

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

Constraints

Integer idx and len may be any int. Return 1 exactly when 0 <= idx < len, else 0. No memory is accessed.

Starter code

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

Common mistakes

Checking only the upper bound or accepting idx==len.

Edge cases to handle

Zero or negative length; negative index; index equal to length; integer limits.

Up next

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