Loops let a program repeat a block of code without writing it out multiple times. C provides three looping constructs — while, for, and do-while — each suited to slightly different situations. This is Post 1 of the Unit II series, following Unit I’s coverage of decision making.
The while Loop
Checks its condition before each iteration — if the condition is false from the start, the body never runs even once.
while (condition) {
// body
}
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
Sample Output
1 2 3 4 5
The for Loop
Bundles initialization, condition, and update into one line — ideal when you know in advance how many times you want to repeat something.
for (initialization; condition; update) {
// body
}
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
Sample Output
1 2 3 4 5
The do-while Loop
Checks its condition after the body runs — guaranteeing the body executes at least once, even if the condition is false from the start.
do {
// body
} while (condition);
#include <stdio.h>
int main() {
int choice;
do {
printf("\nMenu: 1) Add 2) Subtract 3) Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
if (choice == 1) printf("Result: addition selected\n");
else if (choice == 2) printf("Result: subtraction selected\n");
else if (choice != 3) printf("Invalid choice, try again.\n");
} while (choice != 3);
printf("Goodbye!\n");
return 0;
}
Choosing Between Them
| Loop | Condition checked | Best for |
|---|---|---|
while |
Before each iteration | Unknown iteration count, condition-driven (e.g. read until EOF) |
for |
Before each iteration | Known iteration count (e.g. loop exactly n times) |
do-while |
After each iteration | Body must run at least once (menus, input validation) |
Nested Loops: Printing a Pattern
#include <stdio.h>
int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Sample Output
*
* *
* * *
* * * *
* * * * *
The outer loop controls the row number; the inner loop, which restarts fresh on every outer iteration, prints exactly as many stars as the current row number.
Summary
while: checks first, may run zero times.for: compact form for known-count loops, checks first.do-while: checks last, always runs at least once.- Nested loops let an inner loop repeat completely for every single iteration of an outer loop — the basis of most pattern-printing and matrix-processing programs.
Further Reading
Next in this series: break, continue, and goto statements.