Scala for loop with examples

 238 total views,  1 views today

Welcome to Scala series. In this tutorial, you will learn Scala for loop with examples.

Syntax

for(arg  <- collection) code.....

Scala Iterate a range using for loop

def main(args: Array[String]) {
   
   //To print from 1 to 5
   for (i <- 1 to 5) {
     println(i)
   }
   
}

Output

1
2
3
4
5

The above code iterates from 1 to 5.

Scala Iterate a range in reverse order using for loop

def main(args: Array[String]) {
    //To print from 5 to 1
    for (i <- 5 to 1) {
      println(i)
    }
  }

NO Output

The above code does not print because by default increment is one and If you want to print from 5 to 1. You have to do it as below.

def main(args: Array[String]) {
    //To print from 5 to 1
    for (i <- 5 to 1 by -1) {
      println(i)
    }
  }

Output

5
4
3
2
1

The above code loops the range in reverse order. It decrements the range by 1.

More Examples of Scala for loop

To decrement range by 2

for (i <- 5 to 1 by -2) println(i)
Output
5
3
1

To decrement range by 3

for (i <- 5 to 1 by -3) println(i)
Output
5
2

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!.