What is the repeat loop in R?
The repeat loop repeatedly executes a block of code indefinitely. The repeat loop doesn’t check for any loop termination condition. We can stop the repeat loop with the break statement inside the block of code.
Syntax
repeat {
# statement 1
# statement 2
}
The repeat loop will result in an infinite loop if we don’t handle the loop termination condition inside the repeat block.
Example
num <- 2repeat {if (num > 10) {print("Terminating loop")break}print(num)num <- num + 2}
In the code above, we create a num variable with a 2 value. We also create a repeat loop. Inside the loop, we check if the value of the num is greater than 10.
-
If the
num > 10, we terminate therepeatloop with thebreakkeyword and printTerminating loop. -
If the
num <10, we print the value ofnumand increment the value of thenumby2, and therepeatloop will continue its execution.