C

C – Example Of A Do While Loop In C Programming

In the previous tutorial, we learned how to use the while loop in C. A do while loop is similar to a while loop, with the exception that it executes the statements within the do-while body before checking the condition. In the while loop, on the other hand, the condition is checked first, and then the statements in the while loop are executed. So, if a condition is false in the first place, the do while loop will run once, but the while loop will not run at all.

C – loop do..while

Do-while loop syntax

do
{
    //Statements 

}while(condition test);

Do while loop example

#include <stdio.h>
int main()
{
	int j=0;
	do
	{
		printf("Value of variable j is: %d\n", j);
		j++;
	}while (j<=3);
	return 0;
}

Output:

Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3

In C, while vs. do…while loop

While looping:

#include <stdio.h>
int main()
{
    int i=0;
    while(i==1)
    {
	printf("while vs do-while");
    }
    printf("Out of loop");
}

Output:

Out of loop

The same example can be used with a do-while loop.

#include <stdio.h>
int main()
{
   int i=0;
   do
   {
	printf("while vs do-while\n");
   }while(i==1);
   printf("Out of loop");
}

Output:

while vs do-while
Out of loop

Explanation: As I mentioned at the beginning of this guide, do-while runs at least once even if the condition is false because the condition is evaluated after the body of the loop is executed.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button