C Loops

Beginner
⏱️ 14 min read
📚 Updated: Jul 2026
🎯 3 Tutorials
for · while · do-while

What You’ll Learn

Loops let you repeat code without copy-pasting it dozens of times. C gives you three tools: for for counted work, while for open-ended repetition, and do-while when the body must run at least once. This hub explains when to use each and links to full tutorials with five examples each.

01

for

Counted loops.

02

while

Pre-test.

03

do-while

Post-test.

04

break

Exit early.

05

Nested

Patterns.

06

3 guides

Full index.

Definition and Usage

A loop executes a block of code repeatedly until a condition becomes false or you exit with break. Without loops, programs could not walk arrays, print patterns, validate input, or run menus—every repeated task would need duplicate lines.

C standardizes three loop forms. They are interchangeable in theory (any loop can be rewritten as another), but each shape makes certain programs clearer. This page compares them; each tutorial below goes deep with syntax, examples, and FAQs.

💡
Beginner Tip

Start with the for loop when counting (for (int i = 0; i < n; i++)). Switch to while when you repeat until user input or file data ends. Use do-while when you must prompt or show a menu before the first condition check.

📝 Syntax

All three C loop forms side by side:

C
/* for — init, test, update in header */
for (int i = 0; i < n; i++) {
    /* body */
}

/* while — test before body */
while (condition) {
    /* body */
}

/* do-while — body first, then test; note semicolon */
do {
    /* body */
} while (condition);

Loop control

  • break; — leave the innermost loop immediately
  • continue; — skip to the next iteration
  • Nested loops — inner loop completes for each outer step

Compile

C
gcc main.c -std=c11 -o main

⚡ Quick Reference

LoopWhen to useBody runs min times
forKnown count or index walk0 (if condition false at start)
whileRepeat until external condition changes0
do-whilePrompt/menu must run once1

C Loop Tutorial Index

Search by loop name or browse by category. Every card links to a full guide with five examples and FAQs.

Counted & Pre-Test Loops

2 tutorials

Repeat with a clear counter or test the condition before each pass.

Post-Test Loop

1 tutorial

Run the body first, then decide whether to repeat.

Examples Gallery

Five small programs showing each loop type in action. Compile with gcc file.c -std=c11 -o out.

📚 Getting Started

One example per loop type.

Example 1 — Sum with for

Add integers 1 through 10 with a counted for loop.

C
#include <stdio.h>

int main(void) {
    int sum = 0;

    for (int i = 1; i <= 10; i++) {
        sum += i;
    }

    printf("Sum 1..10 = %d\n", sum);
    return 0;
}

How It Works

for keeps init, test, and update in one line—ideal when the iteration count is known.

Example 2 — Countdown with while

Decrement until the condition fails.

C
#include <stdio.h>

int main(void) {
    int n = 5;

    while (n > 0) {
        printf("%d...\n", n);
        n--;
    }

    printf("Go!\n");
    return 0;
}

How It Works

You initialize n before the loop and update it inside—the classic while pattern.

📈 Practical Patterns

Validation, patterns, and comparing loop forms.

Example 3 — Input Validation with do-while

Prompt at least once; repeat until input is valid.

C
#include <stdio.h>

int main(void) {
    int choice;

    do {
        printf("Pick 1, 2, or 3: ");
        if (scanf("%d", &choice) != 1) {
            return 1;
        }
    } while (choice < 1 || choice > 3);

    printf("You picked %d\n", choice);
    return 0;
}

How It Works

The prompt always appears before the first validity check—why do-while beats while here.

Example 4 — Multiplication Table with Nested for

Outer loop = rows, inner loop = columns.

C
#include <stdio.h>

int main(void) {
    int row, col;

    for (row = 1; row <= 3; row++) {
        for (col = 1; col <= 3; col++) {
            printf("%d ", row * col);
        }
        printf("\n");
    }

    return 0;
}

How It Works

Nested loops multiply iterations: 3 × 3 = 9 cells. Star and alphabet patterns use the same idea.

Example 5 — Print 0, 1, 2 Three Ways

