C course menu
Loops in C: for, while and do-while Explained
An overview of loops in C: the three loop types, how each one works, when to use for, while or do-while, loop counters and accumulators, infinite loops, and nested loops, with examples.
Loops repeat a block of code. C has three loop statements, and every repetition you will ever need can be written with them.
The three loops#
#include <stdio.h>
int main(void) {
/* for: counting a known number of times */
for (int i = 1; i <= 3; i++) {
printf("for %d\n", i);
}
/* while: repeat while a condition is true */
int n = 1;
while (n <= 3) {
printf("while %d\n", n);
n++;
}
/* do-while: runs at least once, checks afterwards */
int k = 1;
do {
printf("do-while %d\n", k);
k++;
} while (k <= 3);
return 0;
}for 1
for 2
for 3
while 1
while 2
while 3
do-while 1
do-while 2
do-while 3Accumulating a result#
Loops often build a result step by step:
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
printf("%d\n", sum);
long long factorial = 1;
for (int i = 2; i <= 15; i++) {
factorial *= i;
}
printf("%lld\n", factorial);5050
1307674368000long long is needed for the factorial: 15! does not fit in a 32-bit int.
Infinite loops#
A loop whose condition never becomes false runs forever. Sometimes that is intended, such as a server or an embedded device's main loop:
while (1) {
read_sensor();
update_display();
}When it is not intended, it is a bug: check that something in the loop moves it towards its end. Press Ctrl+C in the terminal to stop a runaway program.
Nested loops#
A loop inside a loop runs completely for each repetition of the outer loop:
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) {
printf("*");
}
printf("\n");
}*
**
***
****The following lessons cover each loop in depth: for Loops, while and do-while and break, continue and goto.
Practice#
Practice exercise
Print the multiplication table of 9 from 9 x 1 = 9 to 9 x 10 = 90, then print the sum of all the results.
Show solution
#include <stdio.h>
int main(void) {
int total = 0;
for (int i = 1; i <= 10; i++) {
printf("9 x %d = %d\n", i, 9 * i);
total += 9 * i;
}
printf("Sum: %d\n", total);
return 0;
}9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
Sum: 495Key takeaway#
Finished this lesson?