Course Content
Introduction to Scala
Introduction to Scala
Iterating in Arrays
Whenever you want to process certain or all elements of an array or fill the array with elements, loops are always there to help you. Instead of dealing with each element manually one by one and writing tons of lines of code, especially for large arrays, you can simply use a for loop.
Iterating Over Indices
The first approach to iterate over an array is to iterate over its indices. Remember the length
property of an array? We'll make use of it here. Let's first take a look at the for loop with until:
Main
object Main { def main(args: Array[String]): Unit = { var charArray = Array('a', 'b', 'c', 'd', 'e') for (i <- 0 until charArray.length) { println(charArray(i)) } } }
We just print all the elements of the array of Char
elements one by one by iterating over the indices of this array. Our loop variable i
starts from 0
to the length of the array exclusive, or to the length - 1 inclusive which is the index of the last element.
Let's now take a look the same example, but instead of until
we'll useto
:
Main
object Main { def main(args: Array[String]): Unit = { var charArray = Array('a', 'b', 'c', 'd', 'e') for (i <- 0 to charArray.length - 1) { println(charArray(i)) } } }
Since to
includes the end value, we use length - 1 here which is index of the last element.
Iterating Over Elements
As we have mentioned previously, a for loop also allows to iterate over elements in a collection. So its range
becomes simply the array over the elements of which we want to iterate.
Let's modify our previous example to illustrate this:
Main
object Main { def main(args: Array[String]): Unit = { var charArray = Array('a', 'b', 'c', 'd', 'e') for (element <- charArray) { println(element) } } }
Here, at each iteration the value of the current element is assigned to our element
variable. This approach is often a preferred one than the two above.
Moreover, we can iterate over the indices of the array in a more concise way by accessing the array indices using the indices
property:
Main
object Main { def main(args: Array[String]): Unit = { var charArray = Array('a', 'b', 'c', 'd', 'e') for (i <- charArray.indices) { charArray(i) = (charArray(i) + 1).toChar println(charArray(i)) } } }
In this example, we add 1
to the encoding of each Char
of our array and convert the resulting encoding back to Char
. In a way, we simply shift each letter by one to the right. Once again, Iterating over the elements directly wouldn't allow us to change the elements and raise an error.
Thanks for your feedback!