Control Flow Lesson 8 of 16
C Loops — while, do-while and for
Repeat code in C with while, do-while and for loops, use break and continue, and build sums, countdowns, multiplication tables and patterns with nested loops.
Loops repeat code. C has three: while, do-while and for. They're the same as in Java, JavaScript and C++, because those languages copied them from C.
while
#include <stdio.h>
int main(void) {
int savings = 0, weeks = 0;
while (savings < 1000) {
savings += 150;
weeks++;
}
printf("%d weeks to save P%d\n", weeks, savings);
return 0;
}
Output
7 weeks to save P1050
do-while
The body runs first, then the condition is checked, so it always runs at least once:
#include <stdio.h>
int main(void) {
int n = 4096, digits = 0;
do {
n /= 10;
digits++;
} while (n > 0);
printf("Digits: %d\n", digits);
return 0;
}
Output
Digits: 4
With a plain while, the number 0 would be counted as having 0 digits. The do-while correctly counts it as 1.
for
#include <stdio.h>
int main(void) {
for (int i = 10; i >= 1; i--) {
printf("%d ", i);
}
printf("Liftoff!\n");
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
printf("Sum 1-100: %d\n", sum);
return 0;
}
Output
10 9 8 7 6 5 4 3 2 1 Liftoff! Sum 1-100: 5050
Declaring the counter inside the for (like int i = 0) is allowed since C99. Very old compilers require declaring int i; before the loop.
break and continue
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 20; i++) {
if (i % 3 == 0) continue; /* skip multiples of 3 */
if (i > 10) break; /* stop after 10 */
printf("%d ", i);
}
printf("\n");
return 0;
}
Output
1 2 4 5 7 8 10
Nested loops: multiplication table
#include <stdio.h>
int main(void) {
for (int r = 1; r <= 5; r++) {
for (int c = 1; c <= 5; c++) {
printf("%4d", r * c);
}
printf("\n");
}
return 0;
}
Output
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Pattern: number triangle
#include <stdio.h>
int main(void) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) printf(" ");
for (int j = 1; j <= i; j++) printf("%d ", j);
printf("\n");
}
return 0;
}
Output
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Fibonacci sequence
#include <stdio.h>
int main(void) {
long long a = 0, b = 1;
printf("First 15 Fibonacci numbers:\n");
for (int i = 0; i < 15; i++) {
printf("%lld ", a);
long long next = a + b;
a = b;
b = next;
}
printf("\n");
return 0;
}
Output
First 15 Fibonacci numbers: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Which loop to use?
| Loop | Use when |
|---|---|
for | You know how many times (counting, arrays) |
while | Repeat until something happens; may run zero times |
do-while | Must run at least once (menus, input checks) |
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04