Learn R Programming  /  Control Flow  /  While Loop

While Loop

A while loop repeats a block of code for as long as a condition stays TRUE. Use it when you do not know in advance how many times you will need to loop.

Basic while Loop

R Code
count <- 1

while (count <= 5) {
  print(count)
  count <- count + 1
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
⚠ Common Mistake
Forgetting to update the loop variable (here, count) inside the loop body creates an infinite loop, since the condition never becomes FALSE. Always double check that something inside the loop moves it closer to stopping.

Using break to Exit Early

R Code
n <- 1
while (TRUE) {
  if (n > 3) break
  print(n)
  n <- n + 1
}
Output
[1] 1
[1] 2
[1] 3

Using next to Skip an Iteration

R Code
n <- 0
while (n < 5) {
  n <- n + 1
  if (n %% 2 == 0) next   # skip even numbers
  print(n)
}
Output
[1] 1
[1] 3
[1] 5

Advanced: while Loop for Iterative Convergence

🚀 Advanced Example
while loops are the natural choice for iterative numerical methods that stop once a result is precise enough, rather than after a fixed number of steps - for example, approximating a square root with Newtons method.
R Code
x <- 10; guess <- 1; tolerance <- 1e-6

while (abs(guess^2 - x) > tolerance) {
  guess <- (guess + x / guess) / 2
}
guess
Output
[1] 3.162278

Key Points

  • while(condition) checks the condition BEFORE each pass, so it may run zero times.
  • Something inside the loop body must eventually make the condition FALSE, or you get an infinite loop.
  • break exits the loop immediately; next skips straight to the next iteration.