Course Content
Introduction to Scala
Introduction to Scala
For Loop
What is a For Loop?
For loop in Scala provides a powerful way to iterate over a range of values or elements in a collection. It is especially useful when the number of iterations is known beforehand.
Let's now take a look at the general syntax of such a loop:
Main
for (variable <- Range) { // Code to be executed }
The Range
here can be a sequence of numbers, typically represented as i to j
or i until j
, where i
is the starting value for our variable
(loop variable) and j
is the end value. Both i
and j
are iterators.
The "left arrow" <-
made of <
and -
symbols, used in the syntax of a for loop, is called a generator. It is so named because it generates individual values from the specified range or collection. As you can see, the loop variable is declared as part of the for
expression and can only be used within the loop. Once the loop completes, it is not accessible outside the loop.
Examples
Let's first take a look at an example where we print integers from 1
to 5
inclusive using a for loop:
Main
object Main { def main(args: Array[String]): Unit = { for (i <- 1 to 5) { println(i) } } }
Here, i
is our loop variable which goes from 1
to 5
inclusive (since we use to
), and at each iteration we print the value of i
.
Now let's recreate our countdown example using a for loop with until
instead of to
:
Main
object Main { def main(args: Array[String]): Unit = { for (i <- 10 until 0 by -1) { println(i) } } }
Our loop variable named i
here goes now from 10
to 0
exclusive with step equal to -1
, so it goes to 1
inclusive.
The by
clause is used in for loops to specify the iteration step (1
by default), so via setting it to -1
we ensured that each next value is equal to the previous value - 1.
Here is another example where we will print every third number starting from 1
:
Main
object Main { def main(args: Array[String]): Unit = { for (i <- 1 to 19 by 3) { println(i) } } }
Our step is now equal to 3
and since we used to
instead of until
, 19
is also printed.
Nesting in Loops
Loops in Scala are indeed a powerful tool. They allow for the implementation of complex logic through nested loops, conditionals within loops, and even loops within conditional statements. The nesting itself can be arbitrarily deep.
Let's take a look at an example:
Main
object Main { def main(args: Array[String]): Unit = { var i = 1 while (i < 5) { println("i = " + i) // Prints i at every iteration if (i == 4) { println("Last iteration") // Prints this message only if i == 4 } else { for (j <- 0 to i) // nested for loop println(" j = " + j) // Prints every j from 0 to i inclusive } i += 1 } } }
As you can see, here we have an if-else statement nested inside the while loop, and a for loop nested in the else statement.
Thanks for your feedback!