Loops

1. while loop a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement. Syntax :- [c]while(condition) { statements; }[/c]

Example :- Lets print 1 to 10 numbers using while loop

[c]void main()
{
int i;
i=1;
while(i<=10)
{
printf("\n%d",i);
i=i+1;
}
getch();
}[/c]

2. do while loop

The do while construct consists of a block of code and a condition. First, the code within the block is executed, and then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false.

Syntax :-

[c]do
{
statements;
}while(condition);[/c]

Example :- Lets print 10 to 11 numbers using do while loop

[c]void main()
{
int i = 10;
do
{
printf("\n %d", i );
i = i -1;
}while ( i < 0 );
getch();
}[/c]

3. for loop

for loop is just like the while loop but it does 3 things in a single line.
1. Sets a loop counter to an initial value.
2. Tests the loop counter to determine whether its value has
reached the number of repetitions desired.
3. Increases the value of loop counter each time the program segment within the loop has been executed

Syntax :-

[c]for(initialization;check condition;increment/decrement)
{
statements;
}[/c]

Example :- Lets print Hello world 10 times using for loop

[c]void main()
{
int i;
for (i = 0; i < 10; i++)
{
printf ("\nHello world");
}
getch();
}[/c]