Do-loops are useful when you always want to run a codeblock at least once. A Do-loop will evaluate the condition after executing the codeblock, unlike a while-loop which does it before executing the codeblock.
You can use do-loops in two ways:
- Loop while the condition is true:
Do {
code_block
} while (condition)
- Loop until the condition is true, in other words, loop while the condition is false:
Do {
code_block
} until (condition)
Real Examples:
$i = 0
Do {
$i++
"Number $i"
} while ($i -ne 3)
$i = 0
Do {
$i++
"Number $i"
} until ($i -eq 3)
do/while and do/until are opposite loops. If the code inside is the same, the condition is reversed. Reset $i before the second loop; otherwise it starts at 3 and the until condition never becomes true. With $i starting at 0, both loops print 1, 2, and 3.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents