For Loops
Introduction to For Loops
For loops are ideal when you know exactly how many times to repeat something. They combine initialization, condition, and increment in one compact statement.
For Loop Structure:
// Basic for loop structure
for (initialization; condition; increment) {
// Code to repeat
}
// Example: Print numbers 0 to 9
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
// Same logic as while loop:
// int i = 0; // initialization
// while (i < 10) { // condition
// System.out.println(i);
// i++; // increment
// }For Loop Examples:
// Count with variables
int start = 3;
int end = 7;
for (int i = start; i < end; i++) {
System.out.println("Count: " + i);
}
// Output: 3, 4, 5, 6
// Robot motor test - run each motor for 5 seconds
String[] motorNames = {"frontLeft", "frontRight", "backLeft", "backRight"};
for (int i = 0; i < motorNames.length; i++) {
System.out.println("Testing motor: " + motorNames[i]);
// setMotorPower(motorNames[i], 0.5);
// wait(5000); // 5 seconds
// setMotorPower(motorNames[i], 0.0);
}Calculating with For Loops:
// Calculate 4 * 3 as repeated addition (3 + 3 + 3 + 3)
int result = 0;
for (int i = 0; i < 4; i++) {
result += 3; // Add 3 each time
}
System.out.println("4 * 3 = " + result); // 12
// Robot sensor average over 10 readings
int sensorSum = 0;
int readings = 10;
for (int i = 0; i < readings; i++) {
// int sensorValue = readSensor();
int sensorValue = (int)(Math.random() * 100); // Simulate sensor
sensorSum += sensorValue;
System.out.println("Reading " + (i + 1) + ": " + sensorValue);
}
double average = (double) sensorSum / readings;
System.out.println("Average sensor value: " + average);When to Use For Loops:
Perfect For:
- Known iterations: When you know exactly how many times to loop
- Array processing: Iterating through arrays or collections
- Counting operations: Incrementing or decrementing by fixed amounts
- Mathematical calculations: Repeated calculations with counters
Try It Yourself:
Exercise 1: For Loop Practice
- Create a multiplication table using nested for loops
- Build a robot sensor calibration system with progress tracking
- Calculate factorial using for loops
- Create a motor test sequence for all robot motors
Practice using for loops for different scenarios: