Learn R Programming  /  Control Flow  /  Repeat Loop

Repeat Loop

repeat runs a block of code over and over with no built-in stopping condition - you must use break yourself. It guarantees the body runs at least once.

Basic repeat Loop

R Code
count <- 1

repeat {
  print(count)
  count <- count + 1
  if (count > 5) {
    break
  }
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
⚠ Common Mistake
Forgetting the break statement entirely means the loop never stops on its own - repeat has no condition of its own to check, unlike while.

repeat vs while — When the Body Must Run First

repeat is the right tool when the loop body needs to run at least once before you can even check whether to continue - for example, validating user input where you must first ask for it.

R Code
# simulated input values to validate, one per attempt
inputs <- c(-5, 200, 42)
i <- 1

repeat {
  value <- inputs[i]
  i <- i + 1
  if (value > 0 && value <= 100) {
    cat("Valid value received:", value, "\n")
    break
  } else {
    cat("Rejected:", value, "- trying next\n")
  }
}
Output
Rejected: -5 - trying next 
Rejected: 200 - trying next 
Valid value received: 42

Advanced: repeat for a Retry-Until-Success Pattern

🚀 Advanced Example
repeat is commonly used to model retry logic - keep attempting an operation until it succeeds or a maximum attempt count is reached.
R Code
attempt <- 0; max_attempts <- 3; success <- FALSE

repeat {
  attempt <- attempt + 1
  cat("Attempt", attempt, "\n")
  success <- (attempt == 3)  # pretend it succeeds on the 3rd try
  if (success || attempt >= max_attempts) {
    break
  }
}
cat("Final result:", success)
Output
Attempt 1 
Attempt 2 
Attempt 3 
Final result: TRUE

Key Points

  • repeat { ... } has no built-in condition - you must call break yourself to stop it.
  • It guarantees the loop body runs at least once, unlike while.
  • Use it for retry logic or validate-then-decide patterns where checking a condition upfront is not possible.