Brainlag
  1. Library
  2. Challenges
  3. C

A health bar that stays in range

Apply a hit or a heal to a health bar and keep the result between 0 and the maximum, whatever the numbers.

CWarm-up10 min

Write apply_hit(hp, amount, max_hp). A positive amount is damage and takes health away; a negative one is a heal and adds it. Return the new health, but never below 0 and never above max_hp.

C
apply_hit(80, 30, 100)    // 50
apply_hit(80, -50, 100)   // 100, not 130
apply_hit(20, 45, 100)    // 0, not -25

Checks

  1. Damage and heals
  2. Never outside the bar
exercise_1.c to run
int apply_hit(int hp, int amount, int max_hp) {
    return hp;
}

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.