0
0
Cprogramming~5 mins

Do–while loop in C

Choose your learning style9 modes available
Introduction

A do-while loop lets you run a block of code at least once, then repeat it while a condition is true.

When you want to ask a user for input and repeat until they enter a valid answer.
When you need to run a menu at least once and keep showing it until the user chooses to exit.
When you want to perform an action first, then check if it should continue.
When you want to read data repeatedly until a stop condition is met, but must read at least once.
Syntax
C
do {
    // code to run
} while (condition);

The code inside do { } runs first, then the condition is checked.

If the condition is true, the loop repeats. If false, it stops.

Examples
This prints numbers 1 to 3, increasing i each time.
C
int i = 1;
do {
    printf("%d\n", i);
    i++;
} while (i <= 3);
This asks the user if they want to continue, repeating if they type 'y'.
C
char answer;
do {
    printf("Continue? (y/n): ");
    scanf(" %c", &answer);
} while (answer == 'y');
Sample Program

This program prints "Count is" followed by numbers 1 to 5 using a do-while loop.

C
#include <stdio.h>

int main() {
    int count = 1;
    do {
        printf("Count is %d\n", count);
        count++;
    } while (count <= 5);
    return 0;
}
OutputSuccess
Important Notes

The do-while loop always runs the code block at least once, even if the condition is false at the start.

Remember the semicolon ; after the while(condition) line is required.

Use do-while when you want the loop body to run before checking the condition.

Summary

A do-while loop runs code first, then checks a condition to repeat.

It is useful when the code must run at least once.

Syntax requires a semicolon after the while condition.