Core Java Fundamentals ยท Loops
Learn how to use loops inside other loops to handle more complex repetitive tasks, like working with two-dimensional data or creating patterns.
public class NestedLoopDemo {
public static void main(String[] args) {
int rows = 3;
int cols = 4;
// Outer loop for rows
for (int i = 1; i <= rows; i++) {
// Inner loop for columns
for (int j = 1; j <= cols; j++) {
System.out.print("* ");
}
System.out.println(); // Move to the next line after each row
}
}
}rows and initialize it to 3.cols and initialize it to 4.i is initialized to 1. This variable will control the rows.i <= rows (1 <= 3) is checked. It is true, so the body of the outer loop will execute.j is initialized to 1. This variable will control the columns for the current row.j <= cols (1 <= 4) is checked. It is true, so the body of the inner loop executes.System.out.print("* ") is executed. It prints an asterisk followed by a space. The string "* " is added to the string pool. The cursor remains on the same line.j++ is executed. j becomes 2. The control goes back to the inner loop condition.j <= cols (2 <= 4) is checked again. It is true, so the inner loop body executes again.j++ is executed. j becomes 3.j <= cols (3 <= 4) is true.j++ is executed. j becomes 4.j <= cols (4 <= 4) is true.j++ is executed. j becomes 5.j <= cols (5 <= 4) is now false. The inner loop terminates. The variable j goes out of scope.System.out.println() is executed, which moves the cursor to the next line in the console.i++ is executed. i becomes 2.i <= rows (2 <= 3) is checked. It is true, so the outer loop body executes for the second time.j is set to 1 again.j <= cols (1 <= 4) is true, so the inner loop starts for the second row.System.out.print("* ") is executed for the second row.j will go from 1 to 4, printing "* " each time.j becomes 5, the condition 5 <= 4 is false, and the inner loop terminates.i++ is executed, and i becomes 3.i <= rows (3 <= 3) is checked. It is true, so the outer loop executes for the third time.i++ is executed, and i becomes 4.i <= rows (4 <= 3) is checked. It is now false, so the outer loop terminates.