Friday, June 14, 2019

Java for Loop With Examples

In Java programming language there are three types of loops- for loop, while loop and do while loop. In this post we’ll learn about for loop in Java along with usage examples.

for loop in Java

In Java there are two forms of for loop.

  1. Traditional for loop– Available from the beginning.
  2. Enhanced for loop (for-each loop)- Added in Java 5.

Syntax for traditional for loop in Java

Syntax of the traditional for loop is as follows-

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

Statements that are part of loop body are enclosed with in curly braces. If there is only one statement with in a for loop then curly braces are optional.

It is not mandatory to do initialization and increment\decrement with in the for loop statement.

There are three parts in a for loop-

  1. Initialization– Initialization step is used to set the initial value of the variable which controls the for loop. Initialization is the first step in for loop execution and it is executed only once. The initilized 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– The variable that controls the loop is incremented or decremented in this step.

Java for loop execution flow

Flow of the for loop can be explained using the following flow chart.

Java for loop

Java for loop examples

1- Using for loop to print numbers 1..5.

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

Output

 
1
2
3
4
5
  1. In the initialization part of for loop statement, variable i is declared and initialized to 1.
  2. Condition part (i <= 5) is evaluated in each iteration, returning true if value of i is less than or equal to 5 and returning false when value of i becomes greater than 5 and the condition evaluates to false which terminates the for loop.
  3. Third part of the for loop increments the variable i.

2- Using for loop in Java to print table of 7.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int number = 7;
    for(int i = 1; i <=10; i++){
      System.out.println(number + " X " +i + " = " + (i*7));
    }
  }
}

Output

 
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70

3- Using for loop to print numbers in reverse order 5..1

 
public class ForLoopDemo {
  public static void main(String[] args) {
    for(int i = 5; i > 0; i--){
      System.out.println(i);
    }
  }
}

Output

 
5
4
3
2
1

In this example value of i is decremented in the increment\decrement part.

4- As already stated it is not mandatory to do initialization and increment\decrement as part of for loop statement. Previous example of printing number in reverse order can also be written as follows.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int i = 5;
    for(; i > 0;){
      System.out.println(i);
       i--;
    }
  }
}

Output

 
5
4
3
2
1

As you can see in this example initialization and increment/decrement part is done outside the for loop statement but you still need semicolons with in the for loop statement.

Java for-each loop (Enhanced for loop)

for-each loop or enhanced for loop is available Java 5 onward. This version of for loop is used to iterate a collection of objects like an array, list or set sequentially.

Java for-each loop syntax

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

Java for-each loop examples

1- Using for-each loop to iterate an ArrayList and displaying its elements.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    List<String> avengers = new ArrayList<String>();
    avengers.add("Iron Man");
    avengers.add("Captain America");
    avengers.add("Hulk");
    avengers.add("Thor");
    avengers.add("Black Widow");
    avengers.add("Hawkeye");        
    for(String avenger : avengers){
      System.out.println(avenger);
    }
  }
}

Output

 
Iron Man
Captain America
Hulk
Thor
Black Widow
Hawkeye

2- Iterating an array using for-each loop and finding the max element in the array.

 
public class ForLoopDemo {
  public static void main(String[] args) {
    int arr[] = {6, 7, 34, -23, 45, 48, 9, 4, 10, 21};
    int max = 0;
    for(int number: arr) {
      if(number > max)
        max = number;
    }
    System.out.println("Max elements in the array- " + max);        
  }
}

Output

 
Max elements in the array- 48

Nested for loop in Java

You can have a for loop (or any other loop) inside another for loop, such loops are known as nested loops.

In a nested for loop, for each iteration of the outer for loop, inner for loop is iterated until the condition in the inner for loop evaluates to false.

Java Nested for loop example

If you want to display the following pyramid pattern in Java.

 
     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6
 
import java.util.Scanner;
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - "); 
    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    // Outer for loop
    for(int i = 1; i <= num; i++){
      // this nested loop prints the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop prints the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println();
    }            
  }
}

That's all for this topic Java for Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Switch Case Statement in Java With Examples
  2. Conditional Operators in Java
  3. Object Creation Using new Operator in Java
  4. Java Pass by Value or Pass by Reference
  5. Core Java Basics Interview Questions

You may also like-

  1. Ternary Operator in Java
  2. Constructor in Java
  3. How to Format Date in Java Using SimpleDateFormat
  4. Linked List Implementation Java Program
  5. How to Loop Through HashSet in Java
  6. Creating a Thread in Java
  7. Python Conditional Statement - if, elif, else Statements
  8. Dependency Injection in Spring Framework

No comments:

Post a Comment