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

Repeat until

Keep repeating while a condition stays true, even when you don't know how many passes it takes. About 8 minutes.

Keep going while it's true

A for loop is perfect when you know how many times to repeat. But often you don't. You stir your tea while it is too hot. You walk while you haven't reached home yet.

A while loop checks a condition before every pass. If the condition is true, the lines inside run once, and then the check happens again. As soon as the condition is false, the loop ends. If it is false at the very beginning, the loop never runs at all.

A while loop: repeats as long as its condition is true.
In code
count = 0
while n > 0:
    n = n // 2
    count = count + 1
Halving 10 until nothing is left
n: 5
0
count: 1
1
line
n
5
count
1

n is 10, which is more than 0, so the loop runs. Halve n: it becomes 5, and the count becomes 1.

Move 1 of 5

Something must change

Be careful with while loops. The loop only ends when its condition becomes false, so something inside the loop has to make that happen.

In the halving loop, each pass makes n smaller, and eventually it reaches 0. If you forgot to change n, the condition would stay true forever, and the computer would run the loop for ever. That is called an infinite loop. Before you run a while loop, ask: what changes on each pass to bring it closer to the end?

If nothing changes, the loop never ends.
Quick check

n is 6. You halve it with whole-number division until it reaches 0. How many halvings is that?

  1. A3
  2. B2
  3. C6
Show the answer

3. 6 becomes 3, then 1, then 0. That is three halvings.

Your problem

How many halvings?

A rope is n metres long. You keep cutting it in half and throwing away the extra metre if the length is odd (whole-number division), until nothing is left. Return how many cuts that takes.

Example
n = 10 → 4

0 ≤ n ≤ 2,000,000,000

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