Loops
For loops, foreach loops, and the very important reason while loops are banned from robot code.
For Loops
The for loop runs code a set number of times. Use it whenever you know how many iterations you need.
// for (init; condition; step) for (int i = 0; i < 5; i++) { System.out.println("Iteration: " + i); } // Prints: 0, 1, 2, 3, 4
i++ counts up, i-- counts down, i += 2 skips every other.Infinite loop: If the condition never becomes false, the loop runs forever and your program freezes. for (int i = 0; i >= 0; i++) — i always stays ≥ 0, so it never stops. Always double-check your condition.
Foreach Loops
Cleaner syntax for looping through every element when you don't need the index.
double[] speeds = {0.5, 0.75, 1.0, -0.5}; // Foreach — clean, read-only for (double speed : speeds) { System.out.println(speed); } // Regular for — use this to MODIFY the array for (int i = 0; i < speeds.length; i++) { speeds[i] = speeds[i] * 0.8; // reduce all by 20% }
Foreach gotcha: The foreach variable is a copy of each element, not a reference to the original slot. Modifying it doesn't change the array. Use a regular for loop if you need to write back.
⛔ The While Loop Ban
While loops repeat as long as a condition is true. They work fine in normal Java programs. In robot code they are banned. Here's why.
FRC robots run on a 20ms loop cycle. The framework calls your code every 20ms to update motors, read sensors, and respond to the driver. If your code contains a while loop that gets stuck — waiting for a sensor, waiting for a button — it blocks the entire 20ms cycle. Motors stop updating. The driver loses control. The watchdog timer fires and disables the robot.
This has happened in real matches. Do not use while loops in robot code. Ever.
// ❌ DO NOT DO THIS IN ROBOT CODE while (!atTarget) { driveToTarget(); // blocks the entire robot loop until done } // ✓ Use state machines and command-based instead (you'll learn this in Phase 2)
Loop Visualizer
Adjust the values and watch the loop execute.
Fill in the Blanks
for (int i = 0; i ; ) { }
for (double : readings) { }
for (int i = 5; i > 0; ) { }
Knowledge Check
Coding Challenge
Given double[] readings = {12.4, 13.1, 11.8, 14.0, 12.7};, use a regular for loop to: calculate and print the average, find and print the maximum value, and print a warning for any reading below 12.0 inches.