R While Loop

A while loop repeats a block of code as long as a condition remains TRUE. Unlike a for loop (which runs a set number of times), a while loop keeps running until something changes that makes the condition FALSE. This makes it ideal when you do not know in advance how many repetitions are needed.

Syntax

while (condition) {
  # code to repeat
  # something must eventually make condition FALSE
}

How the While Loop Works

START
  │
  ▼
Check condition ──► FALSE ──► Exit loop
  │ TRUE
  ▼
Run code block
  │
  ▼ (update something)
Check condition ──► repeat...

Basic Example

count <- 1

while (count <= 5) {
  cat("Count:", count, "\n")
  count <- count + 1   # IMPORTANT: update count, or loop runs forever
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Practical Example: Savings Goal

savings   <- 0
goal      <- 10000
monthly   <- 1500
months    <- 0

while (savings < goal) {
  savings <- savings + monthly
  months  <- months + 1
}

cat("Reached ₹", goal, "in", months, "months\n")
cat("Actual savings: ₹", savings, "\n")

Output:

Reached ₹ 10000 in 7 months
Actual savings: ₹ 10500

Practical Example: Find First Factor

number  <- 56
divisor <- 2

while (number %% divisor != 0) {
  divisor <- divisor + 1
}

cat("Smallest factor of", number, "is", divisor, "\n")

Output:

Smallest factor of 56 is 2

Infinite Loop Warning

If the condition never becomes FALSE, the loop runs forever (infinite loop). Always make sure the code inside the loop changes something that will eventually make the condition FALSE.

# DANGER: infinite loop — count never changes!
count <- 1
while (count <= 5) {
  cat(count, "\n")
  # forgot: count <- count + 1
}

# If this happens in RStudio, press the STOP button or Ctrl+C

While vs For Loop

For Loop                        While Loop
──────────────────────────────────────────────────────
Know exactly how many times     Don't know iterations
Loop variable auto-advances     Must update manually
Iterates over sequence/vector   Continues while condition TRUE
Safer for bounded tasks         Better for open-ended tasks

do-while Style in R

R has no built-in do-while loop, but you can simulate one using repeat and break:

count <- 0
repeat {
  count <- count + 1
  cat("Count:", count, "\n")
  if (count >= 3) break    # exit after 3 runs
}

This ensures the block runs at least once before the condition is checked.

While loops excel at tasks that run until a goal is reached, a threshold is hit, or a search finds what it needs. Always update your loop variable inside the block to prevent accidental infinite loops.

Leave a Comment

Your email address will not be published. Required fields are marked *