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:
Syntax
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
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
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
- Using
1 to 5and expecting the last number to be excluded, whentoincludes 5 anduntilexcludes it. - Using
for (i = 0; i < 5; i++)C-style syntax, which does not exist in Scala; usefor (i <- 0 until 5). - Trying to change the loop variable inside the body, when
iis avaland cannot be reassigned.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: