Topic 45 of 100 Control Flow in C Interactive Tutorial

Loops in C: Understanding Repetitive Program Execution

11 mins read Last updated: 22 Aug 2026 21,400 views
C Compiler 0.00%

What is Loops in C? Core Concept & Direct Summary

Core Objective & Problem Statement

What are the three core loop constructs in C (`for`, `while`, `do-while`), and how do entry-controlled vs exit-controlled loops differ?

Direct Answer Summary

Imagine I asked you to print "Hello" five times. Easy — five printf() calls. Now a hundred times. Now a million. Now "keep printing until the user says stop." Suddenly copy-paste isn't a strategy; it's a punishment.

This is the problem loops were invented to solve. A loop tells the computer: "run this block of code again and again, until I say otherwise." It's the second great pillar of control flow (decisions were the first), and honestly, it's the moment programming reveals its superpower — because computers never get bored, never get tired, and never make a mistake on repetition number 999,999.

C gives you three loop statements — for, while, and do-while — plus two controls, break and continue, to manage them. This page gives you the complete map: how each loop thinks, when to use which, and the traps that send beginners into infinite circles. Each loop then gets its own deep-dive tutorial next in this series.

(Suggested image: the hero flowchart — a condition diamond with the "true" path looping BACK to the body, and "false" exiting forward. The loop-back arrow is the whole concept in one image.)


How Does Loops in C Work? In-Depth Mechanics & Architecture

The Anatomy of Every Loop

Despite their different personalities, all three loops share the same four parts:

  1. Initialization — set up a starting point (e.g., i = 1)
  2. Condition — checked to decide whether the loop continues (e.g., i <= 5)
  3. Body — the code that repeats
  4. Update — something that moves the loop toward ending (e.g., i++)

Here's the most important sentence in this tutorial:

If the condition never becomes false, the loop never ends.

Forget the update step, or write a condition that can't fail, and you've built an infinite loop — the program runs forever (or until you kill it with Ctrl+C). Every loop bug you've ever heard of traces back to one of these four parts being wrong.


Loop #1: for — The Counter

for is the organized one. All four parts visible at a glance, three of them packed into the header line:

main.c
Run Online
for (initialization;
condition;
update) {
    // body
}

In action:

main.c
Run Online
#include <stdio.h>
int main() {
    for (int i = 1;
    i <= 5;
    i++) {
        printf("Hello %d\n", i);
    }
    return 0;
}

Output:

main.c
Run Online
Hello 1Hello 2Hello 3Hello 4Hello 5

Read the header as a sentence: "Start i at 1; keep looping while i is at most 5; add 1 after each pass." The condition is checked before every iteration — so for (int i = 10; i <= 5; i++) would run zero times without complaint.

Personality: use for when you know how many times you need to repeat. Counting, tables, array processing (soon!), fixed repetitions.


Loop #2: while — The Condition-Watcher

while strips the loop down to its essence — just a condition and a body:

main.c
Run Online
while (condition) {
    // body — and YOU handle the update inside
}

Initialization happens before the loop; the update happens inside the body. It's your responsibility not to forget them:

