Courses / Complete Java Course by codesofrohan / Loops / Nested for Loop in Java: Understanding Loops Inside Loops

Nested for Loop in Java: Understanding Loops Inside Loops

In the previous lesson, we learned how to use a for loop in Java to repeat a particular piece of code multiple times. Instead of writing the same statement again and again, we can use a loop and let Java handle the repetition for us.

But now let's take that idea one step further.

What happens when one repetition itself needs to be repeated?

For example, suppose we want to print five stars on the same line:

*****

A normal for loop can easily handle this. But what if we want those five stars to appear three times on separate lines?

*****
*****
*****

Now we have two levels of repetition. First, we need to print five stars. Then, we need to repeat that entire process three times.

This is exactly where nested for loops become useful. A nested for loop simply means putting one for loop inside another for loop.

What Is a Nested for Loop?

A nested for loop is not a completely different type of loop. It is simply a normal for loop placed inside another for loop.

The important thing is to understand the responsibility of each loop.

The outer loop controls the larger repetition, while the inner loop performs the repeated operation inside it.

Think about it this way:

Outer loop → How many times should the process happen?

Inner loop → What should happen each time?

The most important rule is this:

Whenever the outer loop runs once, the entire inner loop runs completely.

So, if the outer loop runs three times and the inner loop prints five stars, the inner loop will complete its five-star task three separate times.


Starting With a Simple Example

Let's first understand the problem without immediately jumping into nested loops.

Suppose we want to print one star. That's straightforward.

Now imagine that we need five stars on the same line.

A normal for loop can repeat the printing operation five times. The important thing here is that we use print() instead of println() because we don't want Java to move to a new line after every star.

So the result becomes:

*****

This is still just a normal loop.

The real problem starts when we say:

"Print those five stars three times."

The expected output is:

*****
*****
*****

At this point, we already have a loop that knows how to print five stars. We don't need to create that logic again. Instead, we need a way to repeat that entire loop.

That's where the second loop comes in.


Putting One for Loop Inside Another

Instead of writing the same five-star loop multiple times, we place it inside another loop.

Conceptually, the structure looks like this:

for (outer loop) {
    for (inner loop) {
        // repeated operation
    }
}

The outer loop decides how many times the inner loop should be executed.

For our example, the outer loop runs three times, while the inner loop prints five stars every time.

After the inner loop finishes printing five stars, System.out.println() is used to move to the next line.

The output is therefore:

*****
*****
*****

This is the simplest way to understand a nested loop: one complete repetitive process is being repeated by another loop.


Understanding the Outer Loop

Let's focus on the outer loop first.

If our outer loop runs three times, its counter goes through three values:

0
1
2

You can think of these iterations as representing three different rows.

So the outer loop is responsible for creating the three lines.

However, the outer loop isn't actually printing the stars. It simply tells Java:

"Run the inner operation again."

This distinction is extremely important.

When learning nested loops, don't try to think of both loops as doing the same thing. Each loop should have a clear responsibility.

For our example:

Outer loop → controls the number of rows

Inner loop → controls the number of stars in each row


Understanding the Inner Loop

The inner loop is responsible for printing the stars.

For every single iteration of the outer loop, the inner loop starts from the beginning and completes its entire job.

So when the outer loop starts for the first row, the inner loop prints five stars.

Once those five stars are printed, the inner loop finishes.

The program then moves to the next line and the outer loop starts its next iteration.

The inner loop then starts again and prints another five stars.

This happens until the outer loop has completed all three iterations.

So you can visualize the execution like this:

Outer iteration 1
    → Inner loop prints 5 stars

Outer iteration 2
    → Inner loop prints 5 stars

Outer iteration 3
    → Inner loop prints 5 stars

That's why the final output contains three rows of five stars.


A Real-World Example

Let's connect this concept to something outside programming.

Imagine a school with three classrooms, and each classroom has five students.

Suppose you want to perform an operation for every student in every classroom.

You could think of the problem like this:

First classroom

→ Student 1
→ Student 2
→ Student 3
→ Student 4
→ Student 5

Second classroom

→ Student 1
→ Student 2
→ Student 3
→ Student 4
→ Student 5

Third classroom

→ Student 1
→ Student 2
→ Student 3
→ Student 4
→ Student 5

There are clearly two levels of repetition.

First, we move through the classrooms.

Then, inside each classroom, we move through the students.

This is the same mental model as a nested loop:

Outer loop → classrooms

Inner loop → students inside each classroom

