Loops in C: for, while and do-while with worked examples

Learn how C loops initialise, test, execute and update. Trace complete programs, diagnose common bugs and practise choosing the right loop.

Prashant Jain

KnowledgeGate AI educator

Updated 17 Jul 20265 min read

You may know how to make C execute a statement once, but repeating it safely requires a clear model. This tutorial gives you that model, runnable programs for all three loop forms, common-error diagnosis and short exercises you can trace. Every C loop needs either a stopping condition or an intentional infinite-loop design.

Loops in C: the four parts of controlled repetition

A loop repeatedly executes code while a condition permits it. Read any loop in this order: initialise the state, test the condition, run the body, and update the state. A for or while loop tests before entering the body, while a do-while loop tests after one execution.

int i = 1;
while (i <= 3) {
    printf("%d ", i);
    i++;
}

The first test sees i=1, so the loop prints 1 and updates i to 2. The next two passes print 2 and 3. The update after the third pass makes i=4; now i <= 3 is false. The exact output is 1 2 3. If you omit i++, i remains 1 and the loop does not terminate.

The Coding & DSA Courses for Placements page places this skill in a wider programming path, but the model above is enough to trace the examples here.

The for loop in C: count when the range is known

The grammar is for (initialisation; condition; update) { body }. Initialisation runs once, the condition is tested before every pass, and the update runs after each completed pass. These fields directly represent the initialise, test and update parts of the model; the block supplies the body.

#include <stdio.h>

int main(void) {
    int i, sum = 0;
    for (i = 2; i <= 10; i += 2) {
        sum += i;
    }
    printf("Sum = %d\n", sum);
    return 0;
}

i before body

sum before

sum after

2

0

2

4

2

6

6

6

12

8

12

20

10

20

30

After the fifth update, i=12, so 12 <= 10 is false. The program prints Sum = 30.

Flowchart of the even-sum for loop, testing i <= 10 and ending at Sum = 30.

The while loop in C: repeat until changing data says stop

A while loop is usually clearer when you cannot know the number of passes in advance. Its condition describes the state in which repetition should continue, and its body must move that state towards false.

#include <stdio.h>

int main(void) {
    int n = 4827, sum = 0, digit;

    while (n > 0) {
        digit = n % 10;
        sum += digit;
        n /= 10;
    }

    printf("Digit sum = %d\n", sum);
    return 0;
}

n

digit

sum after addition

next n

4827

7

7

482

482

2

9

48

48

8

17

4

4

4

21

0

For positive integers, integer division by 10 removes the final digit. Once n=0, n > 0 is false, so the exact output is Digit sum = 21.

The do-while loop in C: run once before checking

The exact form is do { body } while (condition);. Notice the required semicolon after the condition. This loop is exit-controlled, unlike the entry-controlled while, because its body runs before the first test.

#include <stdio.h>

int main(void) {
    int choice;

    do {
        printf("1. Continue\n");
        printf("2. Exit\n");
        scanf("%d", &choice);
    } while (choice != 2);

    return 0;
}

With the fixed input stream 1 and then 2, the menu appears twice. The first check sees choice != 2 as true; the second sees it as false and exits. If the first input is 2, the menu still appears exactly once. Use do-while only when that first execution is part of the requirement, such as showing a menu before accepting an exit choice.

Nested loops in C: trace rows outside and columns inside

For every single outer-loop pass, the inner loop completes all its passes. This program runs rows 1 to 3 outside and columns 1 to 4 inside.

#include <stdio.h>

int main(void) {
    int row, col;

    for (row = 1; row <= 3; row++) {
        for (col = 1; col <= 4; col++) {
            printf("%d ", row * col);
        }
        printf("\n");
    }

    return 0;
}
1 2 3 4
2 4 6 8
3 6 9 12

The inner body executes 3 x 4 = 12 times. That concrete count is the bridge to Time Complexity & Asymptotic Notation: Big-O, where loop growth becomes the main question.

Grid of row times col values for the 3 by 4 nested loops, with arrows finishing each row's columns first.

Loop control and common C loop errors

continue skips the rest of the current pass, while break exits the nearest loop completely.

for (i = 1; i <= 8; i++) {
    if (i == 3) continue;
    if (i == 7) break;
    printf("%d ", i);
}

The output is 1 2 4 5 6. At 3, continue still leads to the for update. At 7, break exits before printing or updating again.

Trap and cause

Observed result

Correction

Using i < 5 when 5 must be included

Starting at 1 prints only 1 through 4

Use i <= 5 when the upper boundary is inclusive

Omitting i++

The tested value never changes, causing an infinite loop when the condition stays true

Update the controlling state in the body

Writing while (i <= 5);

The semicolon forms an empty loop, so the intended body is not controlled

Remove the stray semicolon and keep the update inside the body

Writing while (i = 5)

The expression assigns 5, a nonzero value, so it remains true

Use i == 5 when comparison is intended

Output puzzles should also use sequenced, well-defined operations. Do not try to reason from undefined expressions such as i = i++.

How loops in C are tested, plus three exercises

Assessments commonly ask you to trace output, count iterations, repair a boundary or update bug, choose a loop form, or count a nested body. Sorting Algorithms: Complexity and Comparison is a useful next application because sorting relies on repeated passes.

Try these on paper before reading the sketches:

  1. Sum the digits of 9054.

  2. Print values from 10 down to 2 in steps of 2.

  3. Use nested loops with row counts 1, 2, 3 and 4, printing one * for each inner pass.

The first answer is 18: take % 10, add the digit, and apply /= 10 until n becomes 0. The second uses for (i = 10; i >= 2; i -= 2) and prints 10 8 6 4 2. The third uses outer row=1..4 and inner col=1..row:

*
**
***
****

It prints 1+2+3+4 = 10 stars. Hand-trace each control variable before compiling.

Loops in C: the short version and next step

Use for for a clear counter range, while for condition-led repetition with an unknown pass count, and do-while when the body must run at least once. Before trusting any loop, identify which variable changes and why the condition will eventually become false.

The C Programming Course is a structured next step if you want the full C sequence. For one final check, retype the even-sum program, change the upper bound from 10 to 14, predict 56, then compile and confirm.