linux-sysprog · beginner · ~15 min

Seconds remaining on a timer

Compute a countdown without underflow.

Challenge

alarm(n) schedules SIGALRM n seconds from now. Model the countdown: how many seconds remain after some time has elapsed, never going negative.

Task

Implement int alarm_remaining(int set_seconds, int elapsed) that returns set_seconds - elapsed, floored at 0.

Input

  • set_seconds: the alarm's original duration.
  • elapsed: seconds already passed.

Output

Seconds left before the alarm fires (>= 0).

Example

alarm_remaining(10, 3)   ->   7
alarm_remaining(5, 5)    ->   0
alarm_remaining(5, 9)    ->   0   (already past)

Edge cases

  • elapsed >= set_seconds: return 0.

Input format

set_seconds: alarm duration; elapsed: seconds passed.

Output format

set_seconds - elapsed, floored at 0.

Constraints

Never return a negative remaining time.

Starter code

int alarm_remaining(int set_seconds, int elapsed) {
    /* TODO */
    return 0;
}

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