Insights into Company
← Data Structures & Algorithms

Data Structures & Algorithms

01 For Loop in Programming
A for loop repeats a block of code in a controlled way. Use it when the number of iterations is known, when traversing a sequence, or when generating a predictable series.

1. Basic for loop

Initialization runs once, the condition is checked before every iteration, and the update runs after the loop body.

for (int i = 2; i <= 10; i += 2) {
    System.out.print(i + " " );
}
// 2 4 6 8 10

2. For-each loop

Use for-each when you need every element and do not need its index.

int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.print(number + " " );
}
// 1 2 3 4 5

3. Multiple control variables

Java permits more than one initializer and update expression. Keep the condition clear.

for (int i = 0, j = 10; i < 5 && j > 0; i++, j--) {
    System.out.println("i=" + i + ", j=" + j);
}

4. Infinite for loop

An omitted condition is always true. Provide a safe break, cancellation, or shutdown condition.

for (;;) {
    // Repeats until break, return, or process termination.
}

5. Nested for loop

The inner loop completes for each outer-loop iteration. This is useful for matrices and patterns.

for (int row = 1; row <= 3; row++) {
    for (int column = 1; column <= 3; column++) {
        System.out.print(row * column + " " );
    }
    System.out.println();
}

6. Step or stride

Adjust the update expression to skip values or count backwards.

for (int i = 0; i < 10; i += 2) {
    System.out.print(i + " " );
}
// 0 2 4 6 8
Algorithm analysis

When studying this topic, always ask: how much time does it take, how much memory does it use and how does performance change as input size grows?

Time Input growth
Space Extra memory
Trade-off Speed vs memory
Run / study this example
public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " " );
        }
        System.out.println();
    }
}

// Output: 1 2 3 4 5

Hands-on challenge

Change the loop to print the even numbers from 2 through 10. Then rewrite it as a for-each loop over an integer array.

Quick quiz

Which statement is correct?

Solution & Explanation

Correct answer: A. The condition is checked before each iteration
In a conventional Java for loop, initialization runs once, then condition, body, and update repeat.
Interview approach: Explain the concept, give a small example, mention an important edge case or trade-off, and discuss time and space complexity when applicable.