Start learning free

LESSON 192 OF 348 · NESTED LOOPS & BRUTE FORCE

Nested loops in Scala in Scala

Lesson

A nested loop has one loop inside of another. These are typically used for working with two dimensions such as printing stars in rows and columns as shown below. When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

Example:

for (row <- 0 until 3) {
	for (col <- 0 until 5) {
		print("*")
	}
    println()
}

// This code prints a rectangle with 3 rows and 5 columns, filled with '*'

Iterating through multidimensional arrays

Nested loops are also helpful when we want to iterate through a multi dimensional array, for example:

val arr = Array(Array(1, 2), Array(3, 4), Array(5, 6))

for (i <- arr.indices) {
	for (j <- arr(i).indices) {
		println(arr(i)(j))
	}
}

This outputs each sub-element in arr one at a time. Note that for the inner loop, we are using the indices of arr(i), since arr(i) is itself an array.

Breaking nested loops

Scala does not have a built-in break. A common beginner-friendly approach is to put the work behind an if condition:

val arr = Array(Array(1, 2), Array(3, 4), Array(5, 6))

for (i <- arr.indices) {
	for (j <- arr(i).indices) {
		if(arr(i)(j) != 3 && arr(i)(j) != 4) {
			println(arr(i)(j))
		}
	}
}

// prints the numbers 1, 2, 5 and 6 on different lines

When the value is 3 or 4, the body of the if does not run, so those values are skipped.


Assignment
Follow the Coding Tutorial and let's write some nested loops.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    Nested Loops in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free