for loop

In this article we will learn about for loop in Java. The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.

Three types of for loop

1. Simple for loop

Syntax

 
for(initialization ; condition ; increment/decrement ){
//code to be executed
}

Program

 
public class For_loop
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
System.out.println(i);
}
}
}

Explanation

Here, i=1 is an initialization from where the for loop starts. i<=5 condition where for loop ends. i++ is incrementation which increment the i variable in each iteration. Remember that in this for loop variable i is accessible only through this for loop. Outside of for loop variable i is not accessible.

2. for each loop

Syntax

for(Type var:array){
//code to be executed
}

Program

 
public class foreach
{
public static void main(String args[])
{
int arr[] = {11, 22, 33, 44, 55};
for(int i : arr)
{
System.out.println(i);
}
}
}

Explanation

In this for each we can say variable i as container for array element. In every iteration of loop index of array is incremented and that element is stored in container.

3. Labbled for loop

Syntax

labelname:
for(initialization;condition;incr/decr){
//code to be executed
}

Program

 
public class labled_for
{
public static void main(String args[])
{
iloop:
for(int i=1; i<=5; i++)
{
jloop:
for(int j=1; j<=5; j++)
{
if(j==3) break jloop;
System.out.println(i + "-" + j);
}
}
}
}

Explanation

Here, we named for loop with variable i as iloop and for loop with variable j as jloop. When condition i==3 becomes true iloop will break while jloop continue to iterate.

Extra Extra Extra

Infinite for loop

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax

for(;;){
//code to be executed
}

Program

 
public class infinite_forloop
{
public static void main(String args[])
{
for( ; ; )
{
System.out.println("This is infinite for loop.");
}
}
}

Comments

Popular posts from this blog

System.Environment

System.Console

Datatype and keyword