Saturday, December 13, 2008

Loops

While loop-
The while loop only has a condition in it. It doesn’t have the initialization in it and also it dosen’t have incement or decrement statement. The increment or decrement statement can be given in the body of the loop. Initialization of variable which is used in the loop to give condition is necessary.
Eg.while(x<5){ }
Eg.
Void main()
{
Int x=0;
While(x<5)
{
Printf(“Hello”);
X++;
}
Getch();
}
In this program x is initialized to zero. Then the command enters the while loop. Then it checks the condition whether x is less than 5 or not. Then it executes the statement in the loop if the condition is satisfied or else it exits. Hence in this loop the statement in the loop executes only if the condition is satisfied. In this program the condition is satisfied five times. The word hello will be displayed five times. No semicolon is given after the while statement.
Do…while loop-
In the do…while loop the do statement is written at the beginning of the loop and the while statement is given at the end of the loop. Only the condition is given in the while statement as the while statement given above.the initialization of variable is given at the beginning and increment or decrement in the body of the loop. This loop executes the statement once and then checks the condition and then decides whether to run the loop or exit. This is the advantage of this loop that it executes the statement in it atleast once.
Eg do
{
Statement.
}while(condition );
Eg.
Void main()
{
Int x=0;
Do
{
Printf(“hello”);
X++;
}while(x<5);
Getch();
}
In this program first the print statement is executed. Then x is incremented and then the condition si checked whether x is less then five or not. If the condition satisfies then the loop is executed again else it exits.

No comments:

Watch tv!