The same idea can be applied to rows and columns, groups and items, floors and rooms, or many other situations where one repeated operation exists inside another repeated operation.


Creating a Star Pattern

Now let's make the problem a little more interesting.

Suppose we want this pattern:

*
**
***
****
*****

At first, this may look complicated, but we can break it down.

There are five rows.

The number of stars in each row is:

1
2
3
4
5

Now look at the outer loop's counter.

If it starts from 0, its values will be:

0
1
2
3
4

There is a simple relationship between these two sequences.

We need:

1  2  3  4  5

but the outer loop gives us:

0  1  2  3  4

The required number of stars is therefore one more than the outer-loop value.

That's why we use:

j + 1

The logic becomes:

When j is 0 → print 1 star

When j is 1 → print 2 stars

When j is 2 → print 3 stars

When j is 3 → print 4 stars

When j is 4 → print 5 stars

So the pattern gradually grows from one star to five stars.


Why Does j + 1 Matter?

This is one of the most important parts of the example.

Beginners often wonder why we don't simply use j.

The reason is that our counter starts at zero.

When j = 0, we don't want zero stars. We want the first row to contain one star.

Adding one solves this:

0 + 1 = 1

Then:

1 + 1 = 2
2 + 1 = 3
3 + 1 = 4
4 + 1 = 5

So j + 1 converts the outer-loop values from:

0, 1, 2, 3, 4

into the number of stars we need:

1, 2, 3, 4, 5

This small relationship is what creates the increasing pattern.


Creating the Reverse Pattern

Now let's do the opposite.

Instead of increasing the number of stars, we want them to decrease:

*****
****
***
**
*

The number of stars now follows:

5
4
3
2
1

We can achieve this by changing the direction of the outer loop.

Instead of starting from 0 and increasing, we start from 4 and decrease:

for (int j = 4; j >= 0; j--)

Now the values of j are:

4 → 3 → 2 → 1 → 0

Since the inner loop still uses the relationship j + 1, the number of stars becomes:

5 → 4 → 3 → 2 → 1

The result is the reverse pattern.

Notice something important here: we didn't need completely different logic. We mainly changed the way the outer loop moves through its values.

This is an important programming habit: sometimes changing the initial value, condition, or increment/decrement can completely change the output while keeping most of the logic the same.


How to Think About Nested for Loops

Whenever you see a nested loop, don't try to understand everything at once.

Instead, ask two simple questions.

1. What does the outer loop control?

It usually controls the larger repetition.

For example:

  • Number of rows

  • Number of classrooms

  • Number of groups

  • Number of times a process should repeat

2. What does the inner loop control?

It controls the repeated operation inside each outer-loop iteration.

For example:

  • Number of stars

  • Students inside a classroom

  • Columns inside a row

  • Items inside a group

For our star pattern, the mental model is:

Outer loop → rows

Inner loop → stars in each row

Once you start thinking about nested loops this way, they become much easier to understand.


The Main Idea: Repetition of Repetition

The biggest takeaway from this lesson is actually very simple.

A normal for loop is used when we need to repeat a task.

But sometimes that entire repetitive task needs to be repeated again.

That's when we use a nested loop.

In our example, the inner loop knows how to print five stars. The outer loop doesn't need to know how individual stars are printed. Its job is simply to repeat that process multiple times.

This separation makes the program easier to understand:

Outer loop → repeat the process

Inner loop → perform the process

This concept goes far beyond star patterns. The star examples are simply a visual way to understand what is happening inside the loops.


Final Takeaway

A nested for loop is simply a for loop placed inside another for loop.

The most important thing is not memorizing a particular pattern or code snippet. Instead, understand the relationship between the two loops.

When the outer loop runs once, the entire inner loop runs completely.

When the outer loop runs again, the inner loop starts again.

That's how we can create multiple rows, repeated groups, and different patterns.

For example, an increasing pattern can be understood as:

j = 0 → 1 star
j = 1 → 2 stars
j = 2 → 3 stars
j = 3 → 4 stars
j = 4 → 5 stars

And by making the outer loop move in the opposite direction, we can create:

5 → 4 → 3 → 2 → 1

The key mental model to remember is:

Outer loop controls the bigger repetition, while the inner loop handles the repeated operation inside it.

Once this concept is clear, you'll be able to approach many pattern-based problems much more confidently.

The next step is to take this same nested-loop concept and use it to create more complex patterns, such as a pyramid structure, where the relationship between spaces and stars becomes slightly more challenging.

🔖 Bookmark saved successfully!