News:

MyKidsDiary.in :: Capture your kids magical moment and create your Online Private Diary for your kids

Main Menu

The for Statement

Started by VelMurugan, Nov 21, 2008, 10:26 PM

Previous topic - Next topic

VelMurugan

The for Statement

In the world of Java programming, the for loop has made the life much more easier. It is used to execute a block of code continuously to accomplish a particular condition. For statement consists of tree parts i.e. initialization, condition, and iteration.

initialization : It is an expression that sets the value of the loop control variable. It executes only once.
condition :  This must be a boolean expression. It tests the loop control variable against a target value and hence works as a loop terminator.
iteration : It is an expression that increments or decrements the loop control variable.

Here is the form of the for loop:

Quotefor(initialization; condition; iteration){
//body of the loop
}

For example, a sample for loop may appear as follows:

int i;
for (i=0; i<10; i++)
System.out.println("i = " +i);


In the above example, we have initialized the for loop by assigning the '0' value to i. The test expression, i < 100, indicates that the loop should continue as long as i is less than 100. Finally, the increment statement increments the value of i by one. The statement following the for loop will be executed as long as the test expression is true as follows:

System.out.println("i = " + i);

Well, we can add more things inside a loop. To do so we can use curly braces to indicate the scope of the for loop. Like,

int i;
for (i=0; i<10; i++) {
MyMethod(i);
System.out.println("i = " + i);
}


There is a simpler way to declare and initialize the variable used in the loop. For example, in the following code, the variable i is declared directly within the for loop:

for (int i=0; i<100; i++)
System.out.println("i = " +i);

Lets see a simple example which will help you to understand for loop very easily. In this example we will print 'Hello World' ten times using for loop.

class printDemo{
  public static void main(String[] args){
    for (int i = 0; i<10; i++){
      System.out.println("Hello World!");
    }
  }
}


Here is the output:

C:\javac>javac printDemo.java

C:\javac>java printDemo
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!


After learning how to use a for loop, I would like to introduce another form of for loop to be used for iteration through collection and arrays. This form has enhanced the working of for loop. This is the more compact way to use a for loop.

Here we will take an array of 10 numbers.

int[] numbers = {1,2,3,4,5,6,7,8,9,10};