Scala Iterate Over an Array

1. Introduction

Iterating over arrays is a common task in programming. Scala, with its functional programming features, offers multiple ways to iterate over arrays, each with its own use case and advantages. In this blog post, we'll explore various methods to iterate over an array in Scala, from basic loops to functional programming concepts.

2. Program Steps

1. Define an array to iterate over.

2. Demonstrate different methods of iteration including traditional for loop, foreach, map, and more advanced methods like foldLeft.

3. Print results of each iteration method.

3. Code Program

object ArrayIterationDemo extends App {
  val numbers = Array(1, 2, 3, 4, 5)

  // Traditional for loop
  println("Using traditional for loop:")
  for (number <- numbers) {
    println(number)
  }

  // Using foreach
  println("\nUsing foreach:")
  numbers.foreach(println)

  // Using map
  println("\nUsing map to square each number:")
  val squaredNumbers = numbers.map(x => x * x)
  squaredNumbers.foreach(println)

  // Using foldLeft
  println("\nUsing foldLeft to calculate sum:")
  val sum = numbers.foldLeft(0)(_ + _)
  println(sum)

  // Using zipWithIndex
  println("\nUsing zipWithIndex:")
  numbers.zipWithIndex.foreach { case (number, index) =>
    println(s"Index $index is $number")
  }
}

Output:

Using traditional for loop:
1
2
3
4
5
Using foreach:
1
2
3
4
5
Using map to square each number:
1
4
9
16
25
Using foldLeft to calculate sum:
15
Using zipWithIndex:
Index 0 is 1
Index 1 is 2
Index 2 is 3
Index 3 is 4
Index 4 is 5

Explanation:

1. The traditional for loop iterates over each element in the numbers array, printing them one by one.

2. The foreach method applies a given function (in this case, println) to each item in the array.

3. The map method transforms each element in the array (squares them here) and returns a new array.

4. foldLeft is used to aggregate the elements in the array, calculating the sum in this instance.

5. zipWithIndex pairs each element with its index, allowing iteration over both elements and their indices.


Comments