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, beforeWhile
body is executedbody
- list of blocks executed when thecondition
istrue
Let's write a program that prints numbers 1 to 5:
- declare an
x: Integer = 1
- add a
While
loop block with conditionx <= 5
(the diamond block) - output
x
in theWhile
loop body (thetrue
branch) - assign
x = x + 1
in theWhile
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.