← Back to R Course | Chapter 4: Control Flow | Lesson 4 of 6

while Loop

In this page:

  1. while Loop

while Loop

A while loop checks its condition before every iteration and keeps running as long as it's TRUE. It's used when the number of iterations isn't known ahead of time. If the condition is FALSE from the start, the body never executes.

Warning: Forgetting to update the loop variable inside the body creates an infinite loop, just like in most other languages.

Example: while Loop

markup
n <- 10
steps <- 0

while (n > 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- n * 3 + 1
  }
  steps <- steps + 1
}

cat("Reached 1 in", steps, "steps\n")
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.