while Loop
In this page:
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
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")
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: