while and do while are both loop statements in C language, and their main difference lies in the order in which the loop body is executed.

The while loop first checks the loop condition, and only executes the loop body when the condition is true. Therefore, if the condition is false from the beginning, the loop body will never execute. And if the condition is always true, the loop will keep executing forever.

while: You owe me money, I'm walking on the road, there's someone ahead; I first take a clear look at whether this person is you, if not, I won't hit.

do while: You owe me money, I'm walking on the road, there's someone ahead; I don't care whether this person is you, I'll hit first, then talk.

Below is an example program of a while loop:

Example

#include <stdio.h>

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

The output result is:

i = 0
i = 1
i = 2
i = 3
i = 4

The main difference between the do while loop and the while loop is the order in which they execute the loop body. The do while loop first executes the loop body, then checks the loop condition. Therefore, even if the condition is false from the beginning, the loop body will be executed at least once.

Below is an example program of a do while loop:

Example

#include <stdio.h>

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

The output result is:

i = 0
i = 1
i = 2
i = 3
i = 4

It can be seen that even if the initial value of i is 0, the do while loop still executes the loop body 5 times, because it executes the loop body first, and then checks the loop condition.

In general, the while loop is suitable for checking the condition before the loop, while the do while loop is suitable for executing the loop body at least once, regardless of whether the condition is true.

Reference articles: