how loop in scala

To loop in Scala, you can use various constructs such as for loops, while loops, and recursion. Here's an example of each:

For loop:

for (i <- 1 to 5) {
  println(s"Value of i: $i")

In this example, the for loop iterates from 1 to 5, and for each iteration, it prints the value of i.

While loop:

var i = 1
while (i <= 5) {
  println(s"Value of i: $i")
  i += 1

In this example, the while loop continues as long as the condition i <= 5 is true. It prints the value of i and increments it by 1 in each iteration.


def printNumbers(n: Int): Unit = {
  if (n > 0) {
    println(s"Value of n: $n")
    printNumbers(n - 1)


In this example, the printNumbers function is defined to recursively print the value of n and call itself with n - 1 until n becomes 0.

These are the basic constructs you can use to loop in Scala. Depending on your specific use case, you can choose the most appropriate loop construct.