Slide 1
Slide 2
Slide 3

Nested For Loop in java programming (V33)

No Comments

Nested For Loop

A nested for loop is a for loop inside another for loop. The outer loop controls the number of iterations, while the inner loop executes completely for each iteration of the outer loop.

Syntax:

How it works

  • The outer loop runs once.

  • The inner loop executes all its iterations.

  • After the inner loop completes, the outer loop increments and repeats.

  • The process continues until the outer loop’s condition is false.

Source Code:

Copied!
public class NestedLoop {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) { // Outer loop
            for (int j = 1; j <= 2; j++) { // Inner loop
                System.out.println("i=" + i + ", j=" + j);
            }					  
        }						  
    }							  
}

Result:

Source Code:

Copied!
public class StarPattern {
    public static void main(String[] args) {
        int n = 5; // Number of rows
        for (int i = 1; i <= n; i++) { // Outer loop (rows)
            for (int j = 1; j <= i; j++) { // Inner loop (columns)
                System.out.print("* ");
            }
            System.out.println(); // Move to the next line
        }
    }
}

Result:

Source Code:

Copied!
public class PyramidStarPattern {
    public static void main(String[] args) {
        int n = 5; //5 rows
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n - i; j++) { // Print spaces
                System.out.print(" ");
            }
            for (int j = 1; j <= 2 * i - 1; j++) { // Print stars
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top