While loop

A loop repeats a block of code until a stopping condition is met. A while loop keeps running as long as its condition evaluates to TRUE.

while (condition) {
  # expressions
}

While Loop Flow Chart
While Loop Flow Chart

Important: Always ensure the loop has a clear stopping condition; otherwise it may run forever.

Example 1: Count from 1 to 10

This example increments a counter by 1 at each iteration and stops when it reaches 10.

i <- 1

while (i <= 10) {
  cat("This is loop number", i, "\n")
  i <- i + 1
}
## This is loop number 1 
## This is loop number 2 
## This is loop number 3 
## This is loop number 4 
## This is loop number 5 
## This is loop number 6 
## This is loop number 7 
## This is loop number 8 
## This is loop number 9 
## This is loop number 10

Notes:

  • cat() is convenient for printing multiple values in one line and controlling newlines with "\n".
  • Avoid mixing cat() and print() unless there is a specific reason; it usually makes the output noisier.

Example 2: Simulate a stock price until it triggers a rule

Suppose a stock starts at 50. At each step, the price changes by an integer amount between -10 and +10. If the price drops below (or equal to) 45, we “short” it and stop the loop.

set.seed(123)  # makes random draws reproducible [2]

stock <- 50
price <- stock
n_iter <- 0

while (price > 45) {
  price <- stock + sample(-10:10, size = 1)
  n_iter <- n_iter + 1
  cat("Iteration:", n_iter, "- price:", price, "\n")
}
## Iteration: 1 - price: 54 
## Iteration: 2 - price: 58 
## Iteration: 3 - price: 53 
## Iteration: 4 - price: 42
cat(
  "It took", n_iter, "iterations before we shorted.",
  "Final price:", price, "\n"
)
## It took 4 iterations before we shorted. Final price: 42
 

A work by Gianluca Sottile

gianluca.sottile@unipa.it