A for loop is a special type of loop in Scala which allows us to loop over the items of a collection, such as an array.
Looping through an array:
For example, an array is a sequence of items, so we can use a for loop to iterate over each item and do something with it:
val fruits = Array("banana", "orange", "pear", "kivi")
for (fruit <- fruits) {
println("I eat " + fruit)
}
The output of this code is:
I eat banana
I eat orange
I eat pear
I eat kivi
Let's break down this code:
- The
forkeyword that indicates the start of aforloop. fruitis the loop variable. It will take the value of each different item in the collection- The
<-separates the loop variable from the collection we will iterate on fruitsis the collection to loop over
Assignment
Now let's greet our friends using a for loop!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check