Java - For Loop

The for loop is used to iterate a set of statements a fixed number of times. The for loop in Java is similar to the for loop in other programming languages, but it has some additional features that make it more powerful and flexible.

The syntax of the for loop is as follows:

for (initialization; condition; increment/decrement) {
   // code to be executed
}
  • The initialization statement is executed only once at the beginning of the loop. It is used to initialize the loop counter variable.
  • The condition is checked before each iteration of the loop. If it is true, the loop body is executed. If it is false, the loop terminates.
  • The increment/decrement statement is executed after each iteration of the loop. It is used to update the loop counter variable.
  • Example:

Let's say we want to print the numbers from 1 to 5 using a for loop. We can do it as follows:

for (int i = 1; i <= 5; i++) {
   System.out.println(i);
}

In the above example, the initialization statement initializes the loop counter variable i to 1. The condition checks if i is less than or equal to 5. If it is true, the loop body is executed, which prints the value of i using the System.out.println() method. The increment statement increments the value of i by 1 after each iteration of the loop.

Nested for loop:

The for loop can also be nested inside another for loop. This is known as a nested for loop. A nested for loop is used to iterate over a two-dimensional array or a matrix.

Let's say we want to print a matrix of 3 rows and 3 columns. We can do it using a nested for loop as follows:

int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < 3; i++) {
   for (int j = 0; j < 3; j++) {
      System.out.print(matrix[i][j] + " ");
   }
   System.out.println();
}

In the above example, we have created a two-dimensional array matrix of 3 rows and 3 columns. The outer for loop iterates over the rows of the matrix. The inner for loop iterates over the columns of the matrix. The System.out.print() method prints each element of the matrix followed by a space. The System.out.println() method is used to print a new line after each row of the matrix.

Infinite loop:

An infinite loop is a loop that runs indefinitely. It occurs when the condition in the for loop is always true or when the increment/decrement statement does not change the loop counter variable. An infinite loop can cause the program to hang or crash.

for (;;) {
   // code to be executed
}

The above example shows an infinite loop. There is no condition specified in the for loop. Therefore, the loop runs indefinitely.