HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

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

Example, the following code prints the numbers from 1 to 10:

Example
int age = 17;
                        
for (int i = 1; i <= 10; i++) {
 System.out.println(i);
 }


 -The initialization statement initializes the variable i to 1.
-The condition statement evaluates to true as long as the value of i is less than or equal to 10.
-The update statement increments the value of i by 1 after each iteration of the loop.

Nested Loops-

It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
    
 // Outer loop
  for(int i = 1; i <= 2; i++) {
 System.out.println("Outer: " + i) // Executes 2 times
                          
  // Inner loop
 for (int j = 1; j <= 3; j++) {
 System.out.println>(" Inner: " + j); // Executes 6 times (2 * 3)
                          }
                        }