DEV Community

Aditya
Aditya

Posted on Originally published at techvaniai.blogspot.com

Loops in C: for, while and do-while (C Learning Guide, Part 4)

In Part 4 of our beginner C series we move from decisions to repetition: loops. for, while and do-while can all express any repetition, but each one makes one shape of work read most clearly.

What the full guide covers:

  • The three loop shapes and how to pick between them: for when you know the number of passes (one per box, numbers 1 to 10), while when you repeat until a condition changes (packing until nothing remains), and do-while when the work must happen at least once (asking a question until the answer is valid).
  • break and continue: leave early or skip a turn without stopping everything.
  • Input validation loops: refuse bad input before the loop uses it, and re-ask without writing the question twice.
  • A side-by-side comparison table (condition checked when, runs at least once, when to reach for it) and runnable examples with verified expected output.

A taste of the style - counting down with a for loop:

#include <stdio.h>
int main(void) {
    for (int i = 3; i >= 1; i--) {
        printf("%d\n", i);
    }
    printf("Go!\n");
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

3
2
1
Go!
Enter fullscreen mode Exit fullscreen mode

Read the full guide with every example and practice exercise: Loops in C: for, while and do-while - C Learning Guide, Part 4

New to the series? It starts from zero setup here: Programming in C - Learning Guide series index

Top comments (0)