for Loop
In this page:
for Loop
A basic for loop, for (i <- 1 to 5) { ... }, iterates over a Range or any collection, running the block once per element. to is inclusive of its endpoint while until excludes it. This simple form is a statement producing Unit, used purely for its side effects like printing.
Note: 1 until 5 excludes 5, while 1 to 5 includes it -- easy to mix up at a glance.
Example: for Loop
object Main extends App {
for (i <- 1 to 5) {
println(s"Count: $i")
}
for (i <- 0 until 3) {
println(s"Zero-based: $i")
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: