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

for Loop

A for loop goes through a set of values one at a time, like counting from one to five on your fingers. The variable takes each value in turn.

In this page:

  1. for Loop
Syntax
scala
for (i <- start to end) {
  // body
}

for (item <- collection) {
  // body
}

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")
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using 1 to 5 and expecting the last number to be excluded, when to includes 5 and until excludes it.
  2. Using for (i = 0; i < 5; i++) C-style syntax, which does not exist in Scala; use for (i <- 0 until 5).
  3. Trying to change the loop variable inside the body, when i is a val and cannot be reassigned.
🔒

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.