Java For Loop

In this tutorial, we will learn how to use for loop to perform repetitive tasks.

The for loop is used to execute the block of codes for certain number of times.

Syntax of for loop

for(initialization; condition; increment/decrement){
 // block of codes.
}

The intialization statement is executed only once during the first execution in the for loop.

The condition is checked to execute the block of codes if the condition is satisfied.

The increment or decrement statement is used to increment or decrement any value, usually the variable initialized in the initialization statement.

Example program to print sequence of n numbers

class Main {
  public static void main(String[] args) {

    int n = 5;
    // for loop  
    for (int i = 1; i <= n; i++) {
      System.out.println("Loop "+i);
    }
  }
}

Output

Loop 1
Loop 2
Loop 3
Loop 4
Loop 5

In the above program, the value of n is initially set to 5 for running the loop 5 times.

In the for loop, we initially set the values of i to 1 which is the start count of the loop. In the condition, we check whether the value of i is less than n.

If the condition is satisfied, it will allow to enter the loop. The third statement is the increment statement which increase the value of i by 1 after the execution of the loop.

Example for sum of n natural numbers

class Main {
  public static void main(String[] args) {

    int n = 5, sum = 0;
    for (int i = 1; i <= n; ++i) {
        sum+=i;
    }
    System.out.printf("Sum of %d numbers is %d",n,sum);
  }
}

Output

Sum of 5 numbers is 15

In the above program, we need to find the sum of 5 natural numbers.

Here, we initialize the value of n to 5 and sum to 0. The variable sum is used to hold the sum of n natural numbers.

In the for loop we will initialize the value of i to 1. Then in the condition we check whether the value of i is less than n.

If the condition is satisfied, we add the value of i to sum variable.
Finally, when the condition is not satisfied, we print the value of sum.


Most Read