Beginner · C PROGRAMMING

While and do while

What you will learn

Use condition-controlled repetition.

Understand the concept

while checks before the body and can run zero times. do while checks afterward and runs at least once. Update a value involved in the condition so that the loop can finish.

Read the example

The complete program appears below. Read it first, predict the output, then run it.

Expected output

3
2
1
Finished

Practise

Start remaining at zero. Explain why only the do-while body prints.

Common mistake

Forgetting the decrement can create an infinite loop. The do-while statement requires a final semicolon.

Lesson discussion

Log in to participate.

#include <stdio.h>

int main(void) {
    int remaining = 3;
    while (remaining > 0) {
        printf("%d\n", remaining);
        --remaining;
    }
    do {
        puts("Finished");
    } while (remaining > 0);
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
No input required.
Expected output for the original program
3
2
1
Finished
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA