Java For Loops

18-Sep-2024

Learn how to use the for loop for repeating tasks in Java programs

The for loop in Java is a control flow statement that lets you run a code block repeatedly in response to a given condition. It is frequently employed when the whole number of iterations is known in advance.


Syntax :



for (initialization; condition; increment/decrement){
//statements
}


initialization: It is the initialization of the loop control variable.

condition: It is the condition that is checked before each iteration. If the condition is true, the loop continues; otherwise, it terminates.

increment/decrement: It is the update statement that is executed after each iteration.


Flow Chart:

                




 Example:



/**
 * Java For Example
 */
public class JavaExample {

    public static void main(String[] args) {
       
        for(int i=0;i<=10;i++){
            System.out.println("For Loop index : " +i);
        }
    }
}


Output:





For Loop index : 0 For Loop index : 1 For Loop index : 2 For Loop index : 3 For Loop index : 4 For Loop index : 5 For Loop index : 6 For Loop index : 7 For Loop index : 8 For Loop index : 9 For Loop index : 10



 Explanation:


In this example, the for loop first initialized the variable i = 0 and then tested the condition. The condition is i value is less than or equal to 10. If the condition is true then the for block of code will execute once. After executing all statements in the block of for the variable i value will increment by 1 and next again test the condition if the condition is true then the block of code will execute again. After that again increment the variable i value by 1. This process is repeated until the condition is false. In the example when the variable i value is 11, the condition will false and break the loop statement.




Comments