R Repeat Loop
A repeat loop runs its block again and again with no test of its own. A break statement inside the block is what stops it.
Count from 1 to 3
The block prints the counter and raises it each round. An if test triggers break once the counter passes 3.
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 3) {
break
}
}Run once then stop
The block prints one line. A break right after the print ends the loop.
repeat {
print("once")
break
}Example
i <- 3
repeat {
print(i)
i <- i - 1
if (i < 1) {
break
}
}Key points
- The word repeat is followed by a block in curly braces.
- The block runs at least once before anything can stop it.
- A break inside the block ends the loop at once.
- An if test inside the block often guards the break.
In this example, the counter falls by one each round. When the counter drops below 1, the if test triggers break and the loop stops.
Note
Without a break, a repeat loop never ends.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What stops a repeat loop?