For Loop in Scala

In Scala, for loop is also known as for-comprehensions. A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.
Syntax:

for(w <- range){
// Code..
}

Here, w is a variable, <- operator is known as a generator, according to the name this operator is used to generate individual values from the range, and the range is the value which holds starting and ending values. The range can be represented by using either i to j or i until j.

for loop using to

In for loop, We can use to when We want to print the values from 0 to n. Or in other words, when We use to with for loop it includes both start and end value like as shown in the below program, it prints from 0 to 10 not print from 0 to 9 like in until.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate how to
// create for loop using to 
object Main 
{
    def main(args: Array[String])
    {
        println("The value of w is:");
          
        // Here, the for loop starts from 0 
        // and ends at 10
        for( w <- 0 to 10)
        {
            println(w);
        }
    }
}

chevron_right


Output:

The value of w is:
0
1
2
3
4
5
6
7
8
9
10

for loop using until

In for loop, We can use until when We want to print the value from 0 to n-1. Or in other words, until with for loop it excludes the end value like as shown in the below program, it prints only from 0 to 9 not print from 0 to 10.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate how to
// create for loop using until
object Main 
{
    def main(args: Array[String])
    {
        println("The value of w is:");
          
        // Here, the for loop starts from 0 
        // and ends at 10
        for( w <- 0 until 10)
        {
            println(w);
        }
    }
}

chevron_right


Output:

The value of w is:
0
1
2
3
4
5
6
7
8
9

Multiple values in for-loop

We can also use multiple ranges in single for-loop. These ranges are separated by a semi-colon(;). Let us discuss with the help of an example. In the below example, we use two different ranges into a single loop, i.e, w <- 0 to 3; z<- 8 until 10.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate how to
// create multiple ranges in for loop
object Main
{
    def main(args: Array[String]) 
    {
          
    // for loop with multiple ranges
        for( w <- 0 to 3; z<- 8 until 10 )
        {
            println("Value of w is :" +w);
            println("Value of y is :" +z);
        }
    }
}

chevron_right


Output:

Value of w is :0
Value of y is :8
Value of w is :0
Value of y is :9
Value of w is :1
Value of y is :8
Value of w is :1
Value of y is :9
Value of w is :2
Value of y is :8
Value of w is :2
Value of y is :9
Value of w is :3
Value of y is :8
Value of w is :3
Value of y is :9

Using for-loop with Collections

In Scala, We can use for-loop with collections like List etc. It provides an efficient way to iterate over the collections.
Syntax:

for(i <- List){
// Code..
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate how to
// use for loop with collection
object Main
{
    def main(args: Array[String])
    {
        var rank = 0;
        val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
          
        // For loop with collection
        for( rank <- ranklist){
            println("Author rank is : " +rank);
        }
    }
}

chevron_right


Output:

Author rank is : 1
Author rank is : 2
Author rank is : 3
Author rank is : 4
Author rank is : 5
Author rank is : 6
Author rank is : 7
Author rank is : 8
Author rank is : 9
Author rank is : 10

Using for-loop with Filters

In Scala, for-loop allows you to filter some elements from the given collection using one or more if statements in for-loop.
Syntax:

for(i<- List 
if condition1; if condition2; if condition3; ...)
{
// code..
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate how to
// use for loop with filters
object Main
{
    def main(args: Array[String]) 
    {
        var rank = 0;
        val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
          
        // For loop with filters
        for( rank <- ranklist
        if rank < 7; if rank > 2 )
        {
            println("Author rank is : " +rank);
        }
    }
}

chevron_right


Output:

Author rank is : 3
Author rank is : 4
Author rank is : 5
Author rank is : 6

Explanation: In the above example, the for loop use two filters to filter the given collection. These filters eliminate those ranks which are less than 7 and greater than 2.

Using for-loop with Yeild

In Scala, the return value of the for loop is stored in a variable or may return through a function. To do this you should use yield keyword to prefix the body of for loop.
Syntax:

var output = for{ i<- List
if condition 1; if condition 2; 
} 
yeild i

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to illustrate how to
// use for loop with yields
object Main
{
    def main(args: Array[String])
    {
        var rank = 0;
        val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
          
        // For loop with yields
        var output = for{ rank <- ranklist
                    if rank > 4; if rank != 8 }
                    yield rank
          
        // Display result
        for (rank <- output)
        {
            println("Author rank is : " + rank);
        }
    }
}

chevron_right


Output:

Author rank is : 5
Author rank is : 6
Author rank is : 7
Author rank is : 9
Author rank is : 10

Explanation: In the above example, the output is a variable where all the values of rank are stored in the form of a collection. And the for loop display only those Author’s rank whose rank is greater than 4 and not equal to rank 8.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.