🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Nested Loops

Java Nested Loop Examples

In Java, you can nest loops by placing one loop inside another. This is often used for complex iterations, such as working with two-dimensional arrays or for solving problems that involve nested structures. The most common types of nested loops are nested for loops.

Example of Nested for Loop - Multiplication Table:

public class NestedForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.print(i * j + "\t");
            }
            System.out.println(); // Move to the next line after each row
        }
    }
}

In this example:

  • The outer loop (for (int i = 1; i <= 5; i++)) iterates over the rows of the table.
  • The inner loop (for (int j = 1; j <= 5; j++)) iterates over the columns for each row.
  • System.out.print(i * j + "\t"); prints the product of i and j followed by a tab character.
  • System.out.println(); moves to the next line after each row is printed.

The output of this program will be a simple multiplication table:

1	2	3	4	5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25

Example of Nested while Loop - Pattern:

public class NestedWhileLoopExample {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 3) {
            int j = 1;
            while (j <= i) {
                System.out.print("* ");
                j++;
            }
            System.out.println();
            i++;
        }
    }
}

In this example, the outer while loop controls the rows, and the inner while loop controls the number of asterisks printed in each row. The output of this program will be:

* 
* * 
* * *

Example of Combination of Loop Types - while Inside for:

public class CombinationOfLoopsExample {
    public static void main(String[] args) {
        int i = 1;

        while (i <= 3) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
            i++;
        }
    }
}

This program produces the same output as the nested while loop example.

Nested loops provide a way to handle more complex patterns and structures in your code. However, it's essential to maintain clarity and avoid excessive nesting to keep the code readable.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.