← Back to Scala Course | Chapter 4: Control Flow | Lesson 3 of 7

for Loop

In this page:

  1. for Loop

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

markup
object Main extends App {
  for (i <- 1 to 5) {
    println(s"Count: $i")
  }

  for (i <- 0 until 3) {
    println(s"Zero-based: $i")
  }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.