C:C While and Do-While Loops with Examples
C•Loops

C While and Do-While Loops with Examples

Use while loops when the number of iterations depends on runtime events or sensor reads.

Syntax

while (condition) {} do {} while (condition);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
whileLoopTests condition before running body.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

#include <stdio.h>

int main(void) {
    int countdown = 3;
    printf("--- Rocket Countdown ---\n");
    while (countdown > 0) {
        printf("T-minus %d...\n", countdown);
        countdown--;
    }
    printf("Liftoff! 🚀\n\n");

    // do-while executes at least once
    int attempts = 0;
    do {
        attempts++;
        printf("Polled hardware status: attempt #%d\n", attempts);
    } while (attempts < 1);

    return 0;
}
Expected Output:
--- Rocket Countdown ---
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀

Polled hardware status: attempt #1

How It Works: Step-by-Step

  • Lines 6-9: while loop decrements countdown until 0.
  • Lines 14-17: do-while runs body once before condition check.

Key Concepts

  • The while loop condition is tested before entering the loop.
  • do-while is guaranteed to execute at least once.

Common Mistake: Accidental infinite while loop caused by missing counter update

Failing to mutate the condition variable freezes program execution.

❌ Incorrect
while (i < 5) { printf("%d", i); } // i never changes!
✅ Correct
while (i < 5) { printf("%d", i); i++; }

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler