The for loop enables code to execute repeatedly until a boolean expression evaluates to false.
Syntax:
for (initialization; expression; modification)
{
statement(s);
}
The keyword for begins the loop. The parentheses contain an initialization, an expression, and a modification. The initialization is used to initialize a variable with certain value. Initialization is followed by a semicolon (;), followed by an expression. This is followed by another semicolon and then modification. Modification is basically an increment or decrement statement. When a for loop is encountered, initialization is first executed, and then the expression. If it evaluates to true, the statement or block following the for statement is executed. When the end of the body is reached, modification is executed. The expression is then evaluated again. If it is false, execution continues with the statement following the for loop. If it is true, the body of the for loop is executed again.
/* Print the sequence no from 20 to 30 */
class ForSequence
{
public static void main(String args[] )
{
int i;
for(i=20;i<=30;i++)
{
System.out.print(i + ” “);
}
}
}
The variable i is assigned a value 20. Since 20 <=30, the body of the for loop is executed, displaying the value of i I.e. 20 on the screen. Then i++ is executed, which increases value of i to 21. This value of 21 is compared with 30. Since 21 <=30, again the body of for loop will be executed replacing 21 on the screen. Again, the process is repeated until i becomes >30. The initialization of variable i of for loop shown above can be done before the beginning of for loop:
i=20;
for(;i<=30;i++)
{
System.out.print(i + ” “);
}
We can even write the increment statement of the loop as shown:
i=20;
for(;i<=30;)
{
System.out.print(i + ” “);
i++;
}
Even the logical expression can be avoided written at the top and can be included in the body of the loop as shown:
i=20;
for(;;)
{
If( i<=30) break;
System.out.print(i + ” “);
i++;
}
Above for loop i.e. for(;;) is considered as infinite for loop. break statement is used for coming out of the loop