Translate

Saturday 16 August 2014

Iteration of statements (Looping)

Repetitive execution of a statement is known as iteration or loop.

While loop:-
while(boolean expression)
   statement;

This loop runs till the condition is true. Compiler first checks the condition in while loop, if its true then statements under while loop are run then condition is checked again and iteration occurs.
In case of while loop initially condition is checked then loop runs.
e.g.
int a=5;
while(a<10)
{
    System.out.println("Loop");
    a++;
}
here Loop will be printed 5 times.


Do while loop:-
do
    statement;
while(boolean expression);

Do while also runs as a while loop statement. But here statement is executed first then condition is checked. Which means statement is executed once, whether condition is true or false.
int a=5;
do
{
    System.out.println("Loop");
    a++;
}while(a<5);
Here condition is false still Loop will be printed once.


For loop:-
for(initialization; condition; action part)
     statement;

Here compiler first goes to initialization part then checks the condition then after executing statement under for loop it goes to action part then checks the condition part and continues doing so till condition is false. Here initialization is done only once when loop starts then only condition and action part is run.
for(int i=0; i<5; i++)
    System.out.println("Loop");
Here first i will be assigned to 0 and then it starts printing Loop for 5 times.


If loop never ends then it is known as infinite loop.

No comments:

Post a Comment

Total Pageviews