for Loop
Basic for Loop
public class ForLoop {
public static void main(String[] args) {
// Standard for loop
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// Output: 0, 1, 2, 3, 4
// Counting down
for (int i = 10; i > 0; i--) {
System.out.print(i + " ");
}
System.out.println(); // 10 9 8 7 6 5 4 3 2 1
// Step by 2
for (int i = 0; i < 10; i += 2) {
System.out.print(i + " ");
}
System.out.println(); // 0 2 4 6 8
}
}
For Loop Components
// init; condition; update
for (int i = 0; i < 10; i++) {
// i=0; i<10? yes; i++
// i=1; i<10? yes; i++
// ...
// i=10; i<10? no → exit
}
// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println(i + ", " + j);
}
// Output: 0,10 1,9 2,8 3,7 4,6
// Infinite loop
for (;;) {
// runs forever (use break to exit)
}
Enhanced for Loop (for-each)
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println(); // 1 2 3 4 5
// Collections
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
// Cannot modify array with for-each
for (int num : numbers) {
// num = 0; // ERROR: final variable
}
// Use regular for loop to modify
for (int i = 0; i < numbers.length; i++) {
numbers[i] *= 2; // OK
}
while Loop
Basic while Loop
public class WhileLoop {
public static void main(String[] args) {
// Standard while loop
int i = 0;
while (i < 5) {
System.out.println("i = " + i);
i++;
}
// While with condition
Scanner sc = new Scanner(System.in);
System.out.print("Enter positive number: ");
int num = sc.nextInt();
while (num <= 0) {
System.out.print("Try again: ");
num = sc.nextInt();
}
System.out.println("You entered: " + num);
}
}
do-while Loop
// Executes at least once
public class DoWhile {
public static void main(String[] args) {
int i = 10;
// while loop: may not execute
while (i < 5) {
System.out.println(i); // never executes
}
// do-while: executes at least once
do {
System.out.println(i); // prints 10
i++;
} while (i < 5);
// Menu example
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("1. Play");
System.out.println("2. Settings");
System.out.println("3. Exit");
choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Playing..."); break;
case 2: System.out.println("Settings..."); break;
case 3: System.out.println("Goodbye!"); break;
}
} while (choice != 3);
}
}
Loop Comparison
| Loop | When to Use | Executes At Least |
|---|---|---|
| for | Known iterations | No |
| while | Unknown iterations, condition first | No |
| do-while | Must execute once | Yes |
break and continue
break Statement
// Exit loop early
public class BreakDemo {
public static void main(String[] args) {
// Find first even number
int[] nums = {1, 3, 5, 8, 9, 12};
for (int num : nums) {
if (num % 2 == 0) {
System.out.println("First even: " + num);
break; // exit loop
}
}
// Output: First even: 8
// Break in nested loops (labeled break)
outer:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking at " + i + ", " + j);
break outer; // exits outer loop
}
}
}
}
}
continue Statement
// Skip current iteration
public class ContinueDemo {
public static void main(String[] args) {
// Print only odd numbers
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.print(i + " ");
}
System.out.println(); // 1 3 5 7 9
// Continue in nested loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) continue; // skip j=1
System.out.print(i + "," + j + " ");
}
}
// Output: 0,0 0,2 1,0 1,2 2,0 2,2
}
}
Labeled break and continue
// Labeled break
outer:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i + j == 5) break outer;
}
}
// Labeled continue
outer:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 2) continue outer;
}
}
Nested Loops
Nested Loop Patterns
// Multiplication table
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
}
// Output:
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
// 4 8 12 16 20
// 5 10 15 20 25
2D Array Traversal
public class MatrixTraversal {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Row-major order
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
// Enhanced for loop
for (int[] row : matrix) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
}
Diagonal Traversal
// Print matrix diagonals
public class DiagonalTraversal {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Main diagonal
for (int i = 0; i < matrix.length; i++) {
System.out.print(matrix[i][i] + " ");
}
System.out.println(); // 1 5 9
// Anti-diagonal
int n = matrix.length;
for (int i = 0; i < n; i++) {
System.out.print(matrix[i][n - 1 - i] + " ");
}
System.out.println(); // 3 5 7
}
}
Spiral Order
// Print matrix in spiral order
public class SpiralOrder {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++)
System.out.print(matrix[top][i] + " ");
top++;
for (int i = top; i <= bottom; i++)
System.out.print(matrix[i][right] + " ");
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--)
System.out.print(matrix[bottom][i] + " ");
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--)
System.out.print(matrix[i][left] + " ");
left++;
}
}
}
}
Time Complexity of Nested Loops
Single loop: O(n)
for (int i = 0; i < n; i++) { ... }
Nested loops: O(n²)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) { ... }
}
Triple nested: O(n³)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) { ... }
}
}
Common Loop Patterns
Pattern 1: Accumulator
// Sum of array
int sum = 0;
for (int num : numbers) {
sum += num;
}
// Product of array
long product = 1;
for (int num : numbers) {
product *= num;
}
Pattern 2: Counter
// Count even numbers
int count = 0;
for (int num : numbers) {
if (num % 2 == 0) count++;
}
// Count occurrences
int count = 0;
for (char c : str.toCharArray()) {
if (c == target) count++;
}
Pattern 3: Find Max/Min
// Find maximum
int max = numbers[0];
for (int num : numbers) {
if (num > max) max = num;
}
// Find minimum
int min = numbers[0];
for (int num : numbers) {
if (num < min) min = num;
}
Pattern 4: Search
// Linear search
int target = 5;
int index = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
index = i;
break;
}
}
Pattern 5: StringBuilder
// Build string efficiently
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i).append(" ");
}
String result = sb.toString();
Pattern 6: Reverse
// Reverse array
for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}
Pattern 7: Two Nested Loops
// Bubble sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
// Check all pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
// found pair
}
}
}
Practice Problems
What is the output of this code?
Example:
Input: public class Test { public static void main(String[] args) { int x = 1; while (x < 10) { x *= 2; } System.out.println(x); } }
Output: 16
x: 1 → 2 → 4 → 8 → 16. Loop exits when x=16 (not < 10).
Optimal Solution — O(log n) time, O(1) space
Trace through loop iterations
public class Test {
public static void main(String[] args) {
int x = 1;
while (x < 10) {
x *= 2; // 1→2→4→8→16
}
System.out.println(x); // 16
}
}Edge Cases:
- Infinite loops
- Off-by-one errors
What is the output of this code?
Example:
Input: public class Test { public static void main(String[] args) { int count = 0; for (int i = 0; i < 4; i++) { for (int j = i; j < 4; j++) { count++; } } System.out.println(count); } }
Output: 10
i=0: j=0,1,2,3 (4 iterations). i=1: j=1,2,3 (3). i=2: j=2,3 (2). i=3: j=3 (1). Total: 4+3+2+1=10.
Optimal Solution — O(n²) time, O(1) space
Count iterations systematically
public class Test {
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = i; j < 4; j++) {
count++;
}
}
System.out.println(count); // 4+3+2+1 = 10
}
}Edge Cases:
- Different loop bounds
- Infinite nested loops
Find and fix the bug in this code.
Example:
Input: public class Bug { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println(i); // forgot to increment i! } } }
Output: Infinite loop printing 0
i is never incremented, so the condition i < 5 is always true.
Optimal Solution — O(n) time, O(1) space
Add increment statement
public class Bug {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++; // add increment!
}
}
}Edge Cases:
- Multiple variables
- Complex conditions
Print the following pattern for n=5: * ** *** **** *****
Example:
Input: 5
Output: * ** *** **** *****
Each row has i stars where i goes from 1 to n.
Optimal Solution — O(n²) time, O(1) space
Use nested loops to print pattern
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}Edge Cases:
- n=1
- Large n
Reverse an array in-place.
Example:
Input: [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Swap elements from both ends moving inward.
Optimal Solution — O(n) time, O(1) space
Two pointers from both ends
class Solution {
public void reverseArray(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}Edge Cases:
- Empty array
- Single element
Quiz
1. How many times does this loop execute? for(int i=0; i<10; i+=2)
2. What is the difference between while and do-while?
3. What does continue do in a loop?
4. What is the time complexity of a nested loop with both running n times?
5. When should you use a for-each loop?
Flashcards
Question
What are the three loop types in Java?
Click to reveal answer
Answer
1) for - known iterations 2) while - condition first 3) do-while - executes at least once
Question
What is the difference between break and continue?
Click to reveal answer
Answer
break exits the loop entirely. continue skips to the next iteration.
Question
When does a while loop execute?
Click to reveal answer
Answer
Only when the condition is true. It may execute zero times if the condition is initially false.
Question
How do you exit a nested loop?
Click to reveal answer
Answer
Use a labeled break: outer: for(...) { break outer; } exits the outer loop.
Question
What is the time complexity of nested loops?
Click to reveal answer
Answer
Two nested loops running n times each = O(n²). Three nested = O(n³).
Revision Notes
Key Takeaways
- 1.Use for loop for known iterations, while for unknown
- 2.do-while executes at least once
- 3.break exits loop, continue skips iteration
- 4.Nested loops have O(n²) complexity
- 5.for-each is cleaner for reading elements
Interview Tips
- •Know loop time complexity for algorithm analysis
- •Use labeled break for nested loop exits
- •Practice pattern printing problems
- •Avoid infinite loops by ensuring termination
Cheat Sheet
Loops Cheat Sheet
for loop:
for (int i = 0; i < n; i++) { ... }
for-each:
for (int num : array) { ... }
while:
while (condition) { ... }
do-while:
do { ... } while (condition);
break: exits loop
continue: skips to next iteration
Time Complexity:
- Single loop: O(n)
- Nested loops: O(n²)
- Triple nested: O(n³)
Common Patterns:
- Accumulator (sum, product)
- Counter (count occurrences)
- Find max/min
- Linear search