11 Java Fundamentals | Nested Loops in Java | By Dummy for Dummies

Java Nested Loops | Hassan Bukhari
Java Notes

11 Java Fundamentals | Nested Loops in Java | By Dummy for Dummies

Java Beginner Guide Nested Loops Patterns Matrix

INTRODUCTION

Remember when we talked about nested if-else statements? One structure of if-else inside another structure. Similarly here we will have a loop inside another loop. It'll come in handy in many projects and actual coding later. A student who understands nested loops is often considered good in programming.


NESTED LOOPS

Suppose a monkey wants 5 bananas. For each banana it has to perform in the circus. So it will be a loop of performing 5 times in the circus. Now imagine the performance it gives in the circus is jumping into a fire ring 5 times. This jumping into the fire ring is also a loop of a single act that it will do 5 times.

So here we have a loop of working in the circus. In each iteration, it'll run another loop of jumping into the ring 5 times. In a single iteration of one loop, another loop runs and completes as many times as we set. This is the concept of nested loops.

Here is a demonstration of just one loop, monkey performing and getting banana:

Java
public class Main {
    public static void main(String[] args) {
        // Monkey performing and getting banana
        for (int banana = 1; banana < 6; banana++) {
            System.out.println("Monkey performed in circus");
            System.out.println("Banana acquired: " + banana);
        }
        System.out.println("Loop exited!");
    }
}
Console Output
Monkey performed in circus Banana acquired: 1 Monkey performed in circus Banana acquired: 2 Monkey performed in circus Banana acquired: 3 Monkey performed in circus Banana acquired: 4 Monkey performed in circus Banana acquired: 5 Loop exited!

This is a simple one loop. Now let's write a loop for the performance, i.e., in each performance the monkey has to jump into the ring 5 times, so we will replace the performance line of code with a loop:

Java
public class Main {
    public static void main(String[] args) {
        // Monkey performing and getting banana
        for (int banana = 1; banana < 6; banana++) {
            System.out.println("Performance starts!");

            // Inner loop: monkey jumps 1 to 5 times
            for (int jump = 1; jump < 6; jump++) {
                System.out.println("Monkey jumped " + jump + " time(s)");
            }

            System.out.println("Performance ended! (Inner Loop exited!)");
            System.out.println("Banana acquired: " + banana);
            System.out.println();
        }
        System.out.println("All performances completed! (Outer Loop exited)");
    }
}
Console Output
Performance starts! Monkey jumped 1 time(s) Monkey jumped 2 time(s) Monkey jumped 3 time(s) Monkey jumped 4 time(s) Monkey jumped 5 time(s) Performance ended! (Inner Loop exited!) Banana acquired: 1 Performance starts! Monkey jumped 1 time(s) Monkey jumped 2 time(s) Monkey jumped 3 time(s) Monkey jumped 4 time(s) Monkey jumped 5 time(s) Performance ended! (Inner Loop exited!) Banana acquired: 2 Performance starts! Monkey jumped 1 time(s) Monkey jumped 2 time(s) Monkey jumped 3 time(s) Monkey jumped 4 time(s) Monkey jumped 5 time(s) Performance ended! (Inner Loop exited!) Banana acquired: 3 Performance starts! Monkey jumped 1 time(s) Monkey jumped 2 time(s) Monkey jumped 3 time(s) Monkey jumped 4 time(s) Monkey jumped 5 time(s) Performance ended! (Inner Loop exited!) Banana acquired: 4 Performance starts! Monkey jumped 1 time(s) Monkey jumped 2 time(s) Monkey jumped 3 time(s) Monkey jumped 4 time(s) Monkey jumped 5 time(s) Performance ended! (Inner Loop exited!) Banana acquired: 5 All performances completed! (Outer Loop exited)
⦿ The outer loop runs 5 times → Once for each banana.
⦿ For each banana, the inner loop runs 5 times → 5 jumps
⦿ Total jumps = 5 x 5 = 25
⦿ In each iteration of the outer loop, the inner loop freshly starts from 1 and ends at 5.

TECHNICAL EXAMPLE (Matrix)

Let's write a small code that outputs a square matrix of any order we want.

Java
import java.util.Scanner;

public class SquareMatrix {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter order of square matrix (e.g., 3 for 3x3): ");
        int n = scanner.nextInt();

        int value = 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                System.out.print(value + "\t");
                value++;
            }
            System.out.println();
        }

        scanner.close();
    }
}
Console Output
Enter order of square matrix (e.g., 3 for 3x3): 3 1 2 3 4 5 6 7 8 9
  • The outer loop controls the number of rows. On each iteration, it allows the inner loop to run and do whatever it wants. At the end of the iteration, it shifts to the next line. That's how it controls rows.
  • The inner loop actually prints numbers on the row set by the outer loop. It runs all of its iterations and prints the numbers on a single line.
  • Each value the inner loop prints acts as a separate column on that row. Therefore, we say the inner loop controls the number of columns.
  • Each time a value is printed, value++ updates the value so that the next value is NOT the same as the previous.
  • The n in the condition controls how many iterations the outer loop and inner loop will run. If the user enters 3, both inner and outer loops will run for 3 iterations. As a result, the outer loop will create 3 rows, and the inner loop will create 3 columns on each.

CLOSING

That's it for Nested Loops in Java. You will now be able to understand YouTube tutorials and textbooks. There are a few complex things in nested loops though, e.g., pattern making like this:

Right Triangle: * * * * * * * * * * * * * * * Pyramid: * * * * * * * * * * * * * * * * * * * * * * * * * Hollow Triangle: * * * * * * * * * * * * Hollow Square: * * * * * * * * * * * * * * * *

But now you'll be able to understand them from tutorials. For exercise and project, try learning to make the mentioned patterns. I would suggest learning from Apna College YT channel. Still, if there is any issue, you can ask me or any other senior on campus. I assure you they are all really nice.