do while loop in C programming

do while loop in C Using do while loop we will execute the statement first and then check the condition. Here the C statements can be executed once even if condition is not satisfied.

This is the basic difference between while loop and do while loop.

Usually the condition changes during the execution of the statement so next time while checking the condition ( after executing the statement ) we may get a False output to terminate the loop.

Let us start with a basic program to print number 1 to 5.
#include<stdio.h>
#include<string.h>
int main()
{
 int i=1;

 do{
 printf("%d \n",i);
 i++; // increment of value by 1 
 } while(i <=5);

 return 0;
}
The above code will give this output.
1
2
3
4
5

Executing the code even if condition is False

Check this code, here the condition is checked after executing the statement once.
#include<stdio.h>
#include<string.h>
int main()
{
 int i=50;
 
 do{
 printf("I am executed but i value = %d ",i);
 } while(i >=100);
 
return 0;
}
Output is here ( executed once before the condition is checked )
I am executed but i value =50

Indefinite loop

If we don’t increment the value of I inside the do while loop, then the condition will be true in all cases and the loop will never end. This will continuously execute the code inside the loop without any end.
Avoid such loops as they never stops.
#include<stdio.h>
#include<string.h>
int main()
{
 int i=1;
 
 do{
 printf("%d \n",i);
 } while(i <=5);

 return 0;
}
Sometime even the increment conditions became in such a way that the condition never became false and it became indefinite loop.
#include<stdio.h>
#include<string.h>
int main()
{
 int i=1;
 
 do{
 printf("%d \n",i);
 i=i-1;
 } while(i <=5);

 return 0;
}

Break statement

We can terminate the execution of loop in between and came out of the loop by using break statement.
Here we have used one if condition checking and once the value of i became more than 3 then break; statement gets executed and the loop is terminated.
#include<stdio.h>
#include<string.h>
int main()
{
 int i=1;
 
 do{
 printf("%d \n",i);
 i=i+1;
 if(i>3)
    break;
 } while(i <=5);

 return 0;
}
Output is here
1
2
3
We will increment the variable by more steps.
i++; // increment i value by 1 
i--; // decrement i value by 1
i += 5; // increment i value by 5 
i -= 5; // Decrement i value by 5 

Example with decrement of value by 10

#include<stdio.h>
#include<string.h>
int main()
{
 int i=50;
 
 do{
 printf("%d \n",i);
 i-=10;
} while(i >=0);

return 0;
}
Output is here
50
40
30
20
10
0
Your Rating




Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer