for loop is three loop statement in java. It is used to repeat a statement or block of statements for specified number of times.
Syntax of For Loop Statement
for(initialization; test; increment) statement;
initialization section gives an initial value to the variable that controls the loop. It is also called a loop-control variable.It is executed only once , before the loop begins.
test section of the loop tests the loop-control variable against a target value. If it evaluates to true, the loop repeats. If it is false, the loop stops. test is performed at the start of the loop each time the loop is repeated.
increment section is executed at the bottom of the loop. It is executed after the block of statement has been executed. It's main purpose is to increase or decrease the loop-control variable.
Note that for loop places no limits on the types of expressions that occur inside it. All three sections in the for loop are optional. The increment section is technically just an expression that is evaluated each time the loop iterates. It does not have to increment or decrement a variable.
Examples of For Loop Statement
Example 1 : Program to print numbers from 1 to 10
class ForDemo
{
public static void main(String args[])
{
System.out.print("Numbers : ");
for(int i=1; i <= 10; i++)
{
System.out.print(i + " ");
}
}
}
Output
Numbers : 1 2 3 4 5 6 7 8 9 10
Example 2 : Program to print tables
class TablesUsngForLoop
{
public static void main(String args[])
{
System.out.println("Tables");
for(int i=1; i <= 2; i++) // change to 2 to 10 or 20 as many tables user want
{
for(int j=1; j <= 10; j++)
{
System.out.println(i + " * " + j + " = " + (i*j));
}
System.out.println("");
System.out.println("");
}
}
}
Output
Tables
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Example 3 : Program of for loop where initialization section is empty
class ForLoopDemo
{
public static void main(String args[])
{
int i = Integer.parseInt(args[0]);
for(; i > 0 ; i--)
System.out.println(i + " ");
}
}
// call from command line
java ForLoopDemo 5
Output
5
4
3
2
1
Example 4 : Program that illustrates infinite for loop example
class InfiniteForLoopDemo
{
public static void main(String args[])
{
for( ; ; )
System.out.println("In Loop");
}
}