Learn
Loops
Nested Loops

Loops inside loops, oh my! A nested loop represents one loop placed inside the body of another loop which results in a higher dimensions of iterations. This strategy is most often used when we’d like to compare the contents of two different collections/iterators.

Below is an example of nested loops. The outer loop iterates through the range 1..2 and the inner loop iterates through the range 'A'..'C':

for (i in 1..2) { for (j in 'A'..'C') { println("Outer loop: $i - Inner loop: $j") } }

It’s important to understand that for every iteration in the outer loop, the inner loop will run through all of its own iterations.

In the example above, the inner loop iterates 3 times for each of the outer loop’s 2 iterations. Therefore, the println() statement is run 6 times:

Outer loop: 1 - Inner loop: A Outer loop: 1 - Inner loop: B Outer loop: 1 - Inner loop: C Outer loop: 2 - Inner loop: A Outer loop: 2 - Inner loop: B Outer loop: 2 - Inner loop: C

When beginning with nested loops they may seem difficult to work with, but they make advanced applications easy to implement.

Instructions

1.

You’ll be building a grid of rows and columns much like the ones that exist in Google and Excel sheets using nested loops. First start with a single loop.

Create a for loop that contains:

  • i as the loop variable.
  • a range of 1 through 6 as the iterator.
2.

Now you will implement another loop inside the first one.

Inside the first loop body, create a for loop that contains:

  • j as the loop variable.
  • a range of 'A' through 'F' as the iterator.
  • a print() statement that outputs "$j$i ".

The empty space at the end of the String template is used to create a gap between columns which helps us visualize what is happening in the code.

3.

There is now a single line of each loop variable concatenated to each other. The last step will show off the dimensional nature of nested loops.

Outside of the inner loop but still inside of the outer loop:

  • add an empty println() statement.

When you run the code you can now see that each inner loop iteration outputs a column, while each outer loop iteration creates a new row.

Folder Icon

Take this course for free

Already have an account?