Loops (for, while, do-while)

⚙️ C Language 🟢 Lesson 6 of 20 📅 2026 Edition
Loops let you repeat a block of code without duplicating it. C provides three loop types — for, while, and do-while — each suited to slightly different situations, and understanding when to use each is a core skill for writing clean C code.
1The for Loop
C Language ▶ Run Code
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}

A for loop has three parts separated by semicolons: initialization (int i = 0, runs once), condition (i < 5, checked before every iteration), and increment (i++, runs after every iteration). This makes it ideal when you know exactly how many times you want to repeat something.

2The while Loop
C Language ▶ Run Code
int count = 0;
while (count < 3) {
    printf("Attempt %d\n", count + 1);
    count++;
}

A while loop checks its condition before each iteration, and keeps running as long as it stays true. Use it when the number of repetitions depends on something that isn't known in advance — like reading input until the user types "quit".

3The do-while Loop
C Language ▶ Run Code
int num;
do {
    printf("Enter a positive number: ");
    scanf("%d", &num);
} while (num <= 0);

The key difference from a regular while loop: a do-while loop checks its condition after running the block, guaranteeing the code inside runs at least once — perfect for input validation, where you need to ask the user at least one time no matter what.

4break, continue, and Nested Loops
C Language ▶ Run Code
for (int i = 1; i <= 5; i++) {
    if (i == 4) break;        // exit the loop entirely
    if (i == 2) continue;     // skip this iteration, go to next i
    printf("%d\n", i);
}

// Nested loop for a multiplication table
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        printf("%d ", i * j);
    }
    printf("\n");
}
⚠️ Common Mistake: Using = Instead of == in a Loop Condition

Writing while (num = 0) instead of while (num == 0) is dangerous in C because it's not a syntax error — num = 0 is a valid assignment that evaluates to 0 (false), so the loop simply never runs, and no error message tells you why. Always double-check for double equals signs in every condition.

💻 Try It Yourself

Print a simple multiplication table for the number 7, from 7×1 up to 7×10, using a for loop.

C Language ▶ Run Code
#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        printf("7 x %d = %d\n", i, 7 * i);
    }
    return 0;
}
Run This in Our Compiler →