Simvik

Keep a value in range

Limit a value to a minimum and a maximum. An easy embedded C problem (Decisions and loops), run and graded in the browser.

easy · Decisions and loops · if · clamp

A motor accepts speeds from lo to hi. Anything outside that range must be pulled back to the nearest limit.

Return v if it lies between lo and hi. Return lo if it is below, and hi if it is above.

Starter code

int limit(int v, int lo, int hi) {
  return v;
}

Example tests

Inside the range

printf("%d\n", limit(5, 0, 10));

Expected output:

5

Above the range

printf("%d\n", limit(15, 0, 10));

Expected output:

10

Learn it first

  • Decisions and loops · Choosing with if and switch, repeating with while and for, and the loop that never ends.

More Decisions and loops problems