R While Loop
A while loop repeats a block while its test stays TRUE. The loop stops on its own once the test turns FALSE.
Count from 1 to 3
The counter starts at 1 and rises each round. The loop prints each value until the test fails.
i <- 1
while (i <= 3) {
print(i)
i <- i + 1
}Count down
The counter starts at 3 and falls each round. The prints run from 3 down to 1.
i <- 3
while (i >= 1) {
print(i)
i <- i - 1
}A test that starts false
The test is false at the start. Only the final print after the loop runs.
i <- 10
while (i < 5) {
print(i)
i <- i + 1
}
print("done")Example
i <- 1
total <- 0
while (i <= 4) {
total <- total + i
i <- i + 1
}
print(total)Key points
- The test sits inside round brackets after while.
- The block runs again and again while the test is TRUE.
- A counter is a value that tracks the rounds.
- The counter must change inside the block.
- A test that starts FALSE runs the block zero times.
In this example, the loop adds the numbers 1 to 4 into total. The counter rises each round, so the test fails after 4 and print shows 10.
Note
A counter that never changes makes the loop run forever.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
A while loop test starts FALSE. How many times does its block run?