Loading
0x60Lesson 7 of 15

Loops: while, for, do-while

Repeat work with loops, control them with break and continue, and avoid the classic off-by-one.

14 min 6-question quiz 2 code exercises
By the end of this lesson you can
  • Write while, for and do-while loops
  • Choose the right loop for a job
  • Use break and continue, and spot off-by-one errors

Computers are good at doing the same thing many times. A loop repeats a block of code while a condition stays true. C has three kinds.

while

countdown.c
1#include <stdio.h>
2
3int main(void) {
4    int n = 3;
5    while (n > 0) {
6        printf("%d...\n", n);
7        n--;
8    }
9    printf("Liftoff!\n");
10    return 0;
11}
Output
3...
2...
1...
Liftoff!

A while loop checks its condition before each pass. If the condition is false from the start, the body never runs. Something inside the body must eventually make the condition false - here, n-- - or the loop runs forever.

for

Counting loops are so common that C has a dedicated form that puts the setup, the condition and the update on one line:

squares.c
1#include <stdio.h>
2
3int main(void) {
4    for (int i = 1; i <= 5; i++) {
5        printf("%d squared is %d\n", i, i * i);
6    }
7    return 0;
8}
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

for (init; condition; update) runs init once, then repeats: check condition, run the body, run update. Declaring int i inside the parentheses keeps it scoped to the loop, which is good practice.

Accumulating a result

A very common pattern: start a variable at a neutral value, and update it each pass. Sum starts at 0, product at 1, maximum at the first value.

sum.c
1#include <stdio.h>
2
3int main(void) {
4    int sum = 0;
5    for (int i = 1; i <= 100; i++) {
6        sum += i;
7    }
8    printf("1 + 2 + ... + 100 = %d\n", sum);
9    return 0;
10}
Output
1 + 2 + ... + 100 = 5050

do-while

A do { ... } while (condition); loop checks its condition after the body, so the body always runs at least once. It fits "do something, then decide whether to repeat" - like asking for input until it is valid. Note the semicolon after the closing while (...).

break and continue

break exits the loop immediately. continue skips the rest of the current pass and moves on to the next one (in a for loop, the update still runs).

skip.c
1#include <stdio.h>
2
3int main(void) {
4    for (int i = 1; i <= 10; i++) {
5        if (i % 2 == 0) {
6            continue;   // skip even numbers
7        }
8        if (i > 7) {
9            break;      // stop entirely
10        }
11        printf("%d ", i);
12    }
13    printf("\n");
14    return 0;
15}
Output
1 3 5 7

Nested loops

A loop can contain another loop. The inner loop runs completely for each pass of the outer one - perfect for grids and tables:

triangle.c
1#include <stdio.h>
2
3int main(void) {
4    for (int row = 1; row <= 4; row++) {
5        for (int col = 1; col <= row; col++) {
6            printf("*");
7        }
8        printf("\n");
9    }
10    return 0;
11}
Output
*
**
***
****

Key takeaways

  • while checks first; do-while runs at least once; for bundles init, condition and update for counting loops.

  • for (int i = 0; i < n; i++) runs exactly n times. Check first and last values to avoid off-by-one errors.

  • break leaves the loop; continue skips to the next pass. Make sure every loop can end.

Lesson quiz

6 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write real C

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

Multiplication table

+25 XP

Read an integer n and print its multiplication table from 1 to 5, one line each, formatted exactly like this for n = 7:

17 x 1 = 7
27 x 2 = 14
37 x 3 = 21
47 x 4 = 28
57 x 5 = 35
  • Table of 7
  • Table of 3
main.c
Loading editor…

Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Exercise 2

Sum of digits

+25 XP

Read a non-negative integer and print the sum of its digits. For 4096 the answer is 19 (4 + 0 + 9 + 6).

Use a while loop with % 10 (last digit) and / 10 (drop the last digit).

  • 4096
  • 7
  • 0
main.c
Loading editor…

Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Sign in to ask questions, help other learners, and earn XP for taking part.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: