Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.

 A for loop consists of four parts as below

  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. It 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 is false. It must return boolean value either true or false. It is an optional condition.
  3. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
  4. Statement: The statement of the loop is executed each time until the second condition is false.

Syntax :

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

 

Example :

import java.util.*;

public class Main {
public static void main(String[] args) {
for (int i = 0; i < 7; i++) {
System.out.println("The number is : "+i);
}
}
}

Output :

The number is : 0
The number is : 1
The number is : 2
The number is : 3
The number is : 4
The number is : 5
The number is : 6

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

71615