Skip to content

Module 3 · Decisions and Loops — topic 3 of 5

Loops: while, do-while and for

Loops repeat code. Learn the three C loops, how each checks its condition, how to write counting and sentinel loops, and how to avoid infinite and off-by-one loops.

Beginner 18 min read·Lesson 13 of 37 in C Programming

Learning objectives

  • Write while, do-while and for loops
  • Choose the right loop for counting, sentinel and validation tasks
  • Trace loop variables and avoid off-by-one errors

Definition

An iteration statement repeatedly executes a body while a controlling expression compares unequal to zero. while and for test before each iteration (entry-controlled); do-while tests after (exit-controlled), so its body runs at least once.

Introduction

Printing a table, summing a list, retrying input until it is valid — anything that repeats is a loop. C has three loop statements that differ mainly in when they check the condition.

Every loop needs the same three ingredients: something that starts it (initialisation), something that keeps it going (the condition) and something that moves it towards the end (an update). Forgetting the update produces an infinite loop.

Why it matters

Loops are where programs spend almost all their time, and where most logic errors live. Being able to trace a loop by hand — writing down the variable values each iteration — is the most useful debugging skill a beginner can learn.

Pattern printing, digit manipulation and series problems in exams are all loop exercises.

Detailed explanation

`while (cond) body` checks the condition first. If it is false initially, the body never runs. Use it when you don't know in advance how many iterations are needed.

`do body while (cond);` runs the body first and checks afterwards, so it always runs at least once. It is ideal for menus and input validation. Note the semicolon after the condition.

`for (init; cond; update) body` gathers the three ingredients in one line. It is the natural choice for counting. Any part may be empty; for (;;) is an infinite loop.

Since C99 you can declare the counter inside the for: for (int i = 0; i < n; i++). That i exists only inside the loop.

LoopCondition checkedMinimum runsTypical use
whilebefore each iteration0unknown count, sentinel input
do-whileafter each iteration1menus, validate-and-retry
forbefore each iteration0counting, arrays

Syntax

C
while (condition) {
/* body */
}
do {
/* body runs at least once */
} while (condition);
for (int i = 0; i < n; i++) {
/* body */
}
  • i < n with i starting at 0 runs exactly n times.
  • The do-while ends with a semicolon.
  • Keep the update next to the condition so infinite loops are easy to spot.

Code examples

Counting with for

C
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++)
printf("%d x 7 = %d\n", i, i * 7);
return 0;
}
Output
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35

Digits with while

C
#include <stdio.h>
int main(void) {
int n = 40213, digits = 0, sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
digits++;
}
printf("%d digits, digit sum %d\n", digits, sum);
return 0;
}
Output
5 digits, digit sum 10

More examples

Sentinel input and validation

C
#include <stdio.h>
int main(void) {
int value, count = 0;
long total = 0;
printf("Enter marks, -1 to stop:\n");
while (scanf("%d", &value) == 1 && value != -1) {
if (value < 0 || value > 100) {
printf("ignored %d\n", value);
continue;
}
total += value;
count++;
}
if (count > 0)
printf("%d marks, average %.2f\n", count, (double)total / count);
else
printf("no marks entered\n");
return 0;
}
Input
72 88 150 64 -1
Output
Enter marks, -1 to stop:
ignored 150
3 marks, average 74.67

Step-by-step explanation

  • The while condition both reads a value and stops if reading fails or the sentinel -1 arrives.
  • Out-of-range marks such as 150 are reported and skipped with continue.
  • Valid marks are added to total (a long to avoid overflow) and counted.
  • After the loop, the program guards against dividing by zero when nothing was entered.
  • (72 + 88 + 64) / 3 = 74.666…, printed as 74.67.

Expected output

Running “Sentinel input and validation” with the sample input shown prints exactly:

TextInput
72 88 150 64 -1
TextOutput
Enter marks, -1 to stop:
ignored 150
3 marks, average 74.67

Practical applications

  • Servers run an event loop that waits for and handles requests forever.
  • Embedded devices run a for (;;) super-loop that reads sensors and updates outputs.
  • Data processing reads records until end of file, a sentinel-controlled loop.

Best practices

  • Prefer for when the number of iterations is known; while when it isn't; do-while for at-least-once.
  • Use half-open ranges 0 <= i < n for arrays.
  • Trace small loops by hand in a table of variable values.

Common mistakes

Forgetting the update

Avoid

int i = 0;
while (i < 5) {
printf("%d\n", i);
}

Prefer

int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}

i never changes, so the condition stays true forever.

Off-by-one with <=

Avoid

int a[5];
for (int i = 0; i <= 5; i++) a[i] = 0;

Prefer

int a[5];
for (int i = 0; i < 5; i++) a[i] = 0;

Valid indexes are 0–4. i <= 5 writes past the end of the array — undefined behaviour.

Semicolon after for

Avoid

for (int i = 0; i < 3; i++);
printf("hi\n");

Prefer

for (int i = 0; i < 3; i++)
printf("hi\n");

The semicolon is the empty loop body; printf runs once after the loop. (With int i declared in the for, the misplaced version may not even compile if the body uses i.)

Important notes

  • A loop whose condition can never become false is not automatically an error; the compiler may even assume a side-effect-free infinite loop terminates in some cases. Always make progress toward the exit.
  • Using a float as a loop counter accumulates rounding error; count with integers.

Key takeaways

  • while and for test first; do-while tests last and runs at least once.
  • Every loop needs initialisation, a condition and an update.
  • Use i < n from 0 for n iterations over an array.

Try it yourself

  1. 1
    Print the sum of the series 1 + 1/2 + 1/3 + … + 1/n for n read from input, to 4 decimal places.
  2. 2
    Write a do-while menu that keeps showing options until the user enters 0.
  3. 3
    Reverse the digits of an integer (e.g. 1234 → 4321) using a while loop.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerHow many times does this loop print "hi"?
  • BeginnerWhat is printed?
  • BeginnerThis loop never ends. Why? `int i = 0; while (i < 10) { printf("%d\n", i); }`
Practise this topic