C Loops

Beginner
12 min read
Updated: Nov 2026
5 examples
3 loop guides

Definition and Usage

A loop repeats a block of code until a condition becomes false or you exit with break. Without loops, C programs could not walk arrays, print patterns, validate input, or run menus without copy-pasting the same lines.

Three loop forms

C gives you exactly three looping statements: for, while, and do-while. Any of them can express the same logic, but each shape makes certain programs clearer.

What should beginners learn first?

Start with for for counted work (for (int i = 0; i < n; i++)). Switch to while when repetition depends on input or an external condition. Use do-while when the body must run at least once (menus, validation prompts).

Hub vs single-loop pages

This page teaches how loops work in a C tutorial. Each name in the table links to a focused guide with syntax, examples, and FAQs. Nested loops and break / continue appear in the concepts and examples below.

Prefer clarity over cleverness.

If a counter and stop rule belong together, use for. If you wait on input, use while. If the body must run once first, use do-while.

Infinite loops.

If the condition never becomes false (or you forget to update the counter), the loop runs forever. Always check that something moves toward the stop condition.

C99 loop variables.

You can declare int i inside for (...) with -std=c99 or newer. In older C, declare i before the loop.

C Syntax

All three 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);

Core C Concepts

How to choose a loop in everyday C programs:

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

Loop control

ToolEffect
break;Leave the innermost loop immediately
continue;Skip the rest of this iteration; go to the next test/update
Nested loopsInner loop finishes fully for each outer step (patterns, tables)

for header parts

PartWhen it runsExample
InitializationOnce, before the first testint i = 0
ConditionBefore every iterationi < n
UpdateAfter each iterationi++

How to Use Loops in C

A practical workflow for this tutorial track:

  1. Decide whether you have a count/index, an open-ended condition, or a must-run-once body.
  2. Pick for, while, or do-while to match that shape.
  3. Write the stop condition first so you know how the loop ends.
  4. Update counters or input inside the loop so the condition can become false.
  5. Use break / continue sparingly when early exit or skip is clearer.
  6. Open a single-loop page from the table when you need a full walkthrough.

Live Preview

Choose how many times to run a counted loop—same idea as for (int i = 1; i <= n; i++) in C.

Simulates printing i from 1 to n. Cap is 12 for a short preview.

Preview
1 2 3 4 5

for (int i = 1; i <= 5; i++) → 5 iterations

C Examples

Five starter patterns from a C tutorial. Compile with gcc file.c -std=c11 -o out.

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;
}
for Tutorial

How It Works

  1. Init sets i = 1 once.
  2. Condition keeps looping while i <= 10.
  3. Update runs i++ after each add.
  4. for keeps those three parts in one header.

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;
}
while Tutorial

How It Works

  1. Initialize n before the loop.
  2. Test n > 0 before each pass.
  3. Update n-- inside the body.
  4. while fits open-ended “keep going until…” logic.

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;
}
do-while Tutorial

How It Works

  1. Body first shows the prompt before any test.
  2. scanf reads the choice.
  3. while repeats while the value is out of range.
  4. Trailing semicolon after while (...) is required.

Example 4 — Nested for multiplication table

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

  1. Outer for picks the row.
  2. Inner for prints every column for that row.
  3. 3 × 3 = 9 body runs for the product cells.
  4. Star / alphabet patterns use the same nesting 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

  1. Same counting job can use any of the three forms.
  2. for packs init/test/update together.
  3. while / do-while keep update in the body.
  4. Pick the form that makes your intent clearest.

C Loops Table

Loop guides in this C tutorial track. Open any row for a full guide with syntax, examples, and FAQs (3 tutorials).

Counted & pre-test loops

2 tutorials

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

LoopDescriptionTutorial
for loopinit; condition; update in one header.Try it
while loopPre-test: body may run zero times.Try it

Post-test loop

1 tutorial

Run the body first, then decide whether to repeat.

LoopDescriptionTutorial
do-while loopPost-test: always runs at least once.Try it

Edge Cases & Pitfalls

Most loop bugs in C are off-by-one errors, missing updates, or the wrong pre/post-test choice.

±1

Off-by-one (< vs <=)

i < n runs n times from 0; i <= n runs n+1 times. Match the bound to your intent.

∞

Forgot to update

If the counter or input never changes, while / do-while never stop.

;

Empty loop body

for (...); with a trailing semicolon runs an empty body—often a silent bug.

do

do-while when zero times is OK

If the body may need to be skipped, use while or for instead.

brk

break only exits one level

In nested loops, break leaves only the innermost loop. Plan flags or restructure for multi-level exits.

C89

Declaring i inside for

Needs C99+. Compile with -std=c99 / -std=c11, or declare i before the loop.

Platform Support

for, while, and do-while are core C language features—available everywhere C compiles.

FeatureSupportNotes
for / while / do-whileUniversalSince early C; same on GCC, Clang, MSVC
break / continueUniversalInnermost loop only
for (int i = 0; …)C99+Use -std=c99 or newer
Nested loopsUniversalNo special library; watch complexity

Key Takeaways

  • Three loops: for, while, do-while.
  • Start with for for counts; while for conditions; do-while for “at least once.”
  • break / continue control flow inside the innermost loop.
  • Next: for loop, then while and do-while.

One line: C loops repeat work—use for for counts, while for conditions, do-while when the body must run once, then open each loop guide for details.

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 comparison table and examples on this page, then open the for loop tutorial first if you are new to C loops. Follow the sidebar order: for, while, do-while.

Start with the for loop

Open the counted-loop guide first, then continue to while and 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.

8 people found this page helpful