A repeat
loop just repeats a block of code indefinitely. In this loop, no condition checking is performed in order to end the loop.
To stop repeating the loop, you must put a condition explicitly inside it with break
statement. Failing to do so will create an infinite/endless loop.
Syntax
Here’s the syntax of the repeat loop:
Examples
A repeat loop without a break statement results into an infinite/endless loop.
# infinite loop
repeat {
print("Press Esc to stop me!")
}
[1] "Press Esc to stop me!"
[1] "Press Esc to stop me!"
...
...
However, you can put a condition explicitly inside the body of the loop and use the break
statement to exit the loop.
# Iterate until x becomes 5
x <- 1
repeat {
print(x)
if (x > 4)
break
x <- x + 1
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5