C in 100 Seconds: While Loops | Episode 7
Video: C in 100 Seconds: while vs do-while — Two Ways to Loop | Episode 7 by Taught by Celeste AI - AI Coding Coach
Watch full page →While Loops — Repeating Code in C
C in 100 Seconds, Episode 7
Loops let you repeat a block of code without writing it out multiple times. The while loop is the simplest form — it keeps going as long as its condition is true.
The While Loop
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
Output: 1 2 3 4 5
The condition is checked before each iteration. If the condition is false from the start, the body never executes.
Do...While
Sometimes you want the body to run at least once, regardless of the condition:
int j = 10;
do {
printf("%d ", j);
j--;
} while (j >= 8);
Output: 10 9 8
The condition is checked after each iteration. This guarantees at least one execution.
While vs Do...While
The difference is simple: while checks first, do...while checks last. Use do...while when you need the loop body to run at least once — like reading user input before validating it.
Watch for Infinite Loops
If the condition never becomes false, the loop runs forever. Always make sure something inside the loop changes the condition variable. Forgetting i++ in a while loop is a classic beginner mistake.
Full Code
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n");
int j = 10;
do {
printf("%d ", j);
j--;
} while (j >= 8);
printf("\n");
return 0;
}
Compile and Run
gcc while.c -o while
./while
Next episode: For Loops — the compact loop for when you know how many times to iterate.
Student code: github.com/GoCelesteAI/c-in-100-seconds/episode07