Nested For Loops in Java

Lesson Transcript
Instructor: Martin Gibbs

Martin has 20 years experience in Information Systems and Information Technology, has a PhD in Information Technology Management, and a master's degree in Information Systems Management. He is an adjunct professor of computer science and computer programming.

Nested for loops in Java are loops that iterate inside a larger parent-loop. Examine the conventions surrounding nested loops while also learning the syntax required to utilize these useful tools. Updated: 12/28/2021

Nested Loops

A nested loop is really a loop-within-a-loop. This can be done at two levels, or three, or even more. But as we'll see in this lesson, increased nesting can cause issues and be very hard to maintain. Below, you'll see an example of how these nested loops can appear.

for (int i = 1; i <= 5; i++) {
  for (int j = 1; j <= i; j++) {
    // do something
  }
}

Think of a nested loop as a race track within a race track. When you begin each lap on the main oval, you veer into another track inside the original (the nested track or loop). You may go around any number of times within the smaller track before looping around the main one. Then it starts over again until you've done the required number of laps on the main track. In all, you may go around a thousand times, or many more!

In Java, nested for loops are usually declared with the help of counter variables, conventionally declared as i, j, k, and so on, for each nested loop. That is, the first loop uses i as the counter, while j is used for the second, and so on. This keeps track of how many times each for loop is run.

Let's look at this one more time. The j loop will actually run 15 times because i is set to stop at 5 runs. Each run would look like what you can see in this table.

Run value of i loops through j
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

This is a total of 15 laps through the inner track.

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: While Loops in Java: Example & Syntax

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 Nested Loops
  • 1:20 Examples of Nested Loops
  • 3:24 Mistakes in Looping
  • 4:18 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Examples of Nested Loops

Let's take a look at how this will work in the Java language.

Let's first look at a simple example of 5 laps. This example has a main loop (race track) that will process until the counter reaches 5. However, within each lap around the track, it will step into the nested for loop (nested race track) and loop. The number of loops in the nested track will depend on what the lap count is. If we are on lap 3, we'll go around 3 times within the nested track.

Below is the code. Note that we'll print out the values of each counter.


for (int i = 1; i < 5; i++) {
 System.out.println("Outside loop: i = " + i);  for (int j = 1; j <= i; j++) {
  System.out.println(" Nested Loop: j = " + j);
 }
}


And this next image is the output, showing the value of the outer track (i) and the inner track (j). During the first pass, both are 1, but then the inside track has more runs through it as the value of i (the outer track) increases.


Java nested example


Now let's look at another example. This time, focusing on cookies. In this example, we'll place chips on 100 cookies. There are 10 cookies sheets, each with 10 cookies on them (to make it simple). We have to start at sheet 1, run through all the cookies, then move to sheet 2. Instead of laps around a race track, we're making stops at each cookie sheet, which you can see play out with this code.


int cookieSheets = 10;
int cookies = 100;
for (int i = 1; i <= cookieSheets; i++) {
 System.out.println("Chips placed on sheet: " + i);
 for(int j = 1; j <= 10; j++) {
  System.out.println(" And on Cookie: " + j);
 }
}


The output can be seen here. Only the first two are displayed for the sake of brevity.


Java nested for output


Now let's take a look at an example involving looping through rows and columns. Another example is a loop through a table's rows and columns. In this example, let's move away from using i and j, so that the variable names make more sense for a table. The sample table has 24 rows and 24 columns. There are some special additions to this code for displaying the row number times the column, which creates an old-fashioned multiplication table, but the key syntax is the same for the loop.

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back

Resources created by teachers for teachers

Over 30,000 video lessons & teaching resources‐all in one place.
Video lessons
Quizzes & Worksheets
Classroom Integration
Lesson Plans

I would definitely recommend Study.com to my colleagues. It’s like a teacher waved a magic wand and did the work for me. I feel like it’s a lifeline.

Jennifer B.
Teacher
Jennifer B.
Create an account to start this course today
Used by over 30 million students worldwide
Create an account