For Loops
beginner45 min
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:Create a multiplication table using nested for loops
Create a multiplication table using nested for loops
public class MultiplicationTable {
public static void main(String[] args) {
final int TABLE_SIZE = 10;
System.out.println("=== Multiplication Table (1-" + TABLE_SIZE + ") ===");
// Print header
System.out.print(" ");
for (int col = 1; col <= TABLE_SIZE; col++) {
System.out.printf("%4d", col);
}
System.out.println();
// Print separator line
System.out.print(" ");
for (int col = 1; col <= TABLE_SIZE; col++) {
System.out.print("----");
}
System.out.println();
// Print multiplication table
for (int row = 1; row <= TABLE_SIZE; row++) {
System.out.printf("%2d|", row); // Row header
for (int col = 1; col <= TABLE_SIZE; col++) {
int product = row * col;
System.out.printf("%4d", product);
}
System.out.println(); // New line after each row
}
// Robot gear ratio table
System.out.println("\n=== Robot Gear Ratio Table ===");
double[] gearRatios = {1.0, 1.5, 2.0, 3.0, 4.0};
int[] motorSpeeds = {100, 200, 300, 400, 500};
System.out.println("Motor Speed vs Gear Ratio (Output RPM)");
System.out.print("Speed\\Ratio");
for (double ratio : gearRatios) {
System.out.printf("%8.1f", ratio);
}
System.out.println();
for (int speed : motorSpeeds) {
System.out.printf("%9d", speed);
for (double ratio : gearRatios) {
double outputRPM = speed / ratio;
System.out.printf("%8.1f", outputRPM);
}
System.out.println();
}
}
}
Build a robot sensor calibration system with progress tracking
Build a robot sensor calibration system with progress tracking
public class SensorCalibrationSystem {
public static void main(String[] args) {
final int CALIBRATION_SAMPLES = 15;
final double TARGET_AVERAGE = 50.0;
final double ACCEPTABLE_DEVIATION = 5.0;
double[] calibrationData = new double[CALIBRATION_SAMPLES];
double sum = 0.0;
int validSamples = 0;
System.out.println("=== Robot Sensor Calibration System ===");
System.out.println("Target average: " + TARGET_AVERAGE);
System.out.println("Acceptable deviation: ±" + ACCEPTABLE_DEVIATION);
System.out.println("Samples to collect: " + CALIBRATION_SAMPLES);
System.out.println();
// Collect calibration samples
for (int sample = 0; sample < CALIBRATION_SAMPLES; sample++) {
// Simulate sensor reading with some noise around target
double reading = TARGET_AVERAGE + (Math.random() - 0.5) * 20;
calibrationData[sample] = reading;
// Progress tracking
int progressPercent = (int)(((double)(sample + 1) / CALIBRATION_SAMPLES) * 100);
System.out.printf("Sample %2d/%d [%3d%%]: %6.2f",
sample + 1, CALIBRATION_SAMPLES, progressPercent, reading);
// Validate reading
if (Math.abs(reading - TARGET_AVERAGE) <= ACCEPTABLE_DEVIATION * 2) {
sum += reading;
validSamples++;
System.out.println(" ✅ Valid");
} else {
System.out.println(" ❌ Outlier");
}
// Show current average
if (validSamples > 0) {
double currentAverage = sum / validSamples;
System.out.printf(" Running average: %.2f (from %d valid samples)\n",
currentAverage, validSamples);
}
// Progress bar
System.out.print(" [");
int barLength = 20;
int filledLength = (progressPercent * barLength) / 100;
for (int i = 0; i < barLength; i++) {
if (i < filledLength) {
System.out.print("█");
} else {
System.out.print("░");
}
}
System.out.println("] " + progressPercent + "%\n");
// Simulate delay
try {
Thread.sleep(200);
} catch (InterruptedException e) {
break;
}
}
// Calibration analysis
System.out.println("=== Calibration Analysis ===");
if (validSamples >= CALIBRATION_SAMPLES * 0.7) { // Need 70% valid
double average = sum / validSamples;
double deviation = Math.abs(average - TARGET_AVERAGE);
// Calculate standard deviation
double variance = 0.0;
for (int i = 0; i < CALIBRATION_SAMPLES; i++) {
if (Math.abs(calibrationData[i] - TARGET_AVERAGE) <= ACCEPTABLE_DEVIATION * 2) {
double diff = calibrationData[i] - average;
variance += diff * diff;
}
}
variance /= validSamples;
double standardDeviation = Math.sqrt(variance);
System.out.println("Valid samples: " + validSamples + "/" + CALIBRATION_SAMPLES);
System.out.println("Calibrated average: " + String.format("%.2f", average));
System.out.println("Target average: " + TARGET_AVERAGE);
System.out.println("Deviation from target: " + String.format("%.2f", deviation));
System.out.println("Standard deviation: " + String.format("%.2f", standardDeviation));
// Quality assessment
if (deviation <= ACCEPTABLE_DEVIATION && standardDeviation <= 3.0) {
System.out.println("\n🎯 CALIBRATION SUCCESSFUL!");
System.out.println("Sensor is properly calibrated and ready for use.");
} else if (deviation <= ACCEPTABLE_DEVIATION * 1.5) {
System.out.println("\n⚠️ CALIBRATION ACCEPTABLE");
System.out.println("Sensor calibration within acceptable range.");
} else {
System.out.println("\n❌ CALIBRATION FAILED");
System.out.println("Sensor requires recalibration or hardware check.");
}
} else {
System.out.println("❌ CALIBRATION FAILED - Insufficient valid samples");
System.out.println("Only " + validSamples + "/" + CALIBRATION_SAMPLES + " samples were valid.");
System.out.println("Check sensor connections and environment.");
}
}
}
Calculate factorial using for loops
Calculate factorial using for loops
import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== Factorial Calculator for Robot Path Planning ===");
System.out.println("Calculate possible arrangements for robot waypoints");
System.out.print("Enter number of waypoints (1-12): ");
int n = scanner.nextInt();
if (n < 1 || n > 12) {
System.out.println("❌ Invalid input. Using n = 5 as example.");
n = 5;
}
// Calculate factorial step by step
System.out.println("\nCalculating " + n + "! (" + n + " factorial):");
long factorial = 1;
System.out.print(n + "! = ");
for (int i = 1; i <= n; i++) {
factorial *= i;
System.out.print(i);
if (i < n) {
System.out.print(" × ");
}
}
System.out.println(" = " + factorial);
// Robot application context
System.out.println("\n🤖 Robot Path Planning Context:");
System.out.println("With " + n + " waypoints, there are " + factorial + " possible arrangements.");
if (n <= 4) {
System.out.println("✅ Small number - can evaluate all paths");
} else if (n <= 8) {
System.out.println("⚠️ Medium complexity - optimization needed");
} else {
System.out.println("🔥 High complexity - advanced algorithms required");
}
// Calculate computation time estimates
System.out.println("\n⏱️ Computation Time Estimates:");
System.out.println("(Assuming 1 microsecond per path evaluation)");
for (int waypoints = 3; waypoints <= Math.min(n + 2, 10); waypoints++) {
long pathCount = 1;
for (int i = 1; i <= waypoints; i++) {
pathCount *= i;
}
double microseconds = pathCount;
String timeUnit;
double timeValue;
if (microseconds < 1000) {
timeValue = microseconds;
timeUnit = "μs";
} else if (microseconds < 1000000) {
timeValue = microseconds / 1000;
timeUnit = "ms";
} else if (microseconds < 1000000000) {
timeValue = microseconds / 1000000;
timeUnit = "s";
} else {
timeValue = microseconds / 1000000000;
timeUnit = "s";
}
System.out.printf("%2d waypoints: %,15d paths = %8.2f %s\n",
waypoints, pathCount, timeValue, timeUnit);
}
// Calculate factorial table
System.out.println("\n📊 Factorial Reference Table:");
System.out.println("n\t|\tn!\t\t|\tRobot Application");
System.out.println("--------|---------------|---------------------------");
long currentFactorial = 1;
for (int i = 1; i <= 10; i++) {
currentFactorial *= i;
String application;
if (i <= 3) {
application = "Simple path";
} else if (i <= 5) {
application = "Basic optimization";
} else if (i <= 7) {
application = "Heuristic needed";
} else {
application = "Advanced algorithms";
}
System.out.printf("%d\t|\t%,12d\t|\t%s\n", i, currentFactorial, application);
}
System.out.println("\nFactorial calculation complete!");
}
}
Create a motor test sequence for all robot motors
Create a motor test sequence for all robot motors
public class MotorTestSequence {
public static void main(String[] args) {
// Robot motor configuration
String[] motorNames = {
"frontLeft", "frontRight", "backLeft", "backRight",
"arm", "intake", "launcher", "elevator"
};
double[] testSpeeds = {0.25, 0.5, 0.75, 1.0};
int testDurationMs = 1000; // 1 second per speed
System.out.println("=== Robot Motor Test Sequence ===");
System.out.println("Motors to test: " + motorNames.length);
System.out.println("Test speeds: " + testSpeeds.length);
System.out.println("Duration per speed: " + testDurationMs + "ms");
int totalTests = motorNames.length * testSpeeds.length;
int testCount = 0;
System.out.println("Total tests: " + totalTests);
System.out.println("\nStarting motor test sequence...\n");
// Test each motor at each speed
for (int motorIndex = 0; motorIndex < motorNames.length; motorIndex++) {
String motorName = motorNames[motorIndex];
System.out.println("=== Testing Motor: " + motorName.toUpperCase() + " ===");
System.out.println("Motor " + (motorIndex + 1) + " of " + motorNames.length);
// Test each speed for this motor
for (int speedIndex = 0; speedIndex < testSpeeds.length; speedIndex++) {
testCount++;
double speed = testSpeeds[speedIndex];
int speedPercent = (int)(speed * 100);
System.out.printf("\nTest %d/%d: %s at %d%% power\n",
testCount, totalTests, motorName, speedPercent);
// Simulate motor startup
System.out.print("Starting motor");
for (int dots = 0; dots < 3; dots++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
break;
}
System.out.print(".");
}
System.out.println(" ✅ Running");
// Simulate motor running
System.out.print("Progress: [");
int progressBarLength = 20;
for (int progress = 0; progress <= progressBarLength; progress++) {
// Update progress bar
System.out.print("\rProgress: [");
for (int i = 0; i < progressBarLength; i++) {
if (i < progress) {
System.out.print("█");
} else {
System.out.print("░");
}
}
int percent = (progress * 100) / progressBarLength;
System.out.printf("] %3d%% - %s at %d%% power",
percent, motorName, speedPercent);
try {
Thread.sleep(testDurationMs / progressBarLength);
} catch (InterruptedException e) {
break;
}
}
System.out.println("\n🛑 Motor stopped");
// Simulate motor analysis
double currentDraw = 0.5 + (speed * 2.0) + (Math.random() * 0.3);
double efficiency = 85 + (Math.random() * 10); // 85-95%
boolean testPassed = currentDraw < 3.0 && efficiency > 80;
System.out.printf(" Current draw: %.2f A\n", currentDraw);
System.out.printf(" Efficiency: %.1f%%\n", efficiency);
System.out.println(" Status: " + (testPassed ? "✅ PASS" : "❌ FAIL"));
if (!testPassed) {
System.out.println(" ⚠️ Motor may need maintenance");
}
// Cool down between tests
if (speedIndex < testSpeeds.length - 1) {
System.out.print(" Cooling down");
for (int i = 0; i < 2; i++) {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
break;
}
System.out.print(".");
}
System.out.println();
}
}
System.out.println("\n✅ " + motorName.toUpperCase() + " testing complete");
// Pause between motors
if (motorIndex < motorNames.length - 1) {
System.out.println("\n" + "=".repeat(50));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
}
// Final summary
System.out.println("\n=== Motor Test Sequence Complete ===");
System.out.println("Motors tested: " + motorNames.length);
System.out.println("Total tests performed: " + testCount);
System.out.println("\n🤖 All motors have been tested at multiple speeds.");
System.out.println("📊 Review individual motor results above.");
System.out.println("🔧 Address any failed tests before competition.");
// Summary table
System.out.println("\n📋 Motor Test Summary:");
for (int i = 0; i < motorNames.length; i++) {
String status = (Math.random() > 0.1) ? "✅ PASS" : "❌ FAIL";
System.out.printf(" %12s: %s\n", motorNames[i], status);
}
System.out.println("\nMotor testing system shutdown complete.");
}
}