While Loops
The Three Steps of a Loop
A while loop repeats its body as long as a condition holds, checked before every pass, including the first:
int attempts = 0; // 1. initialize
while (attempts < 3 && !connected) { // 2. test
connected = tryConnect();
attempts++; // 3. update
}
Every loop needs these same three steps — initialize the loop variable, test it, update it inside the loop. A for loop (Lesson 5.1-5.2) just packs all three into one header line; a while loop spreads them out, which is more natural when the "update" isn't a simple counter.
Infinite Loops
Forget step 3 and the condition never changes — the loop runs forever:
int i = 0;
while (i < 10)
{
System.out.println(i); // i never changes — this never stops
}
An infinite loop on a robot doesn't just print forever — it can freeze the whole robot's control loop, since nothing after it ever gets a chance to run.
When to Reach for while Instead of for
for fits naturally when you already know the number of iterations. while fits better when you're waiting for a condition, not counting to a number — like waiting for a sensor to settle, or retrying a connection a limited number of times:
while (!gyro.isConnected() && attempts < 5)
{
attempts++;
}
Common Pitfalls
- Forgetting to update the loop variable. The single most common cause of an infinite loop — every
whileloop needs something inside it that eventually makes the condition false. - A condition that's false from the very first check. If the condition never holds, the loop body never runs at all — not even once. Double-check the loop variable's starting value against the condition.
Key Takeaways
- Every loop needs three steps: initialize, test, update —
whilejust doesn't bundle them into one line likefordoes. - A
whileloop's condition is checked before every pass, including the first — if it starts false, the body never runs. - Forgetting to update the loop variable is the classic cause of an infinite loop, which can freeze a robot's control code.
whilefits naturally when you're waiting for a condition rather than counting a known number of iterations.
Derived from csawesome-2026: unit-2-selection-and-iteration/2.07-while-loops.md (CSA 2.7)