The while Loop
A while loop in R keeps running its body as long as a condition stays TRUE. Where a for loop runs once per element of something, while runs an unknown number of times - until a condition changes:
Three parts make every while loop work, and all three are visible here:
- Setup before the loop -
count <- 1gives the condition something to test. - The condition -
count <= 5, built from the usual comparison operators, checked before every pass. - The update inside the body -
count <- count + 1moves the loop toward stopping.
Delete part 3 and the condition is TRUE forever: the loop never ends. That's the defining risk of while, and the rest of this page is largely about managing it.
The Condition Is Checked Before Each Pass
while tests its condition first, then runs the body. Two consequences follow. If the condition is already FALSE at the start, the body runs zero times:
And the check happens between full passes, not mid-body - once a pass starts, it runs to the end even if the condition turns FALSE halfway through. If you need to bail out mid-body, that's what break is for (below).
A Worked Example: Halving Until Below a Threshold
The natural home of while is "keep going until": you can't know in advance how many passes it takes, so for doesn't fit. How many times can you halve 1000 before it drops below 1?
Ten halvings, ending at about 0.977. The pattern - a state variable the body shrinks, a counter it grows - covers a huge share of real while loops: numeric methods that run until an error is small enough, simulations that run until a resource is exhausted, retries that continue until a call succeeds.
repeat + break: R's do-while
R has no do-while keyword - no loop that tests its condition after the body. But it has repeat, which loops unconditionally forever, and break, which exits any loop immediately. Put the break test at the end of a repeat body and you've built exactly a do-while - a loop whose body is guaranteed to run at least once:
The body always executes before the first test, so n is doubled at least once; the loop exits at 128, the first doubling past 100. Use this shape when "do the thing, then decide whether to do it again" is the honest description - reading input until it's valid, drawing samples until one qualifies. A repeat without a reachable break is an infinite loop by construction, so write the break first, then fill in the body.
break works identically in while and for loops - it's the general "we're done here" exit, and pairs naturally with if statements testing a mid-body condition.
next Inside a while Loop
next skips the rest of the current pass and jumps back to the condition check. It works in while just as in for - with one trap specific to while: if the update step comes after the next, skipping it means the loop variable never advances, and you've built an infinite loop. Put the update before the next:
This prints the even numbers 2 through 10. Move i <- i + 1 below the next line and the first odd value would skip the update forever. In for loops this hazard doesn't exist (the loop variable advances automatically), which is one more reason to prefer for when you're simply walking a sequence.
Guarding Against Infinite Loops
Every infinite loop is the same bug: nothing in the body changes the variables the condition depends on - or changes them in the wrong direction. Interactively you can interrupt with Esc or Ctrl+C, but in a script the process just hangs. Two habits prevent it.
First, when you write the condition, immediately ask "which line of the body moves this toward FALSE?" and make sure that line runs on every path through the body (watch the next trap above).
Second, for loops whose termination you can't easily prove, add a max-iterations guard so a logic bug produces a diagnosable result instead of a frozen session. Here it protects a Collatz-style loop - repeatedly halve even numbers and turn odd x into 3 * x + 1, until reaching 1:
Starting from 10, the loop reaches 1 in 6 steps. If some starting value never reached 1, the steps < 10000 clause would still end the loop, and the printed state would tell you something went wrong - a wrong answer you can see beats a program that never answers. The short-circuiting && is the right operator here: both sides are single values, and the guard reads as one sentence.
while vs for: Choosing
The rule of thumb is about what you know in advance:
- You know what you're iterating over (elements of a vector, numbers 1 to n): use a for loop - the loop variable manages itself.
- You only know the stopping condition (until converged, until below threshold, until valid): use
while. - The body must run at least once before any test makes sense: use
repeatwith a terminatingbreak.
If you find yourself maintaining a manual counter in a while loop just to walk a vector, that's a for loop wearing a disguise - switch.
What You Take Away
while (condition) { ... }checks first, then runs - a false condition at the start means zero passes.- The body must move the condition toward
FALSE; the setup / condition / update trio is the whole discipline. - R has no do-while keyword:
repeat { body; if (done) break }is the idiom, guaranteeing at least one pass. breakexits any loop; withnextin awhile, update the loop variable before the skip or it never advances.- A max-iterations guard (
&& steps < 10000) turns a potential hang into a visible, debuggable wrong answer.
Next up: vectors - the data structure every loop on this page has been walking, and the reason many R loops can disappear entirely.
Frequently Asked Questions
How does a while loop work in R?
while (condition) { ... } checks the condition first, and runs the body only while it stays TRUE. Something in the body must eventually make the condition FALSE - typically updating a counter or shrinking a value - or the loop never ends. If the condition is FALSE at the start, the body runs zero times.
Does R have a do-while loop?
Not as a keyword. The idiom is repeat { ...body...; if (condition) break } - repeat loops unconditionally, so the body is guaranteed to run at least once, and the break at the end plays the role of the do-while exit test.
How do you stop an infinite loop in R?
Interactively, press Esc (RStudio) or Ctrl+C (terminal) to interrupt. To prevent one in the first place: make sure the body updates the variables in the condition every pass, and add a max-iterations guard - while (working && steps < 10000) - so a logic bug produces a wrong count instead of a frozen session.