Monday, June 27, 2011

How Use Loops in C-'DO WHILE' Loops

0 comments



'DO WHILE' loops are useful for things that want to loop at least once.The syntax is:
do
{
Code to execute
}while(condition);

Example:
#include<stdio.h>
int main()
{
int x;
x=0;
do
{/*"Hello World!" is printed at least one time even though the condition is false*/
printf("Hello World!");
}
while(x!=0);
getchar();
}
Notice that the condition is tested at the end of the block instead of beginning ,so the block will be executed at least once.If the condition is true,we jump back to the beginning of the block and execute it again.A DO WHILE loop is almost  the same as WHILE loop except that the loop body is guaranteed to execute at least once.A WHILE loop says"Loop while the condition is true,and execute this block of code".A DO WHILE loop says"execute this block of code,and then continue to loop while the condition is true". Notice that this loop will execute once,because it automatically execute before checking the condition.


<<Prev Home Next>>
Continue reading →