Sunday, October 04, 2015

For Loop

For Loop

For loop is a powerful and versatile construct. Beginning with JDK 5, there are two forms of the for loop.


  • The first is the traditional form that has been in use since the original version of Java.
  • The second is the new “for-each” form.


for(initialization; condition; iteration)
{
      // body
}

If only one statement is being repeated, there is no need for the curly braces.

When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop.It is important to understand that the initialization expression is only executed once.

Condition is evaluated, This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates.

Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false.

Here is a version of the “tick” program that uses a for loop:

// Demonstrate the for loop.
class WLFor
{
public static void main(String args[])
{
int n=5;
for(n; n>0; n--)
{
System.out.println("tick " + n);
}
}
}

Using the Comma

Java allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma.

Using the comma, the preceding for loop can be more efficiently coded as shown here:

// For Loop Using the comma.
class WLForComma
{
public static void main(String args[])
{
int a, b;
for(a=1, b=4; a<b; a++, b--)
{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

In this example, the initialization portion sets the values of both a and b. The two comma-separated statements in the iteration portion are executed each time the loop repeats.

The program generates the following output:

javac WLForComma.java
java WLForComma

a = 1
b = 4
a = 2
b = 3

No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)