Friday 20 February 2015

Iteration statements in Java

       Iteration statements are the statements which is used to specify the logic of a loop. i.e a same set of statements executes 0 or more times until termination condition is met. 

Java supports 3 iteration statements i.e for , while, and do-while . 

while Loop:
It is the fundamental loop statements in Java and it is the entry controlled loop statement.The block of statements will be executed until the condition is met. Once the conditions becomes false it will come out from the loop. 

Syntax:


The condition can be any Boolean expression. If you are using any counter for condition then you have to increment the counter for each iteration.

Example:


Output:









do-while Loop:
        If you use the while loop once the condition is false it will not execute the while block. If the condition is false at first attempt the while block will not execute at all. You may come across the scenario as the while block should execute at least once even though the condition becomes false .In such scenario you need to use do-while Loop. Make a note that in do-while Loop while statement should end with semicolon(;).

Syntax:


Output:







In the example l_count is initially 6 which is >5 and it is printed inside the while loop.

for Loop:
The for statement provides a compact way to iterate over a range of values. There are two types of for loop in java i.e Simple for Loop and for-each Loop

Simple for Loop:

Syntax:


No need to declare ,initialize and increment the counter outside the for loop as do that in while and do-while loop

Example :


Output:

As for-each Loop is advance concept we will discuss later with more examples.







No comments: