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.
Important: Always ensure the loop has a clear stopping condition; otherwise it may run forever.
This example increments a counter by 1 at each iteration and stops when it reaches 10.
## 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".cat() and print() unless
there is a specific reason; it usually makes the output noisier.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
## It took 4 iterations before we shorted. Final price: 42
A work by Gianluca Sottile
gianluca.sottile@unipa.it