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

while Loop

A while loop keeps repeating for as long as its condition is true, like stirring until the sugar has melted. The test comes before every lap.

In this page:

  1. while Loop
Syntax
r
while (condition) {
  # body
}

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")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to change the variable in the condition, so while (n > 1) loops forever.
  2. Using = instead of == in the condition.
  3. Using while for something like summing a vector, when vectorised functions such as sum() are simpler.
🔒

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.