The while loop
- C course
- Beginner
- Lesson 43/116
- 4 min
Learn loops that run while a condition holds with while.
The while loop
The while loop runs as long as the condition is true. The condition is checked first; if false, the body never runs.
int n = 5;
while (n > 0) {
printf("%d\n", n);
n--;
}Here n starts at 5, decrements each iteration, and the loop ends when n reaches 0. Output: 5 4 3 2 1. Without n-- in the body the loop would be infinite; be careful.
for vs while
Any for loop can be written as a while. for is preferred when the iteration count is known; while when the condition is more dynamic.
// with for
for (int i = 0; i < 5; i++) { ... }
// the same with while
int i = 0;
while (i < 5) { ...; i++; }Both work identically. With for the counter is declared in one line; with while it spreads across four lines. Which to use depends on context.
Practice Count down from 5
Write a C program. Declare int n = 5;. Use a while (n > 0) loop to print printf("%d\n", n); and decrement with n--;. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare n, count down with while
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int n = 5;
while (n > 0) {
printf("%d\n", n);
n--;
}
return 0;
}Expected output
5 4 3 2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the condition
while (____ > 0) {
printf("%d", n);
n--;
}
while (n > 0) {
printf("%d", n);
n--;
}
Explanation: n > 0 keeps looping while n is positive.
2 When does while (n > 0) end?
while (n > 0) {
n--;
}- When n=1
- When n=5
- Never
- When n=0 Correct answer
Explanation: When n reaches 0 the condition becomes false and the loop ends.
3 Match the loop types
| Term | Meaning |
|---|---|
for |
Counted loop |
while |
Conditional loop |
i++ |
Increment |
n-- |
Decrement |