Lesson 10 of 15

For Loops

For Loops

Scala's for loop iterates over ranges or collections:

for (i <- 1 to 5) {
  println(i)
}
// 1 2 3 4 5

Use until for exclusive end:

for (i <- 0 until 3) {
  println(i)
}
// 0 1 2

Iterate over a List

val fruits = List("apple", "banana", "cherry")
for (fruit <- fruits) {
  println(fruit)
}

Your Task

Write a function sumTo(n: Int): Int that uses a for loop and a mutable variable to sum all integers from 1 to n (inclusive).

JS Transpiler loading...
Loading...
Click "Run" to execute your code.