Ticker

6/recent/ticker-posts

C Language (Difference Between While and Do While Loop)

DIFFERENCE BETWEEN WHILE AND DO WHILE LOOP





WHILE LOOP
In while loop, the condition is check/tested first, and then the body part code executed (if the condition turns out to be true)  

A while loop is never execute, if its test condition would be false.

Let's understand it, by the following while loop example.
int a=1;
while(a >10)
{
printf(“\n%d”,a);
a=a+1;
}

----------------------------
         OUTPUT 
----------------------------
Nothing will print


Program Explanation: The above program will print nothing, because the While loop never execute when its test condition would be false.


DO-WHILE LOOP
In the do-while loop, statements (body part instructions) executes first, then it will check its test condition and if the condition turns out to be true then the statements are executed again.


A do while loop runs at least once even though the condition given is false.


Let's understand it, by the following do-while loop example.
int a=1;
do
{
printf(“\n%d”,a);
a=a+1;
}

while(a >10);

----------------------------
         OUTPUT 
----------------------------
1

Programmer Explanation: The above program will print 1 number only because the do-while loop execute at-least once even it test condition would be false.

In while loop the condition is tested first and then the statements are executed if the condition turns out to be true.













HOME

Post a Comment

0 Comments