Answer: Difference between do while and while loop in C programming: do…while loop guaranteed to execute at least one time whereas while loop does not.
All statements within do…while loop get executed first and then while condition is checked. Hence, it executes at least one time.
In the below example, the string “interviewsansar.com” will be printed once using do…while loop whereas using the while loop, it will not print.
int main(){
int i = 1;
//Do...While loop
//control will enter in loop, print "interview sansar" and then
//check the while condition that is false.
do{
printf("interviewsansar.com");
}while(i != 1);
//------------------------------
//while loop
//control will not enter in while loop as condition is
//false. So, will print nothing.
while(i != 1){
printf("interviewsansar.com");
}
return 0;
}
When to Use Do…While Loop?
We use do…while loop where we need to execute a piece of code once and on the basis of that execution we decide whether to execute that code repeatedly or not. In this case while or for loop does not work.