Lesson 4 of 6 · Control Flow · 3 min read · Updated
Loops: while, do-while, and for
Three ways to repeat work, and how to choose between them.
Printing 1 to 100 by hand would be a hundred lines. A loop does it in three.
for — when you know how many times
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
1 2 3 4 5
The three parts of a for loop
-
int i = 1
The setup. Runs once, before anything else. This is where the counter starts.
-
i <= 5
The test. Checked before every pass. While it is true the loop keeps going; the moment it is false the loop ends.
-
i++
The step. Runs after each pass, before the test is checked again. Forget this and the loop never ends.
Step 1 of 3
while — when you do not know how many times
int n;
printf("Enter a number (0 to stop): ");
scanf("%d", &n);
while (n != 0) {
printf("You typed %d\n", n);
printf("Another (0 to stop): ");
scanf("%d", &n);
}
do-while — when it must run at least once
int choice;
do {
printf("1. Start 2. Help 3. Quit\n");
printf("Choice: ");
scanf("%d", &choice);
} while (choice < 1 || choice > 3);
Note
The difference is when the test happens. while checks before the first pass, so it may run zero times. do-while checks after, so it always runs at least once. Menus want do-while.
Warning
An infinite loop happens when the condition never becomes false — usually because you forgot to change the variable it tests. Press Ctrl+C to stop a runaway program.
break and continue
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; /* skip just this pass */
}
if (i == 8) {
break; /* leave the loop entirely */
}
printf("%d ", i);
}
1 2 3 4 6 7
Which loop always runs its body at least once?
Try this now
- Print the multiplication table for a number the user chooses.
- Add up the numbers from 1 to 100 with a loop, and print the total.
- Read numbers until the user types 0, then print how many were positive.
Create a free account to save your progress, or sign in.