R While Loop

A while loop is used when you want to perform a task indefinitely, until a particular condition is met. It’s a condition-controlled loop.

Syntax

Here’s the syntax of the while statement:

r while loop syntax

Condition is any expression that evaluates to either true or false.

Statements are executed as long as the condition is true.

Basic Examples

Any non-zero value or nonempty container is considered TRUE; whereas Zero, None, and empty container is considered FALSE.

# Iterate until x becomes 0
x <- 5
while (x) {
  print(x)
  x <- x - 1
}
[1] 5
[1] 4
[1] 3
[1] 2
[1] 1

If the condition is false at the start, the while loop will never be executed at all.

x <- 0
while (x) {
  print(x)
  x <- x - 1
}

Break in while Loop

Python break statement is used to exit the loop immediately. It simply jumps out of the loop altogether, and the program continues after the loop.

# Break the loop when x becomes 3
x <- 6
while (x) {
  print(x)
  x <- x - 1
  if (x == 3)
    break
}
[1] 6
[1] 5
[1] 4

Next (continue) in while Loop

The next statement skips the current iteration of a loop and continues with the next iteration.

# Skip odd numbers using continue statement
x <- 6
while (x) {
  x <- x - 1
  if (x %% 2 != 0)
    next
  print(x)
}
[1] 4
[1] 2
[1] 0