CodeBlanks Logo Icon CodeBlanks

The do-while loop

Learn loops that run at least once with do-while.

The do-while loop

The do-while loop runs the body at least once, then checks the condition. This is useful for cases like menus where the question must be asked at least once.

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

Here even with n=0 the body runs once. Output: 0 1 2. Unlike while, the condition is checked at the end; the semicolon is mandatory.

Semicolon in do-while

In do-while, the semicolon at the end of the while line is mandatory. Forgetting it is a common compile error.

int choice;
do {
    printf("Continue? 1/0: ");
    scanf("%d", &choice);
} while (choice == 1);  // semicolon required

This example loops as long as the user enters 1. When they enter 0 it ends. The return value of scanf is an int; not used here, but you learned the logic.

Practice 0 to 2 with do-while

Write a C program. Declare int n = 0;. Write a do { ... } while (n < 3); loop; in the body include printf("%d\n", n); and n++;. Put #include <stdio.h> at the top.

Starter code

main.c
#include <stdio.h>

int main(void) {
    // Declare n, print with do-while
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int n = 0;
    do {
        printf("%d\n", n);
        n++;
    } while (n < 3);
    return 0;
}

Expected output

0
1
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the loop features

Term Meaning
for Counted
while Condition first
do-while Condition last
at least once do-while

2 How many times does do-while run?

main.c
int n = 10;
do {
    printf("%d", n);
} while (n < 5);
  • At least once Correct answer
  • Never
  • 5 times
  • Infinite

Explanation: Even with a false condition the body runs at least once.

3 Complete the do-while

Question
do {
    n++;
} ____ (n < 5);
Answer
do {
    n++;
} while (n < 5);

Explanation: do-while checks the condition with while after the body.

All lessons in Beginner