Java : for loop


The for loop in Java is a control flow statement used to iterate a part of the program several times. It’s most preferred when the number of the iteration is fixed.

In for loop are used in three ways :

  1. Simple For Loop
  2. Enhanced For Loop or For-each
  3. Labeled For Loop

Java Simple For Loop

In java, simple for loop is the same as C/C++. It consists of four parts:

Syntax


for(initialization;condition;increment/decrement){  
// code to be executed 
}
  • Initialization (Optional): It is the initialization condition which is executed once when the loop starts. We can initialize the variable or use an already initialized variable.
  • Condition (Optional): It is executed each time to test the condition of the loop. It return boolean values true or false but continues execution depend on until the condition is true.
  • Statement: The statement inside the loop is executed each time until the second condition is false.
  • Increment/Decrement (Optional): It increments or decrements the intialization variable value.

For Loop Flow Chart

for loop flow chart

Example:

Program to print even numbers between 1 to 20

public class SimpleForLoopExample {

	public static void main(String[] args) {
		System.out.println("Even Numbers between 1 to 20 :");
		for (int i = 1; i <= 20; i++) {
			// If modulus of number after devision 2 is 0 then even number
			if (i % 2 == 0) {
				System.out.println(i);
			}
		}
	}
}

Output


Even Numbers between 1 to 20 :
2
4
6
8
10
12
14
16
18
20

Java Nested For Loop

If we have a loop inside a loop that is called as nested loop. For each iteration of outer loop inner loop executes completely.

Example:
Print table for 1 to 10

public class NestedForLoop {

	public static void main(String[] args) {
     for(int i=1;i<=10;i++)
     {
    	 for(int j=1;j<=10;j++)
    	 {
    		System.out.printf("%-3d",(i*j)) ;
    	 }
    	 System.out.println();
     }

	}
}

Output:


1  2  3  4  5  6  7  8  9  10 
2  4  6  8  10 12 14 16 18 20 
3  6  9  12 15 18 21 24 27 30 
4  8  12 16 20 24 28 32 36 40 
5  10 15 20 25 30 35 40 45 50 
6  12 18 24 30 36 42 48 54 60 
7  14 21 28 35 42 49 56 63 70 
8  16 24 32 40 48 56 64 72 80 
9  18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100

Java for-each Loop (Java 5+)

The for-each loop is used to traverse object type like array or collection. Java for-each loop is easier than simple for loop because not required to increase or decrese indexes for accessing collections values.

Java for-each loop works on elements basis not index and returns element one by one in the defined variable.

Syntax:


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

Example:

public class ForEachLoopExample {
public static void main(String[] args) {
    //Declaring an array
    int numArr[]={10,20,30,40,50};
    //Print array by using for-each loop
    for(int i:numArr){
        System.out.println(i);
    }
}
}

Output

10
20
30
40
50

Java Labeled For Loop

By using labeled for loop can define a name of loop by using label before the for loop. It’s useful when nested for loop need to break/continue specific for loop.

Usually, break and continue keywords breaks/continues the innermost for loop only.

Syntax:


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

Example:

public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+” “+j);
}
}
}
}
Output:

1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behavior of any loop.

public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+” “+j);
}
}
}
}
Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

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

//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println(“infinitive loop”);
}
}
}
Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.

Advertisements

2 thoughts on “Java : for loop”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s