Beginner · Operators and control flow · topic 9 of 60 · 25 min
Loops: for, while and do-while
Explanation
for
for (int i = 1; i <= 5; i++) {
printf("7 x %d = %d\n", i, 7 * i);
}while and do-while
int balance = 1000, months = 0;
while (balance > 0) {
balance -= 300;
months++;
}
printf("%d\n", months); /* 4 */
int choice;
do {
printf("1) Balance 2) Withdraw 0) Exit: ");
if (scanf("%d", &choice) != 1) break;
} while (choice != 0); /* the menu is shown at least once */break, continue and infinite loops
for (;;) { /* no condition: loops forever */
int reading = read_sensor();
if (reading < 0) continue; /* skip bad readings */
if (reading > 900) break; /* stop on an alarm */
log_reading(reading);
}break leaves only the innermost loop (or switch). To leave nested loops, use a flag variable, put the loops in a function and return, or (sparingly) goto to a clean-up label.
Nested loops
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= row; col++) printf("*");
printf("\n");
}
/* *
**
***
**** */Classic loop bugs
for (int i = 0; i < 10; i++); /* stray semicolon: the loop body is empty */
{
printf("%d\n", i); /* compile error here (i is out of scope), or runs once in older code */
}
int a[5];
for (int i = 0; i <= 5; i++) a[i] = 0; /* off by one: writes a[5], past the end (undefined behaviour) */
unsigned int k;
for (k = 10; k >= 0; k--) { } /* never ends: an unsigned value is always >= 0 */goto (rarely)
C has goto label;. Using it to jump around makes code unreadable, but a common accepted use in C (including the Linux kernel) is jumping forward to a single clean-up section that frees resources when an error occurs in a function. Do not use it for normal loops.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Loops: for, while and do-while · 1/6
In this lesson you will repeat work with C loops.
Prefer a video by a teacher? Find free videos on “c loops for while do while break continue tutorial” on YouTube ↗
In real life: Polling a sensor in a cold store
A cold-storage controller reads the temperature every second in an endless loop, skips faulty readings, and raises an alarm if the temperature rises above a limit. This "super loop" is the most common structure in small embedded programs.
for (;;) {
int t = read_temperature_tenths(); /* e.g. -185 means -18.5 °C */
if (t == SENSOR_ERROR) continue;
if (t > -150) sound_alarm(); /* warmer than -15 °C */
sleep_ms(1000);
}Practice (0/3 done)
What does this print? int s = 0; for (int i = 1; i <= 10; i += 3) s += i; printf("%d\n", s);
How many times does the body run? int i = 5; do { i++; } while (i < 5);
Write a program that prints the multiplication table of a number n (read with scanf) from 1 to 10, then prints a right-angled triangle of n rows of stars using nested loops, then uses a while loop to count how many times n can be halved (integer division) before it reaches 0.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Solving problems with loopsOperators and control flow · same module
- Type conversion and castingOperators and control flow · same module
- Loops: for, while, do-while and range-forC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Loops: repeating workFrontend Web Development · JavaScript basics
- Loops: for, while, do…while, for…of and for…inJavaScript Programming (language in depth) · Strings, decisions and loops
- Loops: for, while, do-while and foreachC# and .NET · Decisions, loops and methods
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which loop always runs its body at least once?
Answer: do-while
The test comes after the body.
What does continue do?
Answer: Skips to the next iteration of the loop
continue jumps to the next round.
for (unsigned i = 3; i >= 0; i--) — what happens?
Answer: Never ends, because unsigned i is always >= 0
After 0, i wraps to a huge value.
What is wrong with: for (i = 0; i < n; i++); { sum += a[i]; }
Answer: The semicolon makes the loop body empty
The block runs once after the loop.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks its condition after the body.
What causes an infinite loop?Related
Answer: A condition that never becomes false
If nothing moves the loop toward its end, it never stops.
Which loop always runs its body at least once?Related
Answer: do…while
do…while checks the condition after the first run.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks the condition after the body.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Operators and control flow” before its exam: Solving problems with loops.
- Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and arrays. 60 topics left in the course before the final exam.