Loops in Scala

    1. For Loop

    For loop is used to do some operations for repeated iterations. In Scala, the for loop is also called comprehension.

    Syntax:

    for(expression/condition) {
        // statements
    }

    Example:

    val x = List(1,2,3,4,5)
    
    val result1: Unit = for (element <- x) {
     element * 2
    }
    
    print(result1)
    
    val result2: List[Int] = for(element <- x) yield (element*2) 
    print(result2)

    Note: In the above example, we can see that expressions without yield do not result in a value. We should avoid writing such code because that will lead to side effects.

    Output:

    val x: List[Int] = List(1, 2, 3, 4, 5)
    val result1: Unit = ()
    ()
    val result2: List[Int] = List(2, 4, 6, 8, 10)
    List(2, 4, 6, 8, 10)

    Here are a few more examples of the For loop:

    val result3: Seq[Int] = for(element <- 0 until 10) yield (element*2)
    print(result3)
    
    val result4: Seq[Int] = for(element <- 0 to 10) yield (element*2)
    print(result4)

    Output:

    val result3: Seq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)
    Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18)
    
    val result4: Seq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
    Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

    2. While Loop

    While writing some piece of code, there might be chances that we want to execute a loop till the time a particular condition is met. In such scenarios, a while loop can be used.

    Syntax :

    while(expression/condition) {
       //statements
    } 

    Example :

    var count = 10
    
    while(count > 0) {
     print(count + "  ")
     count -= 1
    }

    Output:

    var count: Int = 10
    10  9  8  7  6  5  4  3  2  1

    3. Do-While Loop

    Syntax:

    do {
       //statements
    } while (expression/condition)

    Example:

    var count = 10
    
    do {
     print(count + "  ")
     count -= 1
    } while (count > 0)

    Output:

    var count: Int = 10
    10  9  8  7  6  5  4  3  2  1

    Note :  We don’t use while and do-while loops in Scala because they do not return a value.