Facebook Pixel

The For Loop Explained with DSA Examples

Master the 'for' loop, the most widely used loop in programming, and learn how to use it for algorithmic problem-solving.

The Standard of Iteration

When you know exactly how many times you want a block of code to run, the for loop is your best tool. It is the most common loop used in Data Structures and Algorithms, especially when dealing with Arrays.

The Structure of a For Loop

A standard for loop consolidates the initialization, condition, and update steps into a single, highly readable line.

for (int i = 0; i < 10; i++) {
    // Code to execute
}
  1. int i = 0;: Creates a counter variable i, starting at 0.
  2. i < 10;: The condition. The loop runs as long as i is less than 10.
  3. i++: The update. After the block executes, i increases by 1.

For Loops in DSA

The most common use of a for loop in DSA is array traversal. Because array indices start at 0, a for loop naturally pairs with arrays.

for (int i = 0; i < array.length; i++) {
    print(array[i]);
}

This loop guarantees that every element in the array is visited exactly once, from the first element to the last.

The Takeaway

The for loop is clean, predictable, and self-contained. Because it keeps the loop control variables on a single line, it minimizes the risk of infinite loops and makes your iteration logic crystal clear.

Use a for loop when you know exactly how many times you need to iterate, such as when traversing an array of known length.

It is the increment operator. It means 'increase the value of i by 1' after each iteration of the loop.

Yes. You can initialize the counter at a high value, use a greater-than condition, and decrement the counter (e.g., i--).

It occurs when your loop condition tries to access an array element that doesn't exist, usually by looping one time too many (e.g., using i <= array.length).

Yes, variables declared in the initialization step (like 'int i') are scoped only to that loop and disappear when the loop finishes.

Please Login.
Please Login.
Please Login.
Please Login.