9 / 16

While loop

When we want to execute some code many times, we can copy-paste those blocks. But that is not very efficient or readable, so we have blocks like the While loop.

A While block has two parts:

  • condition - checked each time, before While body is executed
  • body - list of blocks executed when the condition is true

Let's write a program that prints numbers 1 to 5:

  • declare an x: Integer = 1
  • add a While loop block with condition x <= 5 (the diamond block)
  • output x in the While loop body (the true branch)
  • assign x = x + 1 in the While loop body

You should see numbers 1,2,3,4,5 printed in the output panel (line by line).

Notice the Assign block: x = x + 1. You can use the previous value of x (before Assign was executed), when calculating its new value.