Thursday, November 14, 2013

Looping Statements in Java

In a situation when we need to execute a number of statements in Java program to be executed several number of times, and this type of operation is referred to as a loop. Java has three looping statements to be used in Java programming the looping statements are given below:
  • while Loop
  • do...while Loop
  • for Loop
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
while(Boolean_expression)
{
Statements
}

Example:
public class Test
{
public static void main(String args[])
{
int x = 10;
while( x < 20 )
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

The do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:
do
{
Statements
}
while(Boolean_expression);

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example:
public class Test {
public static void main(String args[])
{
int x = 10;
do
{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
while( x < 20 );
}
}

No comments:

Post a Comment