cybersecurity · intermediate · ~15 min

Validate an integer in range

Parse and range-check numeric input.

Challenge

Parse a numeric string and confirm it is a clean base-10 integer inside an allowed range.

Task

Implement int valid_int_in_range(const char *s, int lo, int hi) that returns 1 if s parses as a base-10 integer within [lo, hi] inclusive, else 0.

Input

  • s: a NUL-terminated candidate number the grader passes.
  • lo, hi: the inclusive bounds.

Output

Returns int: 1 if s is a valid integer with no trailing junk and lo <= value <= hi, else 0.

Example

valid_int_in_range("50", 1, 100)   ->   1
valid_int_in_range("0", 1, 100)    ->   0   (below lo)
valid_int_in_range("5x", 1, 100)   ->   0   (trailing junk)

Edge cases

  • Trailing non-digit characters make the input invalid.
  • Values outside [lo, hi] are rejected.

Rules

  • Validate both the format (no leftover characters) and the range.

Input format

A NUL-terminated string s and inclusive bounds lo, hi.

Output format

An int: 1 if s is a clean base-10 integer in [lo, hi], else 0.

Constraints

Reject trailing non-digits; bounds are inclusive.

Starter code

#include <stdlib.h>

int valid_int_in_range(const char *s, int lo, int hi) {
    /* TODO */
    return 0;
}

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