Java Loops
for, while, do-while loops and iterations
1. Loop Overview & Types
Loops execute a block of code repeatedly until a specified condition is met. They eliminate code duplication and handle repetitive tasks efficiently.
For Loop
Known number of iterations
for (init; condition; increment)
While Loop
Condition checked before execution
while (condition)
Do-While Loop
Execute at least once
do { } while (condition)
Enhanced For
Iterate through collections
for (type item : collection)
Loop Execution Flow
Start → Initialize → Check Condition → Execute Body → Update/Increment → Repeat
2. For Loops
Traditional For Loop
// Print numbers 1 to 5
for (int i = 1; i 5; i++) {
System.out.println("Number: " + i);
}
// Countdown from 10 to 1
for (int i = 10; i >= 1; i--) {
System.out.println(i);
}
Enhanced For Loop (For-Each)
// Iterate through array
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
// Iterate through String array
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
For Loop Components
- Initialization:
int i = 0- Executed once at the start - Condition:
i < 10- Checked before each iteration - Update:
i++- Executed after each iteration
Common For Loop Patterns
for (int i = 0; i < n; i++)
for (int i = n; i > 0; i—)
for (int i = 0; i < n; i += 2)
for (int i = 0; i < arr.length; i++)
Nested For Loops
// Print multiplication table
for (int i = 1; i 5; i++) {
for (int j = 1; j 5; j++) {
System.out.print((i * j) + "\t");
}
System.out.println(); // New line after each row
}
// Pattern printing
for (int i = 1; i 5; i++) {
for (int j = 1; j "* ");
}
System.out.println();
}
3. While Loops
While loops continue executing as long as the condition remains true. The condition is checked before each iteration.
while (condition) {
// Code to execute repeatedly
// Don't forget to update condition variable!
}
Basic While Loop Examples
// Count from 1 to 5
int count = 1;
while (count 5) {
System.out.println("Count: " + count);
count++; // Important: update condition variable
}
// Sum of numbers until user enters 0
Scanner scanner = new Scanner(System.in);
int sum = 0;
int number = 1; // Initialize to non-zero
while (number != 0) {
System.out.print("Enter a number (0 to stop): ");
number = scanner.nextInt();
sum += number;
}
System.out.println("Total sum: " + sum);
Input Validation
// Validate user input
Scanner input = new Scanner(System.in);
int age = -1; // Invalid initial value
while (age 0 || age > 150) {
System.out.print("Enter your age (0-150): ");
age = input.nextInt();
if (age 0 || age > 150) {
System.out.println("Invalid age! Please try again.");
}
}
System.out.println("Valid age entered: " + age);
Infinite Loop Warning
Always ensure the loop condition will eventually become false. Forgetting to update the condition variable is a common cause of infinite loops.
4. Do-While Loops
Do-while loops execute the body at least once, then check the condition. Perfect for scenarios where you need guaranteed execution.
While Loop
Check Condition → Execute (if true)
May not execute at all
Do-While Loop
Execute Body → Check Condition
Always executes at least once
do {
// Code to execute at least once
// Update condition variable
} while (condition);
Menu System Example
Scanner input = new Scanner(System.in);
int choice;
do {
System.out.println("=== MENU ===");
System.out.println("1. Option 1");
System.out.println("2. Option 2");
System.out.println("3. Option 3");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1: System.out.println("Option 1 selected"); break;
case 2: System.out.println("Option 2 selected"); break;
case 3: System.out.println("Option 3 selected"); break;
case 0: System.out.println("Goodbye!"); break;
default: System.out.println("Invalid choice!");
}
} while (choice != 0);
When to Use Do-While
- Menu systems that must show at least once
- Input validation with guaranteed prompt
- Game loops that run until player quits
- Operations that must execute at least once
5. Loop Control Statements
Control statements modify the normal flow of loop execution: break exits the loop, continue skips to the next iteration.
break Statement
Exits the loop immediately
Loop → Condition → break → Exit
continue Statement
Skips rest of current iteration
Loop → continue → Next Iteration
Break Statement Examples
// Find first even number
int[] numbers = {1, 3, 8, 5, 9};
for (int num : numbers) {
if (num % 2 == 0) {
System.out.println("First even number: " + num);
break; // Exit loop immediately
}
}
// Search for value
int target = 25;
boolean found = false;
for (int i = 0; i if (numbers[i] == target) {
found = true;
break; // Stop searching
}
}
Continue Statement Examples
// Print only positive numbers
int[] numbers = {-2, 5, -1, 8, 0, 3};
for (int num : numbers) {
if (num 0) {
continue; // Skip negative and zero
}
System.out.println("Positive: " + num);
}
// Skip multiples of 3
for (int i = 1; i 10; i++) {
if (i % 3 == 0) {
continue; // Skip 3, 6, 9
}
System.out.print(i + " "); // Prints: 1 2 4 5 7 8 10
}
Labeled Loops (Advanced)
outerLoop: for (int i = 1; i 3; i++) {
for (int j = 1; j 3; j++) {
if (i * j == 4) {
System.out.println("Found 4 at " + i + "," + j);
break outerLoop; // Break from outer loop
}
System.out.println(i + " x " + j + " = " + (i * j));
}
}
Label Guidelines
Use labels sparingly and only when absolutely necessary. They can make code harder to read and maintain. Consider restructuring your logic instead.
6. Practical Examples
Sum Calculator
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
int sum = 0;
for (int i = 1; i "Sum of 1 to " + n + " = " + sum);
Factorial Calculator
int number = 5;
int factorial = 1;
int i = 1;
while (i "! = " + factorial); // 5! = 120
Number Guessing Game
Scanner input = new Scanner(System.in);
int secretNumber = (int)(Math.random() * 100) + 1;
int guess;
int attempts = 0;
do {
System.out.print("Guess the number (1-100): ");
guess = input.nextInt();
attempts++;
if (guess "Too low!");
} else if (guess > secretNumber) {
System.out.println("Too high!");
} else {
System.out.println("Correct! You won in " + attempts + " attempts.");
}
} while (guess != secretNumber);
7. Best Practices
Do’s
- Choose the right loop type for your scenario
- Always update the loop condition variable
- Use meaningful variable names
- Keep loop bodies simple and focused
- Use enhanced for-loops for simple iteration
- Initialize variables before the loop
Don’ts
- Don’t create infinite loops accidentally
- Don’t modify loop variables inside enhanced for-loops
- Don’t use magic numbers in loop conditions
- Don’t nest loops too deeply (max 2-3 levels)
- Don’t ignore loop efficiency for large datasets
- Don’t use break/continue excessively
Loop Selection Guide
- Known iterations count → For Loop
- Iterate through collection → Enhanced For Loop
- Unknown iterations, condition-based → While Loop
- Must execute at least once → Do-While Loop
Performance Considerations
- Cache Array Length: Store
arr.lengthin a variable for long loops - Minimize Nested Loops: O(n) becomes O(n²) with nesting
- Early Exit: Use break statements to exit loops early when result is found
- Move Conditions Outside: Check invariant conditions before the loop
Key Takeaways
- Loops eliminate code repetition and handle repetitive tasks efficiently
- Choose the right loop type: for (counting), while (condition), do-while (at least once)
- Always ensure loop termination to avoid infinite loops
- Use break and continue judiciously to control loop flow