🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Nested Loops

A nested loop is a loop placed inside another loop. The inner loop runs in full for every single round of the outer loop.

The inner loop finishes for each outer round

The outer loop picks a row value. The inner loop then prints both column values before the outer loop moves on.

for i in 1:2
    for j in 1:2
        println("$i x $j")
    end
end

A multiplication grid prints row by row

A small function holds the two loops. Each inner round prints one product, and the row ends with a new line.

function showgrid()
    for i in 1:3
        for j in 1:3
            print(i * j)
            if j < 3
                print(" ")
            end
        end
        println()
    end
end
showgrid()

The inner length can follow the outer value

The inner range ends at the outer value i. Each row therefore prints one more star than the row before it.

for i in 1:3
    for j in 1:i
        print("*")
    end
    println()
end

Example

function table()
    for i in 1:4
        for j in 1:4
            print(i * j)
            if j < 4
                print(" ")
            end
        end
        println()
    end
end
table()

Key points

  • Nested loop: a loop written inside the body of another loop.
  • Outer loop: the loop that holds the other loop inside it.
  • Inner loop: the loop that restarts and finishes on each outer round.
  • Rounds multiply: an outer loop of 2 and an inner loop of 3 run the inner body 6 times.
  • Grid: nested loops fit data in rows and columns, such as a multiplication table.

In this example, the function table holds an outer loop over the rows 1 to 4 and an inner loop over the columns 1 to 4. Each inner round prints one product, with a space after it unless it is the last column. After each inner loop ends, println moves to a new line, so the output is a full 4 by 4 multiplication grid.

Note

the inner loop can use the outer loop variable, so its length can change each round.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

An outer loop runs 3 rounds and an inner loop runs 4 rounds. How many times does the inner loop body run in total?