main.c
Run Online
#include <stdio.h>
int main() {
    int countdown = 5;
    // initialization
    while (countdown > 0) {
        // condition        printf("%d...\n", countdown);        countdown--;            // update — forget this and it loops forever!    }
        puts("Liftoff! 🚀");
        return 0;
    }

Output:

main.c
Run Online
5...4...3...2...1...Liftoff! 🚀

Like for, the condition is checked before each pass — so a while loop can run zero times. Where while truly shines is when you don't know the count in advance: reading input until the user quits, retrying until input is valid, processing data until it runs out:

main.c
Run Online
int number = 0;
while (number >= 0) {
    // no idea how many times this will run    printf("Enter a number (negative to stop): ");
    scanf("%d", &number);
}
puts("Done!");

Personality: use while when repetition depends on a condition, not a count.


Loop #3: do-while — The Optimist

The odd sibling flips the script: body first, condition after.

main.c
Run Online
do {
    // body — always runs AT LEAST ONCE
} while (condition);

That reversal is the entire point. A do-while guarantees one execution minimum, no matter what:

main.c
Run Online
#include <stdio.h>
int main() {
    int pin;
    do {
        printf("Enter your 4-digit PIN: ");
        scanf("%d", &pin);
    } while (pin != 4321);
    puts("Access granted!");
    return 0;
}

Sample Run:

main.c
Run Online
Enter your 4-digit PIN: 1111Enter your 4-digit PIN: 0000Enter your 4-digit PIN: 4321Access granted!

The prompt must happen before there's anything to check — a while loop would need an awkward workaround; do-while says it naturally. Don't miss the semicolon after while (condition); — it's required here, and forgetting it is a classic compile error.

Personality: use do-while when the body must run at least once — menus, input prompts, "play again?" logic.

(Suggested image: three-panel flowchart comparison — for and while checking BEFORE the body, do-while checking AFTER. The single most useful visual on this page.)


The Three Loops Side by Side

Same task — printing 1 to 5 — three ways:

main.c
Run Online
// forfor (int i = 1; i <= 5; i++) {    printf("%d ", i);}
// whileint i = 1;while (i <= 5) {    printf("%d ", i);    i++;}
// do-whileint j = 1;do {    printf("%d ", j);    j++;} while (j <= 5);

All three print 1 2 3 4 5. Which proves an important truth: any loop can imitate any other. The choice isn't about capability — it's about which one makes your intent obvious to the reader.

QuestionBest Answer
Know the repetition count in advance?for
Repeat until a condition changes; maybe zero times?while
Must run at least once?do-while

The Infinite Loop: Bug and Tool

When the condition can never become false, the loop runs forever:

main.c
Run Online
// ACCIDENTAL infinite loops:int i = 1;
while (i <= 5) {
    printf("%d ", i);
    // forgot i++ — i is 1 forever
}
for (int k = 0;
k < 10;
k--) {
    // wrong direction! k goes 0, -1, -2...    printf("%d ", k);
}

These are bugs — the program hangs, fans spin, Ctrl+C saves the day. But here's the twist: programmers deliberately write infinite loops all the time:

main.c
Run Online
while (1) {
    // 1 is always true — loop forever...    showMenu();
    int choice = readChoice();
    if (choice == 0) {
        break;
        // ...until this exits
    }
}

A menu, a game, a server — anything that should run "until the user quits" is naturally an infinite loop with a break escape hatch. while (1) plus break isn't sloppy code; it's a standard idiom.


break and continue: The Loop Controls

Two statements manage loops from the inside (each gets its own deep-dive later in this cluster):

break — leave the loop entirely:

main.c
Run Online
for (int i = 1;
i <= 10;
i++) {
    if (i == 6) {
        break;
        // exit completely at 6
    }
    printf("%d ", i);
}
// Output: 1 2 3 4 5

continue — skip the rest of this pass, start the next:

main.c
Run Online
for (int i = 1;
i <= 10;
i++) {
    if (i % 2 == 0) {
        continue;
        // skip even numbers
    }
    printf("%d ", i);
}
// Output: 1 3 5 7 9

One line to remember: break leaves the loop; continue skips ahead within it.


Loops Can Nest Too

Just like if statements, loops live inside each other — an inner loop runs completely for every single pass of the outer one:

main.c
Run Online
for (int row = 1;
row <= 3;
row++) {
    for (int col = 1;
    col <= 4;
    col++) {
        printf("[%d,%d] ", row, col);
    }
    printf("\n");
}

Output:

main.c
Run Online
[1,1] [1,2] [1,3] [1,4][2,1] [2,2] [2,3] [2,4][3,1] [3,2] [3,3] [3,4]

3 outer passes × 4 inner passes = 12 iterations total. Nested loops are how you'll print patterns, process tables, and (later) walk through multi-dimensional arrays.


A Complete Example: Multiplication Table Generator

Decisions + loops + formatting — the series coming together:

main.c
Run Online
#include <stdio.h>
int main() {
    int number, upto;
    printf("Which table? ");
    scanf("%d", &number);
    printf("Up to? ");
    scanf("%d", &upto);
    if (upto <= 0) {
        puts("Range must be positive!");
        return 1;
    }
    printf("\n=== Table of %d ===\n", number);
    for (int i = 1; i <= upto; i++) {
        printf("%3d × %2d = %4d\n", number, i, number * i);
    }
    return 0;
}

Sample Run:

main.c
Run Online
Which table? 7Up to? 5
=== Table of 7 === 7 × 1 = 7 7 × 2 = 14 7 × 3 = 21 7 × 4 = 28 7 × 5 = 35

A for loop doing counted repetition, an if guarding against silly input, and %3d/%2d/%4d width formatting from our printf deep-dive keeping every column aligned. Real programs are always a blend like this.


The Five Classic Loop Mistakes

  1. The missing update — condition never changes, loop never ends. Suspect it first whenever a program hangs.
  2. The stray semicolon — for (i = 0; i < 5; i++); loops five times doing nothing, then the body runs once after. That semicolon is an empty statement.
  3. Off-by-one errors — < 5 gives you 0–4 (five passes); <= 5 gives you 0–5 (six). When a loop runs once too many or too few, the comparison operator is the culprit.
  4. Wrong update direction — counting down (i--) toward a condition that needs counting up. The condition stays true forever.
  5. Modifying the loop variable inside the body of a for loop — legal, but it turns predictable counting into chaos. Let the header do the counting.

(Suggested image: "5 Loop Mistakes" checklist graphic — consistent with the series)


Final Thoughts

Loops are where C starts feeling like magic: three lines of code doing the work of three million. The whole topic reduces to one picture — a body of code and a condition, with an arrow looping back — plus one rule: make sure the condition can become false.

Remember the personalities: for counts, while watches, do-while guarantees one run. Choose by intent, not habit. And when a program freezes on you, smile — you've just met your first infinite loop, a rite of passage every C programmer shares.

Next in the series, we zoom in on each loop individually, starting with the workhorse: the for loop.

Runnable C Code Example & Practical Implementation

main.c
Run Online
#include <stdio.h>
int main() {
    printf("Counting with for loop:\
");
    for (int i = 1; i <= 3; i++) {
        printf("  for count: %d\
", i);
    }
    int w = 1;
    printf("Counting with while loop:\
");
    while (w <= 3) {
        printf("  while count: %d\
", w++);
    }
    return 0;
}

Key Takeaways, Best Practices & Memory Safety Rules

Best Practice & Key Takeaways
Use for loops when the iteration count is known beforehand; use while loops for event/condition-driven repetition.

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked C programming interview questions
Q

Q: Which loop in C guarantees execution of the loop body at least once?

A: The `do-while` loop because its condition check occurs at the bottom (exit point).
Q

Q: How do you write an infinite loop in C?

A: `for (;;) { ... }` or `while (1) { ... }`.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations