TExcelTAD
Home › R › R While Loop

R While Loop

A while loop repeats a block of code as long as a condition stays TRUE. Use it when you don't know in advance how many repetitions you need.

r · try it yourself
count <- 1
while (count <= 5) {
  cat("Count is", count, "\n")
  count <- count + 1
}
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

The condition is checked before every pass. Something inside the loop must eventually make it FALSE; here we increase count. Forget that line and the loop never ends.

A practical example

How many years until savings of 1000 grow to 2000 at 5% interest per year?

r · try it yourself
balance <- 1000
years <- 0
while (balance < 2000) {
  balance <- balance * 1.05
  years <- years + 1
}
years
round(balance, 2)
[1] 15
[1] 2078.93

break: leave the loop early

break stops the loop immediately. Here we look for the first number divisible by both 7 and 9:

r · try it yourself
n <- 1
while (TRUE) {
  if (n %% 7 == 0 && n %% 9 == 0) {
    break
  }
  n <- n + 1
}
n
[1] 63

while (TRUE) with a break inside is a common pattern when the stopping test is easier to write in the middle of the loop.

next: skip to the next pass

next abandons the current pass and goes back to the condition. This loop prints only the odd numbers:

r · try it yourself
i <- 0
while (i < 10) {
  i <- i + 1
  if (i %% 2 == 0) next
  cat(i, "")
}
cat("\n")
1 3 5 7 9

Make sure the counter is updated before next, otherwise the loop gets stuck.

repeat

repeat is a loop with no condition at all; it runs until a break. It is handy for "do something, then check":

r · try it yourself
set.seed(12)
rolls <- 0
repeat {
  die <- sample(1:6, 1)
  rolls <- rolls + 1
  cat("Rolled", die, "\n")
  if (die == 6) break
}
cat("Got a six after", rolls, "rolls\n")
Rolled 2
Rolled 2
Rolled 3
Rolled 6
Got a six after 4 rolls

set.seed() makes the "random" rolls the same every time you run the example, so the output is reproducible.

The Collatz sequence

A classic while example: start with any positive number; if it is even, halve it, otherwise triple it and add one. The sequence always seems to reach 1:

r · try it yourself
x <- 6
steps <- c(x)
while (x != 1) {
  x <- if (x %% 2 == 0) x / 2 else 3 * x + 1
  steps <- c(steps, x)
}
steps
length(steps) - 1
[1]  6  3 10  5 16  8  4  2  1
[1] 8

Test yourself

When is the condition of a while loop checked?

  1. Only once
  2. Before every pass
  3. After every pass
  4. Only when next is called

Which keyword skips the rest of the current pass?

  1. break
  2. next
  3. continue
  4. skip

What loop construct has no condition and runs until break?

  1. for
  2. while
  3. repeat
  4. loop