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 <- 2
repeat {
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 the repeat loop with the break keyword and print Terminating loop.

  • If the num <10, we print the value of num and increment the value of the num by 2, and the repeat loop will continue its execution.

Free Resources