Blog Posts > Loops in C: for, while, and do-while Explained

Loops in C: for, while, and do-while Explained

Loops in C let you run the same block of code many times without rewriting it. C gives you three loop types: for, while, and do-while. Use for when you know the count, while when you loop until a condition changes, and do-while when the body must run at least once.

Why loops matter

Imagine printing the numbers 1 to 100, or adding up the marks of 60 students in a class register. Writing 100 or 60 separate lines is slow and error-prone. A loop does the repetition for you: you write the logic once, and the computer runs it as many times as needed. This is one of the first real "programming" skills you build after variables and conditions.

Every loop in C has three parts to think about: where it starts, the condition that keeps it running, and how the loop variable changes each time. If the condition never becomes false, you get an infinite loop that never stops. Keeping these three parts clear in your head prevents most beginner bugs.

The for loop

The for loop packs all three parts into one line, which makes it the best choice when you know exactly how many times to repeat. The syntax is for (initialization; condition; update).

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        printf("Number: %d\n", i);
    }
    return 0;
}

Here int i = 1 runs once at the start. Before each pass, C checks i <= 5; if true, the body runs. After the body, i++ adds 1 to i. The loop stops when i becomes 6.

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

The while loop

The while loop checks the condition first, then runs the body. Use it when you do not know the exact number of repetitions in advance, only the condition that should stop the loop. If the condition is false at the start, the body never runs.

#include <stdio.h>

int main(void) {
    int count = 1;
    while (count <= 5) {
        printf("Count is %d\n", count);
        count++;
    }
    return 0;
}

Notice that the loop variable count is created before the loop, and you must update it inside the body with count++. Forgetting that update is the most common cause of an infinite loop, because the condition stays true forever.

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

The do-while loop

The do-while loop runs the body first and checks the condition afterward. This guarantees the body executes at least once, even if the condition is false from the start. It is a good fit for input menus, where you show a prompt before testing what the user typed.

#include <stdio.h>

int main(void) {
    int n = 10;
    do {
        printf("Value: %d\n", n);
        n++;
    } while (n <= 5);
    return 0;
}

Even though n starts at 10 and the condition n <= 5 is already false, the body still runs once. Note the semicolon after while (...) in a do-while loop; leaving it out is a frequent compile error.

Output:

Value: 10

When to use each loop

  • for — you know the number of iterations (counting 1 to 10, looping over array indexes).
  • while — you repeat until a condition changes, and the body may run zero times (read input until end-of-file).
  • do-while — the body must run at least once before the condition is checked (menus, retry prompts).

All three are interchangeable in theory, so pick the one that reads most clearly. Beginners reach for for most often because it keeps the loop control in a single, visible place.

break and continue

Two keywords give you finer control inside a loop. break exits the loop immediately, skipping any remaining iterations. continue skips the rest of the current iteration and jumps to the next one.

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 10; i++) {
        if (i == 6) {
            break;       // stop the loop at 6
        }
        if (i % 2 == 0) {
            continue;    // skip even numbers
        }
        printf("%d\n", i);
    }
    return 0;
}

The loop prints odd numbers below 6. When i is even, continue skips the printf. When i reaches 6, break ends the loop entirely.

Output:

1
3
5

Nested loops

A loop placed inside another loop is a nested loop. The inner loop completes all its passes for every single pass of the outer loop. This is how you print grids, tables, and patterns. A common classroom example in Bangladesh is printing a multiplication table or a star pyramid.

#include <stdio.h>

int main(void) {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= row; col++) {
            printf("* ");
        }
        printf("\n");
    }
    return 0;
}

For each row, the inner loop prints as many stars as the row number, then a newline moves to the next line. Be careful with nested loops: the work grows quickly, so three nested loops over large ranges can be slow.

Output:

*
* *
* * * 

A practical example: sum of numbers

Loops shine when you accumulate a result. This program adds the numbers from 1 to 50 using a running total. Notice how sum is declared before the loop and updated each pass.

#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 50; i++) {
        sum += i;    // same as sum = sum + i
    }
    printf("Sum from 1 to 50 is %d\n", sum);
    return 0;
}

Output:

Sum from 1 to 50 is 1275

Try changing 50 to another number and predict the result before you run it. Practising this kind of mental tracing builds the habit you need for harder problems and coding interviews.

Common mistakes to avoid

  • Forgetting to update the loop variable, which creates an infinite loop.
  • Using = (assignment) instead of == (comparison) in the condition.
  • An off-by-one error: i < 5 runs five times (0–4), while i <= 5 runs six (0–5).
  • Putting a semicolon right after for (...) or while (...), which makes the loop body empty.
  • Missing the semicolon after the condition in a do-while loop.

Frequently asked questions

Which loop should a beginner learn first?
Start with the for loop. It keeps the start value, condition, and update together on one line, so you can see all three parts of the loop at once. Once you are comfortable with for, while and do-while feel natural because they use the same logic split across different lines.

What is the difference between while and do-while?
A while loop checks its condition before running the body, so the body can run zero times if the condition starts false. A do-while loop runs the body once first, then checks the condition, so the body always runs at least one time regardless of the condition.

How do I stop an infinite loop?
An infinite loop usually means the condition never becomes false. Make sure the loop variable changes toward the stop value each pass, for example with i++. While a program is running in the terminal, you can force it to stop by pressing Ctrl + C on your keyboard.

Can I use break and continue in any loop?
Yes. Both break and continue work inside for, while, and do-while loops. break exits the loop entirely, and continue jumps to the next iteration. In nested loops, they affect only the innermost loop that contains them, not the outer loops.

Mastering loops is a core step toward C jobs and other programming roles — explore openings at Avian™ Career once you are confident with the basics.

Keep practising by rewriting each example as a different loop type. If you can turn a for loop into a while loop and back again, you truly understand how loops in C work.


Categories

  • Tutorial
  • Announcement
  • News