R Repeat Loop

The repeat loop in R runs a block of code indefinitely — without any condition. It keeps going until a break statement tells it to stop. Think of it as a loop with no built-in exit: you must write the exit condition yourself inside the loop body.

Syntax

repeat {
  # code block
  if (exit_condition) {
    break   # exits the loop
  }
}

How It Works

START
  │
  ▼
Run code block
  │
  ▼
Condition met? ──► YES ──► break ──► Exit loop
  │ NO
  ▼
Run code block again
  │
  ▼ (repeat forever until break)

Basic Example

x <- 1

repeat {
  cat("x =", x, "\n")
  x <- x + 1
  if (x > 4) break
}

Output:

x = 1
x = 2
x = 3
x = 4

Practical Example: ATM PIN Retry

correct_pin <- 1234
attempts    <- 0
max_attempts <- 3

repeat {
  attempts <- attempts + 1
  pin <- 1234   # simulating user input

  if (pin == correct_pin) {
    cat("PIN correct. Access granted.\n")
    break
  }

  if (attempts >= max_attempts) {
    cat("Too many failed attempts. Card blocked.\n")
    break
  }

  cat("Wrong PIN. Tries left:", max_attempts - attempts, "\n")
}

Output:

PIN correct. Access granted.

Practical Example: Find First Prime

n <- 10   # find first prime greater than 10

repeat {
  n <- n + 1
  is_prime <- all(n %% 2:(n-1) != 0) && n > 1

  if (is_prime) {
    cat("First prime after 10:", n, "\n")
    break
  }
}

Output:

First prime after 10: 11

Repeat vs While vs For

Loop Type    Condition Check    Minimum Runs    Use Case
──────────────────────────────────────────────────────────────
for          Before each run    0               Known iterations
while        Before each run    0               Condition-driven
repeat       Never (manual)     1 guaranteed    Must run at least once

Safety: Always Include a Break

# Safe repeat loop pattern
counter <- 0

repeat {
  counter <- counter + 1

  # Do work here...

  # Safety exit (prevents infinite loop during development)
  if (counter > 1000) {
    cat("Safety limit reached\n")
    break
  }

  # Normal exit condition
  if (counter == 5) break
}

The repeat loop is the most flexible but also the most dangerous loop type because it has no automatic stop mechanism. Always include at least one break statement inside a repeat loop. Use it when the loop must execute at least once before any condition can be checked — like user input validation or connection retries.

Leave a Comment

Your email address will not be published. Required fields are marked *