Nested Looping Statements Tutorial

In this tutorial I am going to teach you how to create nested loops using the three Java looping statements: for, while, and do-while. Nested loops consist of inner loops that are nested inside of outer loops. The program will display all the letters of the alphabet five times using each one of looping statement types.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md NestedLoops
C:\Java>cd NestedLoops
C:\Java\NestedLoops>Notepad NestedLoops.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class NestedLoops {
    public static void main(String args[]) {

        System.out.println("Nested for loop: ");
        for (int i = 0; i < 5; i++) {
            char upperA = 'A';
            for (int a = 0; a < 26; a++) {
                System.out.print(upperA);
                upperA++; 
            }
            System.out.println();
        }
        System.out.println();

        System.out.println("Nested while loop: ");
        int x = 0;
        while (x < 5) {
            char upperA = 'A';
            int y = 0;	
            while (y < 26) {
                System.out.print(upperA);
                upperA++; 
                y++;
            }
            System.out.println();
            x++;
        }
        System.out.println();

        System.out.println("Nested do-while loop: ");
        int c = 0;
        do {
            char upperA = 'A';
            int d = 0;
            do {
                System.out.print(upperA);
                upperA++; 
                d++;
            } while(d < 26);
            System.out.println();
            c++;
        } while(c < 5);
        System.out.println();	
    	
    }
}

Now switch back to the command prompt (CMD) and type in javac NestedLoops.java and press Enter.
Now type in java NestedLoops and press Enter.


C:\Java\NestedLoops>javac NestedLoops.java
C:\Java\NestedLoops>java NestedLoops
Nested for loop:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Nested while loop:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Nested DO-while loop:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ


Final thoughts

Nesteds loop are used quite often. They are extremely useful for reading and writing multi-dimensional arrays. Don't worry about multi-dimensional arrays yet, I have only covered single dimensional arrays so far. I will covering multi-dimensional arrays in a future tutorial.


Tutorials