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:
| Parameter | Type | Description |
|---|---|---|
| while | Loop | Tests condition before running body. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C While and Do-While Conditional Repetition Pipelines
Construct robust while pre-test loops and do-while post-test execution pipelines in C with safety guards and retry counters.
C Break and Continue Statements in Loops
Interrupt or skip loop cycles using break and continue in C.
C Short-Circuit Ternary Logic and Conditional Expressions
Implement short-circuit logical expressions (&&, ||) and compact ternary operators in C for defensive null checks and inline branching.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.