Repeating with a condition – while or until

On other occasions, you might want the loop continuations to depend on a condition:

  • You may want to continue while a certain condition is true, and stop with the loop when the condition turns false

  • You may want to do the opposite—loop until a certain condition is true

Here is an example of the while word, printing out the odd integers smaller than 10:

 n: 1
while [n <= 10 ][
if odd? n [prin n prin " "]
n: n + 1
] ;== 1 3 5 7 9
Note that the condition (here, n <= 10) must be in a code block, [ ]. This block may contain multiple statements and expressions; the last one is taken as a condition.

We can have the same result by simulating a second step:

 n: 1
while [n <= 10 ][
prin n prin " "
n: n + 2
] ;== 1 3 5 7 9

Every while can be turned into an until by inverting the condition. But be careful—the condition, that should become true at a certain moment, must appear as the last expression in the until block:

 n: 1
until [
prin n prin " "
n: n + 2
n > 10 ; the condition to end the loop
] ;== 1 3 5 7 9

This also means that the block will be executed at least once.

The break word can be used to break out of any kind of loop. If it's useful, you can return a value with break/return value. If you want to skip the current iteration of the loop, use continue to transfer control back to the start of the loop to begin the next iteration. The following code snippet illustrates this:

repeat n 8 [
prin ["Before" n " - "]
if n < 3 [continue]
if n = 6 [break]
prin ["After" n " - "]
]

This prints out the following:

Before 1 - Before 2 - Before 3 - After 3 - Before 4 - After 4 -
Before 5 - After 5 - Before 6 -
There is no for word in Red to do something like for i = 2 to 10 step 2as would be done in other languages. Instead, use repeat and while to accomplish what you want. For example, the to value phrase can be used with a <= value  condition in while, and a step can be performed in the while code block with i: i + step.

When looping through a series in a block, you'll most often use foreach and forall, which we'll discuss in the next chapter.

=> Now answer question 7 from the Questions section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.26