Saturday, September 5, 2020

Java For Loop

Java For Loop

There are three types of for loops in Java

1.     Simple for loop
2.     for-each or Enhanced for loop
3.     Labeled for loop

 Java Simple For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

A simple for loop is the same as c/c++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts.

1.     Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. Is is an optional condition.

2.     Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition in false. It must return boolean value either true or false. It is an optional condition.

3.     Statement: The statement of the loop is executed each time until the second condition is false.

4.     Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Syntax

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

The example below will print the numbers 0 to 4:

Example

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

 Example explained

Statement 1 (Initialization) sets a variable before the loop starts (int i = 0).

Statement 2 (Condition) defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 (Increment/Decrement) increases a value (i++) each time the code block in the loop has been executed.

This example will only print even values between 0 and 10:

Example

for (int i = 0; i <= 10; i = i + 2) {
  System.out.println(i);
}

 Example:

//Java Program to demonstrate the example of for loop  
//which prints table of 1  
public class ForExample {  
public static void main(String[] args)  
    //Code of Java for loop  
    for(int i=1;i<=10;i++) 
        System.out.println(i);  
    }  
  }  
}  

Output:

1
2
3
4
5
6
7
8
9
10

Java Nested For Loop

If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.

Example:

public class NestedForExample {  
 public static void main(String[] args)  
     //loop of i  
     for(int i=1;i<=3;i++){  
          //loop of j  
          for(int j=1;j<=3;j++) 
                        System.out.println(i+" "+j);  
          }//end of j  
      }//end of i  
 }  
}  

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Example 1:

public class PyramidExample  
public static void main(String[] args)  
    for(int i=1;i<=5;i++) 
        for(int j=1;j<=i;j++) 
                    System.out.print(“*”);  
          
              System.out.println();//new line  
    }  
  }  
}  

Output:

*
* *
* * *
* * * *
* * * * *

Pyramid Example 2:

 public class PyramidExample2 {  
public static void main(String[] args) {  
int term=6;  
   for(int i=1;i<=term;i++){  
        for(int j=term;j>=i;j--){  
                   System.out.print(“*”);  
         
                   System.out.println();//new line  
    }  
  }  
}  

Output:

* * * * * *
* * * * *
* * * *
* * *
* *
* 

For-Each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined variable.

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

Syntax

for (type variableName : arrayName) {
  // code block to be executed
}

 Example:

//Java For-each loop example which prints the  
//elements of the array  
public class ForEachExample  
public static void main(String[] args) {  
    //Declaring an array  
    int arr[ ]={12,23,44,56,78};  
    //Printing array using for-each loop  
    for(int i:arr) 
        System.out.println(i);  
    }  
  }  
}  

Output:

12
23
44
56
78

The following example outputs all elements in the cars array, using a "for-each" loop:

Example

String[ ] cars = {“Volvo", "BMW", "Ford", "Mazda”};
for (String i : cars) {
  System.out.println(i);
}

Note: Don't worry if you don't understand the example above. You will learn more about Arrays in the Java Arrays chapter.

 

Java Labeled For Loop

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if we have nested for loop so that we can 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:

//A Java program to demonstrate the use of labeled for loop  
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.