Skip to content

Beginner · Operators and control flow · topic 9 of 60 · 25 min

Loops: for, while and do-while

Explanation

for loops are for counting, while loops repeat while a condition is true, and do-while runs its body at least once. break leaves a loop and continue skips to the next round; for (;;) is an infinite loop ended by break. Watch out for off-by-one errors and the stray semicolon after for (...).

for

c
for (int i = 1; i <= 5; i++) {
    printf("7 x %d = %d\n", i, 7 * i);
}
Initialise; test before each round; update after each round. Declaring i inside for needs C99 or later.

while and do-while

c
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

c
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);
}
Embedded programs often run a "super loop" like this forever.

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

c
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) printf("*");
    printf("\n");
}
/* *
   **
   ***
   **** */

Classic loop bugs

c
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 */
Careful: C does not check array bounds, so an off-by-one loop silently writes into other variables' memory, and the bug may appear far away. Use i < N for arrays of size N, and compile with -fsanitize=address while testing (module 11) to catch it immediately.

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.

Think of it like this: A for loop is like a teacher calling roll numbers from 1 to 40: the count is known. A while loop is like waiting at a bus stop until your bus comes: you do not know how long. do-while is like tasting the dal before deciding whether it needs more salt: you always taste at least once.
Tip: Write the loop condition so it clearly ends: count up to a limit, or move toward a condition that will become false. Then check the first and last iterations by hand.

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

Loops

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.

c
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)

Task 1 · Question

What does this print? int s = 0; for (int i = 1; i <= 10; i += 3) s += i; printf("%d\n", s);

Task 2 · Question

How many times does the body run? int i = 5; do { i++; } while (i < 5);

Task 3 · Practice

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

Question 1

1.Which loop always runs its body at least once?

Question 2

2.What does continue do?

Question 3

3.for (unsigned i = 3; i >= 0; i--) — what happens?

Question 4

4.What is wrong with: for (i = 0; i < n; i++); { sum += a[i]; }

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

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.

From Loops: for, while, do-while and range-for

What causes an infinite loop?Related

Answer: A condition that never becomes false

If nothing moves the loop toward its end, it never stops.

From Loops: repeating work

Which loop always runs its body at least once?Related

Answer: do…while

do…while checks the condition after the first run.

From Loops: for, while, do…while, for…of and for…in

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks the condition after the body.

From Loops: for, while, do-while and foreach

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. 1 more topic in “Operators and control flow” before its exam: Solving problems with loops.
  2. Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and arrays. 60 topics left in the course before the final exam.

← Previous: Decisions: if, else and switch