Saturday, April 23, 2011

Java: For Loop

The “for loop” is a type of looping construct. This construct provides a compact way to iterate over a range of values. This loop works as “while loop construct” but it provides the initialization, condition and termination.

The general form (syntax) of the “for statement” can be expressed as follows:

for (initialization; termination; increment) {

statements;

//code_block_to_be_executed

}

The given example illustrates the syntax “for loop” for developing an application or a program.

initialization: The expression initialize the loop. It allows the variables to be initialized.

//it can be such as

int i = 0;

int j = 1;

termination (condition): This term of the for loop allows to check the certain condition. If the condition is true, the code block will be executed or the code block will be ignored.

//it can be such as

i < 10;

j <= 11;

increment: This term of the loop allows to increase the given variable. As programmers you can increment the value one by one, two by two or how you want.

//it can be such as

i++;

j++;

Generally the form of the “for loop” is illustrated above. Now I will give a code block and the output of the code. To be an example for the beginners it will be useful.

Code Block:

class ForLoop {

public static void main(String [] args) {

for (int i = 1; i< 4; i++) {

System.out.println(“Value of i is: ”, +i);

}

}

}

Output of the given code block will be:

Value of i is : 1

Value of i is : 2

Value of i is : 3

I hope it will be useful for programmers, beginners.