Loop Best Practices
Variable Scope in Loops
Variables declared inside a loop only exist within that loop. To use values after the loop ends, declare variables before the loop starts.
Variable Scope - Wrong Way:
Scanner scanner = new Scanner(System.in);
while (true) {
int ones = 0; // [BAD] Variable declared inside loop
System.out.println("Input a number (0 exits): ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
break;
}
if (number == 1) {
ones = ones + 1;
}
}
// [BAD] This won't work - 'ones' doesn't exist here!
// System.out.println("Total ones: " + ones);Variable Scope - Correct Way:
Scanner scanner = new Scanner(System.in);
int ones = 0; // [GOOD] Variable declared before loop
while (true) {
System.out.println("Give a number (end with 0): ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
break;
}
if (number == 1) {
ones = ones + 1;
}
}
// [GOOD] Now we can access 'ones' after the loop
System.out.println("The total of ones: " + ones);Program Structure Best Practices
Keep loops clean by separating the loop logic from the post-loop processing. Place calculations and output after the loop ends, not inside it.
Poor Structure (Avoid):
// [BAD] Poor structure - processing inside loop
Scanner scanner = new Scanner(System.in);
int sum = 0;
int validNumbers = 0;
int invalidNumbers = 0;
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == 0) {
// [BAD] Final processing inside the loop - hard to maintain
System.out.println("Sum: " + sum);
System.out.println("Valid: " + validNumbers);
System.out.println("Invalid: " + invalidNumbers);
break;
}
if (input < 0) {
invalidNumbers++;
continue;
}
sum += input;
validNumbers++;
}Good Structure (Recommended):
// [GOOD] Good structure - clean separation
Scanner scanner = new Scanner(System.in);
// Variables for loop processing
int sum = 0;
int validNumbers = 0;
int invalidNumbers = 0;
System.out.println("Enter numbers (negative invalid, 0 to stop):");
while (true) {
int input = Integer.valueOf(scanner.nextLine());
// Exit condition - clean break
if (input == 0) {
break;
}
// Handle invalid input
if (input < 0) {
invalidNumbers++;
System.out.println("Invalid number: " + input);
continue;
}
// Process valid input
sum += input;
validNumbers++;
System.out.println("Added: " + input);
}
// [GOOD] All final processing after loop
System.out.println("\n=== Final Results ===");
System.out.println("Sum of valid numbers: " + sum);
System.out.println("Valid numbers entered: " + validNumbers);
System.out.println("Invalid numbers entered: " + invalidNumbers);
if (validNumbers > 0) {
double average = (double) sum / validNumbers;
System.out.println("Average: " + average);
}Recommended Loop Structure:
Clean Code Pattern:
- Before loop: Initialize variables and give instructions
- Start of loop: Read input or get next data
- Early exit: Check break conditions first
- Validation: Handle invalid input with continue
- Processing: Handle valid input
- After loop: Display results and final calculations
When to Use Which Loop Type
Choose the right loop type based on your specific needs and the nature of your problem.
Loop Selection Guide:
Choosing the Right Loop:
- For loop: When you know the exact number of iterations
- While with condition: When you have a clear end condition
- While (true) with break: For user input or complex exit conditions
- Continue: Skip invalid input without exiting the loop
Simulating Program Execution:
// Practice tracing through this loop
int result = 0;
for (int i = 0; i < 4; i++) {
result += 3;
}
/*
Execution trace table:
Step | result | i | i < 4 | Action
-----|--------|---|-------|--------
1 | 0 | 0 | true | result = 0 + 3 = 3
2 | 3 | 1 | true | result = 3 + 3 = 6
3 | 6 | 2 | true | result = 6 + 3 = 9
4 | 9 | 3 | true | result = 9 + 3 = 12
5 | 12 | 4 | false | Exit loop
Final result: 12
*/
System.out.println("Result: " + result);Incremental Development
Build complex programs step by step, testing each part before adding the next. This makes debugging easier and ensures each component works correctly.
Step-by-Step Development:
// Robot calibration program - build incrementally
// Step 1: Basic loop structure
// for (int i = 0; i < 5; i++) {
// System.out.println("Step " + i);
// }
// Step 2: Add sensor reading simulation
// for (int i = 0; i < 5; i++) {
// int reading = (int)(Math.random() * 100);
// System.out.println("Calibration step " + i + ": " + reading);
// }
// Step 3: Add processing and validation
System.out.println("=== Robot Sensor Calibration ===");
int totalReadings = 0;
int validReadings = 0;
double sum = 0;
for (int step = 1; step <= 5; step++) {
System.out.println("\nCalibration step " + step + " of 5");
// Simulate sensor reading
double reading = Math.random() * 120; // 0-120 range
totalReadings++;
System.out.println("Raw sensor reading: " + String.format("%.2f", reading));
// Validate reading
if (reading < 0 || reading > 100) {
System.out.println("[WARNING] Reading out of range - skipping");
continue;
}
// Process valid reading
validReadings++;
sum += reading;
System.out.println("[GOOD] Valid reading accepted");
}
// Final calibration results
System.out.println("\n=== Calibration Complete ===");
System.out.println("Total attempts: " + totalReadings);
System.out.println("Valid readings: " + validReadings);
if (validReadings > 0) {
double average = sum / validReadings;
System.out.println("Average calibration value: " + String.format("%.2f", average));
System.out.println("[GOOD] Calibration successful!");
} else {
System.out.println("[BAD] Calibration failed - no valid readings");
}Try It Yourself:
Exercise 1: Best Practices Application
- Refactor a poorly structured loop program using best practices
- Create a data collection system with proper variable scope
- Build a robot diagnostic system using incremental development
- Design a statistics calculator with clean loop structure
Apply best practices to create well-structured programs: