C Do While Loop

The do while loop is like the while loop, but the condition is checked at the end. So the body always runs at least one time.

Syntax

do {
    // code to repeat
} while (condition);

Do not forget the semicolon after while (condition).

Example

#include <stdio.h>

int main(void) {
    int i = 1;

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

Output:

Output of the above program is

1
2
3

Difference from while

#include <stdio.h>

int main(void) {
    int x = 10;

    while (x < 5) {
        printf("while runs\n");
    }
    do {
        printf("do while runs once\n");
    } while (x < 5);
    return 0;
}

Output:

Output of the above program is

do while runs once

The condition is false from the start, but the do while body still ran one time.

Real use: ask until the input is valid

#include <stdio.h>

int main(void) {
    int n;

    do {
        printf("Enter a positive number: ");
        scanf("%d", &n);
    } while (n <= 0);

    printf("You entered %d\n", n);
    return 0;
}

Output:

Output of the above program is

Enter a positive number: -4
Enter a positive number: 0
Enter a positive number: 8
You entered 8

Note: Menu programs are a good use of do while. You show the menu once, and repeat it until the user chooses Exit.

Next: C For Loop.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.