Javascript · Loops
Challenge
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Level-Up Marathon
Zap trains from level 1 to level 8. Each level costs XP: level 1 costs 50 XP, level 2 costs 100 XP, level 3 costs 150 XP, and so on. 1. For each level from 1 to 8, print `"Level X: Y XP"` where Y is the XP cost of that level 2. Add each cost to `totalXP` 3. After the loop, print `"Total: Y XP"`
Starter code
let totalXP = 0; // Write your loop here
Exercise 2 — Duel to the End
Pyrochu faces Rockachu! Each turn, both Codémon attack at the same time. 1. Repeat as long as both Codémon still have HP 2. Each turn: increase `turn` by 1, subtract `pyrochuAttack` from `rockachuHP`, subtract `rockachuAttack` from `pyrochuHP`, then print `"Turn X - Pyrochu: A HP | Rockachu: B HP"` 3. After the loop, print `"Pyrochu wins!"` if Pyrochu still has HP, otherwise `"Rockachu wins!"`
Starter code
let pyrochuHP = 120; let pyrochuAttack = 25; let rockachuHP = 90; let rockachuAttack = 20; let turn = 0; // Write your loop here // Then announce the winner
Exercise 3 — Codémon Safari
You walk through the safari zone, up to 15 steps. At each step, `Math.random()` decides what happens. 1. Repeat while `step` is below 15. At each turn, increase `step` by 1 first 2. If the random number is below 0.3, print `"Step X: nothing here"` and move straight to the next step 3. Otherwise, increase `spotted` by 1 and print `"Step X: a wild Codémon! (N spotted)"` 4. As soon as 5 Codémon have been spotted, print `"Safari complete!"` and stop walking immediately 5. After the loop, print `"Steps walked: X"`
Starter code
let step = 0; let spotted = 0; // Write your loop here
Back to the course