OneBite.Dev - Coding blog in a bite size

implement a three nested loop in java

Code snippet on how to implement a three nested loop in java

  for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
      for (int k = 0; k < 5; k++) {
        System.out.println("I=" + i + ", J=" + j + ", K=" + k);
      }
    }
  }

This code is an example of a three nested loop written in Java. It begins with the outermost loop, which is the first loop (the one with the initializer “int i = 0;). This loop has the condition i < 5, which means “run the loop for as long as i is less than 5.”

Inside the first loop, there is a second loop (the one with initializer “int j = 0;”). This loop also has a condition j < 5. This loop runs for as long as j is less than 5.

Inside the second loop, there is a third loop (the one with initializer “int k = 0;”). This loop also has a condition k < 5. This loop runs for as long as k is less than 5.

Each loop runs the code within its scope, which in this case is simply the command System.out.println(“I=” + i + ”, J=” + j + ”, K=” + k). This code prints the values of i, j and k each time the loop runs. When all the loops are done, the code will have printed all possible combinations of i, j and k from 0 to 4, resulting in a total of 125 combinations.

java