Same result with for, while, and do-while.

C
#include <stdio.h>

int main(void) {
    int i;

    printf("for:       ");
    for (i = 0; i < 3; i++) {
        printf("%d ", i);
    }
    printf("\n");

    printf("while:     ");
    i = 0;
    while (i < 3) {
        printf("%d ", i);
        i++;
    }
    printf("\n");

    printf("do-while:  ");
    i = 0;
    do {
        printf("%d ", i);
        i++;
    } while (i < 3);
    printf("\n");

    return 0;
}

How It Works

All three can count, but each shines in different situations. Pick the form that makes your intent clearest.

🚀 Common Use Cases

  • Array processing — walk every element by index.
  • Pattern printing — nested loops for triangles and grids.
  • User menuswhile or do-while until exit.
  • Input validationdo-while retry until valid.
  • File I/Owhile until EOF.
  • Search — loop with break when found.

🧠 How C Loops Fit Together

1

Pick a loop

for, while, or do-while based on your pattern.

Choose
2

Test condition

Before body (for/while) or after (do-while).

Control
3

Run body

Execute code; update counters or read input.

Repeat
=

Done

Condition false or break — continue program.

📝 Notes

  • Semicolon after do { } while (cond); is required.
  • Avoid while (cond); with a stray semicolon after the header.
  • Always ensure the condition can become false to avoid accidental infinite loops.
  • for loop variables declared in the header are scoped to the loop (C99+).
  • Nested loops increase total iterations multiplicatively.
  • break only exits one level of nesting; use flags or goto for complex exits.

🚀 Usage Tips

  • Learn for first — most array and counting code uses it.
  • Read each tutorial — five examples and FAQs per loop type.
  • Match loop to problem — do not force everything into for.
  • Trace by hand — write i values on paper for the first few iterations.
  • Follow sidebar order — for → while → do-while.

Conclusion

C loops are the backbone of repetition in real programs. Use this hub to compare for, while, and do-while, then open each tutorial for deep coverage with examples and best practices.

New to loops? Start with the for loop tutorial, then work through while and do-while in the sidebar.

💡 Best Practices

✅ Do

  • Use for for index-based array walks
  • Update condition variables inside while bodies
  • Use do-while for must-show-once prompts
  • Check scanf return values in input loops
  • Use break to exit search loops early

❌ Don’t

  • Forget i++ and create infinite loops
  • Put a semicolon after while (cond) by mistake
  • Use do-while when zero iterations is correct
  • Nest loops deeply without clear variable names
  • Choose while (1) when do-while is clearer

Key Takeaways

Knowledge Unlocked

Five things to remember about C loops

Your map to all three loop tutorials on this site.

5
Core concepts
🔄 02

while

Pre-test.

Input
03

do-while

Min once.

Menus
🔗 04

Nested

Patterns.

Grid
📚 05

3 guides

Full index.

Hub

❓ Frequently Asked Questions

Loops repeat a block of code while a condition holds or for a set number of iterations. C provides for, while, and do-while. They power counting, array walks, menus, input validation, and pattern printing.
for bundles init, test, and update in one header—best for counted loops. while tests before the body—the body may run zero times. do-while tests after the body—it always runs at least once.
Use for when you know the iteration pattern upfront (index from 0 to n-1). Use while when repetition depends on runtime input or an external condition (read until EOF, menu until quit).
Use do-while when the body must run at least once before you can test the stop condition—input validation prompts, menus that must display once, play-again dialogs.
break leaves the innermost loop immediately. continue skips the rest of the current iteration and jumps to the next condition test. Both work inside for, while, and do-while.
Read the overview and comparison table, try the five examples, then open the for loop tutorial first if you are new to C loops. Follow the sidebar order: for, while, do-while.
Did you know?

C has exactly three looping statements: for, while, and do-while. break exits the innermost loop; continue skips to the next iteration. Any loop can become infinite if the condition never becomes false.

Start Your First Loop Tutorial

Open the for loop guide, or follow sidebar order from for through do-while.

for loop tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

3 people found this page helpful