DSA Factory
Free lessonsProgramming basics · Stage 4 · Loops that wait · Step 2

Stopping early

Leave a loop the moment you have your answer. About 9 minutes.

A snail on a wall

A snail climbs a wall. Each day it climbs 4 cm, and each night it slips back 1 cm. The wall is 10 cm tall. On which day does it reach the top?

Notice a trick. On the third day the snail climbs from 6 up to 10 and reaches the top. It doesn't wait for night to slip back. So the check "have I arrived?" has to happen right after the climb, before the slip.

Check at the right moment, straight after the climb, before the slip.
A wall 10 high: up 4, down 1
0
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10
snail
day
1
position
4

Day 1: the snail climbs 4 and reaches height 4. That's not the top yet.

Move 1 of 5

Break out of the loop

The word break leaves the loop on the spot. Any lines after it in that pass are skipped, and the computer carries on after the loop.

That's just what the snail needs. Make a loop that goes on until you say stop. Each pass is one day: count the day, climb, and then if you've reached the top, break. If not, slip back and carry on. The loop is written as while true, which means keep going until a break happens.

break: leaves the loop immediately.
In code
while True:
    days = days + 1
    position = position + up
    if position >= height:
        break
    position = position - down
Quick check

A wall is 5 cm tall. A snail climbs 3 cm each day and slips 2 cm each night. On which day does it reach the top?

  1. ADay 3
  2. BDay 5
  3. CDay 2
Show the answer

Day 3. Day 1 ends at 1, day 2 ends at 2, and on day 3 it climbs from 2 up to 5 and reaches the top.

Your problem

Days to climb

A snail climbs a wall. Each day it climbs up cm. If it has reached the top, it stops. Otherwise, each night it slips back down cm. Return the day on which it reaches the top.

Example
height = 10, up = 4, down = 1 → 3

1 ≤ height ≤ 100,000 · 1 ≤ down < up ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding