for Loop

Iteration with counter

Interview Relevant: Essential for array and string manipulation problems
6 min read

The for Loop

The for loop is the most commonly used loop when you know in advance how many times you want to iterate.

Syntax Structure

for (initialization; condition; update) {
    // loop body
}
  • Initialization: Executed once at the start
  • Condition: Checked before each iteration
  • Update: Executed after each iteration

🔑 Execution Order: initialization → condition → body → update → condition → body → update → ... until condition is false

Loop Variations

  • Forward iteration: i++ (most common)
  • Backward iteration: i-- (reverse traversal)
  • Step by N: i += N (skip elements)
  • Multiple variables: int i = 0, j = 10

⚠️ Common Bug: Off-by-one errors! Use < for 0 to n-1, or <= for 0 to n. Always verify your bounds.

Code Examples

Basic for loop and array iteration

java
1// Basic for loop - print numbers 1 to 5
2for (int i = 1; i <= 5; i++) {
3    System.out.println(i);
4}
5// Output: 1 2 3 4 5
6
7// Loop through array
8int[] numbers = {10, 20, 30, 40, 50};
9for (int i = 0; i < numbers.length; i++) {
10    System.out.println("Index " + i + ": " + numbers[i]);
11}

Reverse iteration and custom step values

java
1// Reverse iteration
2String str = "Hello";
3for (int i = str.length() - 1; i >= 0; i--) {
4    System.out.print(str.charAt(i));
5}
6// Output: olleH
7
8// Step by 2 (even numbers only)
9for (int i = 0; i <= 10; i += 2) {
10    System.out.print(i + " ");
11}
12// Output: 0 2 4 6 8 10

Nested loops for 2D patterns

java
1// Nested for loops (multiplication table)
2for (int i = 1; i <= 5; i++) {
3    for (int j = 1; j <= 5; j++) {
4        System.out.printf("%4d", i * j);
5    }
6    System.out.println();
7}
8/*
9   1   2   3   4   5
10   2   4   6   8  10
11   3   6   9  12  15
12   4   8  12  16  20
13   5  10  15  20  25
14*/
15
16// Triangle pattern
17for (int i = 1; i <= 5; i++) {
18    for (int j = 1; j <= i; j++) {
19        System.out.print("* ");
20    }
21    System.out.println();
22}

Advanced for loop patterns

java
1// Multiple variables in for loop
2for (int i = 0, j = 10; i < j; i++, j--) {
3    System.out.println("i=" + i + ", j=" + j);
4}
5// i=0, j=10
6// i=1, j=9
7// ...until i >= j
8
9// Infinite loop (use with break)
10for (;;) {
11    System.out.println("This runs forever!");
12    break;  // Exit immediately
13}
14
15// Empty parts are valid
16int k = 0;
17for (; k < 5; ) {
18    System.out.println(k++);
19}

Use Cases

  • Array and collection traversal
  • Counting operations
  • Pattern printing
  • Matrix operations
  • String manipulation
  • Generating sequences

Common Mistakes to Avoid

  • Off-by-one errors (< vs <=)
  • Infinite loops (forgetting to update counter)
  • Modifying loop variable inside body unexpectedly
  • Using wrong comparison direction
  • Not accounting for empty arrays (length == 0)
  • Integer overflow in very large loops