🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Nested Loops

A nested loop is a loop placed inside another loop. The inner loop finishes all its rounds for each single round of the outer loop.

The inner loop finishes before the outer loop moves

The first value stays at 1 for three prints before it turns to 2. That order proves the inner loop finished its full run first.

@main def main(): Unit =
  for row <- 1 to 2 do
    for col <- 1 to 3 do
      println(s"$row-$col")

Nested loops build a growing pattern

The inner loop runs as many times as the row number. Each row prints one more star than the row before it.

@main def main(): Unit =
  for row <- 1 to 3 do
    for col <- 1 to row do
      print("*")
    println()

A small grid prints row by row

The inner loop prints one row of products with spaces between them. The println after it ends the row and starts a fresh line.

@main def main(): Unit =
  for row <- 1 to 2 do
    for col <- 1 to 3 do
      if col > 1 then
        print(" ")
      print(row * col)
    println()

Example

@main def main(): Unit =
  for row <- 1 to 3 do
    for col <- 1 to 3 do
      if col > 1 then
        print(" ")
      print(row * col)
    println()

Key points

  • Nested: nested means one thing placed inside another thing.
  • Outer loop: the outer loop is the loop written on the outside.
  • Inner loop: the inner loop is the loop written inside the outer loop body.
  • Full inner run: the inner loop runs from start to end before the outer loop moves on.
  • Total rounds: the inner body runs the outer count times the inner count.
  • Rows and columns: nested loops often print grids, with the outer loop for rows and the inner loop for items in a row.

In this example, the outer loop picks the row from 1 to 3, and the inner loop picks the column from 1 to 3. Each inner round prints the product of row and column, with a space before every value after the first. The println at the end of the outer round moves printing to a new line, so the grid has three rows.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

An outer loop runs 3 times and its inner loop runs 4 times. How many times does the innermost line run?