Iteration Statement in JAVA

When you want a part of the code to execute repeatedly and terminate when some condition satisfies, then iteration statements, generally known as loops are used. JAVA’s iteration statements are for, while, do-while.

while 

while loop is fundamental looping statement. It repeats the statements or block until the controlling expression is true. It is an entry controlled loop (when control enters the loop, immediately the condition will be checked).

Syntax:

while( condition ){

while( condition ){

{
// body of loop which will be repeated
}

Here, the condition can be any boolean expression. The body of the loop will be executed as long as the condition is true. When

When the condition becomes false, the control will pass to the next line of code, following the loop.

Example:

int n=5;

int n=5;
while( n>0 )
{
System.out.println(“loop ” + n );
n=n-1;
}
// rest of code

Output:             loop 5
loop 4
loop 3
loop 2
loop 1

do-while

As you now that in while loop the condition will be executed until true but in the case of the do-while loop, the condition will be executed once even if the condition is false. So, we can say that do-while checks the condition at the end of the part’s execution. Therefore, we will call it exit controlled loop.

Syntax:

do{

do{
// body of loop
}while( condition )

Here, you can see in the syntax that when control enters the loop, the one-time body of the loop will get executed because the condition is checked at the last.

Example:               int n=5;

int n=5;
do{
System.out.println(“loop ” + n );
n=n-1;
}while( n>0 )
// rest of code

Output:             loop 5
loop 4
loop 3
loop 2
loop 1

for

The for statement provides a compact way to iterate over a range of values.

Syntax:

for( Initialization; condition; iteration ){
//body of loop
}

Here, these three parameter are important

  1. initialization: expression initializes the loop. it gets executed once as the loop begins.
  2. When the condition expression evaluates to false, the loop terminates.
  3. iteration parameter is increment or decrement.

Example:

for( int n=0; n<5; n=n+1){
System.out.println(“loop ” + n );
}

Output:             loop 0
loop 1
loop 2
loop 3
loop 4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: