Home / Summer / Week 3
Summer · Week 3 of 8

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.

java
// for (init; condition; step)
for (int i = 0; i < 5; i++) {
    System.out.println("Iteration: " + i);
}
// Prints: 0, 1, 2, 3, 4
Init
int i = 0
Runs once at the start. Almost always starts at 0 because arrays are zero-indexed.
Condition
i < 5
Checked before each iteration. Loop keeps going while true. When false, the loop exits.
Step
i++
Runs after each iteration. 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.

java
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.

java — fine in normal programs, BANNED in robot code
// ❌ 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.

Interactive — For Loop Visualizer

Fill in the Blanks

// Loop 10 times (i = 0 to 9)
for (int i = 0; i ; ) { }
// Foreach over double array called readings
for (double : readings) { }
// Loop counting DOWN from 5 to 1
for (int i = 5; i > 0; ) { }

Knowledge Check

Coding Challenge

Sensor Array Analyzer
Process a real FRC-style sensor array

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.