Coding Manifestation Logo

Loops (for / while / nested loops)

Loops (for / while / nested loops)

"A loop is how you tell the computer: do this task not once, but a hundred times — without writing it a hundred times."

Part 1: The for Loop

The for loop is the most common loop in DSA. You use it when you know exactly how many times you want to repeat something — like going through every element of an array.

Basic for loop

Three parts inside the parentheses: start, condition, step.

javascript
// Print numbers 0 to 4
for (let i = 0; i < 5; i++) {
    console.log(i);
}
// Output: 0 1 2 3 4

Looping over an array

This is one of the most used patterns in DSA — visit every element using its index.

javascript
let fruits = ["apple", "banana", "mango"];

for (let i = 0; i < fruits.length; i++) {
    console.log(i, fruits[i]);
}
// Output:
// 0 apple
// 1 banana
// 2 mango

Looping backwards

javascript
let nums = [10, 20, 30, 40];

for (let i = nums.length - 1; i >= 0; i--) {
    console.log(nums[i]);
}
// Output: 40 30 20 10

for...of — Clean iteration over values

When you don't need the index, for...of is cleaner.

javascript
let scores = [85, 92, 78];

for (let score of scores) {
    console.log(score);
}
// Output: 85 92 78

Part 2: while and do-while

Use while when you don't know in advance how many iterations you need — only when to stop.

while loop

The condition is checked before every iteration. If it starts false, the body never runs.

javascript
let count = 0;

while (count < 5) {
    console.log(count);
    count++;
}
// Output: 0 1 2 3 4

// Real-world example: keep asking until valid input
let password = "";
while (password !== "secret") {
    password = "secret"; // simulating user input
}
console.log("Access granted!");

do-while loop — runs at least once

The body executes first, then the condition is checked. Useful when you always want to run the block at least one time.

javascript
let num = 10;

do {
    console.log("num is:", num);
    num++;
} while (num < 5);

// Output: num is: 10
// (runs once even though 10 < 5 is false from the start)

Infinite loops — what to avoid

If the condition never becomes false, the loop runs forever and crashes your program.

javascript
// ❌ Infinite loop — i never changes!
let i = 0;
while (i < 5) {
    console.log(i);
    // forgot i++
}

// ✅ Fixed
while (i < 5) {
    console.log(i);
    i++;
}

Part 3: break and continue

These two keywords give you control over loop flow without writing complex conditions.

break — Exit the loop early

Stops the entire loop immediately when a condition is met.

javascript
let nums = [3, 7, 2, 9, 5];

// Stop as soon as we find 9
for (let n of nums) {
    if (n === 9) break;
    console.log(n);
}
// Output: 3 7 2

continue — Skip an iteration

Skips the rest of the current iteration and jumps to the next one.

javascript
// Print only odd numbers
for (let i = 1; i <= 8; i++) {
    if (i % 2 === 0) continue;
    console.log(i);
}
// Output: 1 3 5 7

Nested loops — the most important pattern in DSA

A loop inside a loop. The inner loop runs completely for every single iteration of the outer loop. This is how you work with 2D arrays and matrices.

javascript
// Print a 3x3 grid
for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 3; col++) {
        process.stdout.write(`[${row},${col}] `);
    }
    console.log();
}
// [0,0] [0,1] [0,2]
// [1,0] [1,1] [1,2]
// [2,0] [2,1] [2,2]

// Nested loops = O(n²) time — important for Big O!