Scala for loops commonly iterate over a range.
The range decides where the loop starts, where it stops, and how it changes:
for (item <- range) {
instruction1
instruction2
...
}
Let's break down each component:
The loop variable takes each value from the range.
The
<-operator connects the loop variable to the range.The range decides which values are visited.
Example:
for (i <- 0 until 4) {
println("Hello world!")
}
// This code prints "Hello world!" on four different lines
Let's break down this code:
The range starts at
0.until 4means the range stops before4.So
itakes the values0,1,2, and3.
This is what the computer does behind the scenes during this loop:
0. Creates and initializes a variable i = 0
1. First iteration:
a. Is i < 4 true? <=> Is 0 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i++ => i = 1
2. Second iteration:
a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i++ => i = 2
3. Third iteration:
a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i++ => i = 3
4. Forth iteration:
a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
b. Run the code inside {}. Print "Hello World".
c. i++ => i = 4
5. Fifth iteration:
a. Is i < 4 true? <=> Is 4 < 4 true? No.
b. Exit the loop.
Assignment
Let's print "I promise to learn coding." 5 times using a for loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.