LessonsBeginner: First stepsLesson 12

Loops that decide

Loop while something is true, until something happens, or forever, and leave a loop or skip a turn with exit and next.

  • Beginner
  • Lesson 12 of 83
  • About 8 minutes
  • 6 examples

Repeat while

Sometimes you do not know how many times to loop, only when to stop. repeat while checks its condition before every turn, and stops as soon as it is false.

ExampleRun it in the playground
put 1 into tNumber
repeat while tNumber < 100
   multiply tNumber by 3
end repeat
put tNumber
Output
243

Repeat until

repeat until is the other way round: it loops until its condition becomes true. How many years does money take to double at 7% a year?

ExampleRun it in the playground
put 1000 into tMoney
put 0 into tYears
repeat until tMoney >= 2000
   multiply tMoney by 1.07
   add 1 to tYears
end repeat
put "Doubled after" && tYears && "years"
put round(tMoney, 2)
Output
Doubled after 11 years
2104.85

Leaving a loop: exit repeat

A plain repeat (or repeat forever) never stops by itself. exit repeat leaves the loop at once, from anywhere inside it.

ExampleRun it in the playground
put 0 into tCount
repeat
   add 1 to tCount
   if tCount * tCount > 50 then exit repeat
end repeat
put tCount && "is the first number whose square is over 50"
Output
8 is the first number whose square is over 50

Skipping a turn: next repeat

next repeat skips the rest of this turn and goes straight on to the next one.

ExampleRun it in the playground
repeat with i = 1 to 12
   if i mod 3 is not 0 then next repeat
   put i && "divides by 3"
end repeat
Output
3 divides by 3
6 divides by 3
9 divides by 3
12 divides by 3

A famous loop

Start with any whole number. If it is even, halve it; if it is odd, triple it and add one. Mathematicians believe you always reach 1, but nobody has proved it (it is the Collatz conjecture).

ExampleRun it in the playground
put 6 into tNumber
put tNumber into tPath
repeat while tNumber is not 1
   if tNumber mod 2 is 0 then
      put tNumber / 2 into tNumber
   else
      put tNumber * 3 + 1 into tNumber
   end if
   put comma & tNumber after tPath
end repeat
put tPath
Output
6,3,10,5,16,8,4,2,1

Try it yourself

Find the first power of 2 that is bigger than 1000, by doubling a number in a loop.

Show a solution
ExampleRun it in the playground
put 1 into tPower
repeat until tPower > 1000
   multiply tPower by 2
end repeat
put tPower
Output
1024

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.