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:
Syntax
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
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
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
- Forgetting to change the variable in the condition, so
while (n > 1)loops forever. - Using
=instead of==in the condition. - Using
whilefor something like summing a vector, when vectorised functions such assum()are simpler.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: