#include<stdio.h>
void main(){
int x;
do{
printf("value of x: %d\n", x);
x=x+1;
}while( x < 10 );
}
In the previous 2 posts we learned about for and while loop respectively, Now one question would be there in your mind that if we have for and while loops why do we even need do while loop ?
By answering that question I would like to explain you the working of do while loop. So do while loop can be used in situations where for and while loop are useless, like when you ALWAYS want to execute the code inside the loop at least once. This cannot be achieved by for and while loops as if the condition is false for 1st iteration itself then your code inside the loop will not executed but this doesn’t happen in do while because here we don’t check the condition in beginning, instead it all begins with a keyword do then in curly brackets we have our code and then the while keyword ahead to it we mention our condition in round bracket.
So because of this structure do while loop can execute the code inside the loop at least one time even if the condition is false.