Unlike for
and while
loops, do-while
loops check the truth of the condition at the end of the loop, which means the do
block will execute once, and then check the condition of the while
at the bottom of the block. Meaning that a do-while
loop will always run at least once.
For example this do-while
loop will get numbers from user, until the sum of these values is greater than or equal to 50
:
int num, sum;
num = sum = 0;
do
{
scanf("%d", &num);
sum += num;
} while (sum < 50);
do-while
loops are relatively rare in most programming styles.