Iterate an array in Scala using ‘for loop’ and foreach

 220 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn how to iterate an array in Scala using for loop and foreach.

Let us create an array.

 var arr = Array(1,2,3,4,5,6)

Iterate an array using for loop in Scala

def main(args: Array[String]) {

  var arr = Array(1, 2, 3, 4, 5, 6)

  for (i <- arr) {
    println(i)
  }

}

Output

1
2
3
4
5
6

Iterate an array in reverse using for loop in Scala

 def main(args: Array[String]) {

    //Iterate i reverse
    var arr = Array(1, 2, 3, 4, 5, 6)
    for (i <- arr reverse) {
      println(i)
    }

  }

Output

6
5
4
3
2
1

Iterate an array using foreach in Scala

 def main(args: Array[String]) {

    var arr = Array(1, 2, 3, 4, 5, 6)
    arr.foreach(println)

  }

Output

1
2
3
4
5
6

References : Scala Documentation

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.