August 9, 2022

for Loop in Java With Examples

Loop in any programming language is used to repeatedly execute a block of code until a condition to terminate the loop is satisfied. In Java there are three types of loops- while loop, do-while loop and for loop. In this post we’ll see how to use for loop in Java.

Java for loop

In Java there are two forms of for loop.

  1. Traditional for loop
  2. Enhanced for loop (for-each loop)

Syntax of the traditional for loop is as follows-

for(initialization; condition; increment\decrement) {
    // body
}

Block of code that is executed with in a loop is enclosed with in curly braces. If there is only one statement that has to be executed with in a for loop then curly braces are optional.

Java for loop execution flow

Following image shows the execution flow of the for loop.

  1. Initialization- When the execution of the for loop starts, first step is initialization which is executed only once in the beginning. Initialization step is generally used to set the initial value of the variable which controls the for loop. This variable is later incremented or decremented in the increment\decrement step of the loop.
  2. Condition- Condition is a boolean expression that is evaluated in each iteration. If condition is true then the loop body is executed, if condition is false then the loop terminates.
  3. Increment\decrement- In this step the variable that controls the loop is incremented or decremented.

Java for loop examples

1- First example uses for loop to print numbers from 1 to 10.

public class ForLoopExample {
  public static void main(String[] args) {
    for(int i = 1; i <=10; i++){
      System.out.println("Value- " + i);
    }
  }
}
Output
Value- 1
Value- 2
Value- 3
Value- 4
Value- 5
Value- 6
Value- 7
Value- 8
Value- 9
Value- 10
  1. First the variable is declared and initialized to 1.
  2. Condition (i <= 10) is evaluated in each iteration, it returns true till value of i is less than or equal to 10. Condition is evaluated to false when value of i becomes greater than 10 and the loop terminates.
  3. Third part of the for loop increments the control variable.

In the next iteration of the for loop only step-2 and step-3 are executed as initialization happens only once.

You can see in the code that the variable declaration and initialization (int i = 0) both happened with in the for loop. Declared like this the scope of the variable is limited with in the loop.

2- Second example uses for loop to print numbers in reverse order 10 to 1.

public class ForLoopExample {
  public static void main(String[] args) {
    for(int i=10; i>0; i--){
      System.out.println("Value- " + i);
    }
  }
}
Output
Value- 10
Value- 9
Value- 8
Value- 7
Value- 6
Value- 5
Value- 4
Value- 3
Value- 2
Value- 1

3- Using for loop to add numbers 1 to 20.

public class ForLoopExample {
  public static void main(String[] args) {
    int sum = 0;
    for(int i=1; i<=20; i++)
      sum = sum + i;
    System.out.println("Sum is- " + sum);
  }
}
Output
Sum is- 210

You can see that the curly braces are not used here as curly braces are optional when there is a single statement with in the for loop.

4- Till now all the examples have used all the three parts of the for loop with in the loop statement but for loop is flexible about the initialization and increment/decrement part.

public class ForLoopExample {
  public static void main(String[] args) {
    int i = 0;
    for(; i<5; ){
      System.out.println("Hello");
      i++;
    }
  }
}
Output
Hello
Hello
Hello
Hello
Hello

In the code both initialization and increment/decrement part are moved out of the loop statement. Note that you still need to have semicolons for those.

For-each loop (Enhanced for loop) in Java

Java 5 onward there is another version of for loop available known as for-each loop or enhanced for loop.

Enhanced for loop is used to iterate a collection of objects like an array, list or set sequentially.

Syntax of the for-each loop is as follows-

for(type var : collection){
  //body
}
  • Here type specifies the type of the elements in the collection.
  • var is the variable that is assigned the next element from the collection in each iteration.
  • collection specifies the collection that is iterated.

Java for-each loop examples

1- Iterating an array using for-each and getting the sum of all the elements in the array.

public class ForEachDemo {
  public static void main(String[] args) {
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sum = 0;
    for(int num: nums) {
      sum = sum + num;
    }
    System.out.println("Sum of the elements- " + sum);
  }
}
Output
Sum of the elements- 55

In the code, in each iteration of the for-each loop num variable is assigned the next element of the array nums.

2- Iterating an ArrayList of Strings and displaying values.

public class ForEachDemo {
  public static void main(String[] args) {
    List<String> names = new ArrayList<String>();
    names.add("Toronto");
    names.add("Montreal");
    names.add("Ottawa");
    names.add("Vancouver");
    //iterating ArrayList
    for(String name: names) {
      System.out.println("Name- " + name);
    }		
  }
}
Output
Name- Toronto
Name- Montreal
Name- Ottawa
Name- Vancouver

Nested for loop

In Java, like in most of the programming languages, for loop can be nested. So, you can have one for loop inside another. In the nested loops for each iteration of the outer for loop, inner for loop is iterated until the condition in the inner for loop is not satisfied.

For example following program prints the pyramid pattern using nested for loops.

public class NestedLoop {
  public static void main(String[] args) {
    int rows = 6;
    for(int i = 1; i <= rows; i++){
      for(int j = 0; j < rows - i; j++)
        System.out.print(" ");
      for(int k = 0; k < i; k++){
        System.out.print("* ");
      }
      System.out.println();                   
      }
  }
}
Output
     * 
    * * 
   * * * 
  * * * * 
 * * * * * 
* * * * * * 

That's all for the topic for Loop in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment