Table of contents
1.
Introduction
2.
For Loop in Scala
2.1.
Using Ranges
2.2.
Using to Keyword
2.3.
Using until Keyword
2.4.
Using Collection
2.5.
Using Maps
2.6.
With Filters
2.7.
With Yield
2.8.
Using by Keyword
2.9.
Having Multiple Values
3.
Guards in For Loop
4.
Frequently Asked Questions
4.1.
What is Scala Programming language?
4.2.
What is the difference between the to and until keywords?
4.3.
What is the use of loops in programming languages?
4.4.
What is the use of filters in a for loop in Scala?
4.5.
What are the different keywords to use with For loop in Scala?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

For Loop in Scala

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A for loop in Scala iterates over a collection of items, such as lists or arrays, executing a block of code for each element. It offers a concise syntax and supports various iteration patterns, including filtering and pattern matching. The for loop enhances code readability and expressiveness, making it a powerful tool for data processing and manipulation in Scala programs.

For loop in Scala

In this article, we will discuss about for loop in Scala in more detail along with some examples.

Also see, Must Do Coding Questions

For Loop in Scala

A For loop in Scala can be used to iterate through the collection of elements and print the steps of instruction multiple times.

Let's see the syntax for the for loop in Scala.

Syntax:

for(x <- range)
{
  	// Statements
}


For example:

var value = Seq(“Soumya”, “Charmi”, “Shruti”)
for(x<- value) {
	println(x)
}


Here, x is any variable, <- operator is known as a "generator"; this is used to generate individual values from the range, and the range holds starting and ending values. We can pass range using the to or until keyword.

It's time to move towards some examples to clarify how the for loop in Scala is implemented.

Using Ranges

In Scala, ranges are represented by the to and until methods, which allow you to create sequences of numbers or characters between a specified start and end point. The to method includes the end value in the range, while the until method excludes it.

Here are examples of using ranges in Scala:

1. Iterating over a range of numbers using the to method:

for (num <- 1 to 5) {
  println(num)  // Outputs: 1, 2, 3, 4, 5
}

 

2. Iterating over a range of numbers using the until method:

for (num <- 1 until 5) {
  println(num)  // Outputs: 1, 2, 3, 4
}

 

3. Specifying a step size:

for (num <- 1 to 10 by 2) {
  println(num)  // Outputs: 1, 3, 5, 7, 9
}

 

4. Creating a range and converting it to a collection:

val numRange = (1 to 5).toList  // Creates a list: List(1, 2, 3, 4, 5)

 

Ranges provide a concise way to generate sequences of numbers in Scala and are commonly used in loops, sequence generation, and other programming tasks.

Using to Keyword

In this example, we will show the use of for loop using the to keyword. In the for loop, if we are using to keyword, then we have to specify the start and the end value. Let's see this in our program mentioned below.

Example:

// Scala program to create a for loop
object Class {  
   def main(args: Array[String]) { 
       // Prints from 1 to 5
        for( x <- 1 to 5 ){  
         println(x);  
      }  
   }  
}  

 

Output:

using to keyword Output

Explanation:

In the above example, the start value inside the for loop is 1 and the end value is 5, So the loop will iterate from 1 to 5 elements, and 5 elements are printed as a result.

Also Read -  Ibegin TCS

Using until Keyword

Here we will use until keyword instead of the to keyword. The major difference between until and to is to include start and end values given in the range, while until excludes the last value of the range. Let's understand the until keyword with the help of an example.

Example:

// Scala program to create a for loop
object Class {  
   def main(args: Array[String]) { 
       // Prints from 1 to 4
        for( x <- 1 until 5 ){  
         println(x);  
      }  
   }  
}  

 

Output:

until keyword Output

Explanation:

As we said, the until keyword excludes the last value of the range, so only four elements are printed instead of five. The until keyword is very useful while iterating an array or string, as the array ranges from 0 to n-1, and until the keyword doesn't exceed to n-1.

Using Collection

In Scala, we can use a for-loop to iterate collections like List, Sequence, etc. It provides an efficient way to iterate over the collections. 

Let's understand the collection in for loop with the help of an example.

Example:

// Scala for loop with Collections
object Class {  
   def main(args: Array[String]) {  
       // Creating a list of 8 integers
        var list = List(5, 6, 7, 8, 9, 10, 11, 12)           
        for( x <- list){                         
            println(x)  
        }            
   }  
}

 

Output:

using Collection Output

Explanation:

In the above-mentioned example, a list of 8 integers is created, and then that list is iterated using a for loop. All the elements in the list are printed as a result.

Using Maps

The difference with iterating over a Map is that the receiver will get a Tuple of two values – the key and the value associated with this key:

Example:

// For loop for Maps
object MyClass {
    def main(args: Array[String]) {
        val mp = Map(1 -> "Hello", "2" -> "Coders")
        for ((key,value) <- mp) {
             println(s"""$key -> $value""")
        }
    }
}


Output:

using Maps Output

Explanation:

Here in the example above we are iterating over the map using a for loop. Println prints the key and value associated with each other.

With Filters

For loop in Scala allows you to filter your data by passing a conditional expression in your for loop. Let's understand Filters in for loop with the help of an example.

Example:

// Scala for loop with Filters
object Class {  
   def main(args: Array[String]) {  
       // For loop with filters
       for( x <- 1 to 20 if x%2==0 ; if x<18 ){  
         println(x);  
      }            
   }  
}


Output:

with Filters Output

Explanation:

In the example mentioned earlier, the for loop uses two filters to filter the range of 1 to 20. These filters eliminate the integers which are odd and more than 18.

With Yield

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

Let's understand the Yield keyword with the help of an example.

Example:

// Scala for loop illustration
object Class {  
   def main(args: Array[String]) {  
       // For loop with yield
        var ret = for( x <- 1 to 15) yield x  
        for(y<-ret){  
            println(y)  
        }            
   }  
}


Output:

with Yield Output

Explanation:

The returned value of the for loop is stored in the ret variable, and the yield keyword is used to return the result of the body of for loop.

Using by Keyword

In Scala, the by keyword is used to skip the iteration. Let's understand by keyword with the help of an example.

Example:

// Scala for loop illustration
object Class {  
   def main(args: Array[String]) {  
       // For loop using by keyword
       for(x<-1 to 20 by 2){  
            println(x)  
        }          
   }  
}


Output:

using by keyword Output

Explanation:

In the above example, the by keyword in the for loop skips all the even iterations.

Having Multiple Values

We can define multiple ranges in a single for loop, and all these ranges are separated using semicolons. Let's understand this in detail using an example.

Example:

// Scala for loop illustration
object Class {  
   def main(args: Array[String]) {  
       // For loop having multiple values
       for( x <- 1 to 4; y<- 7 until 10 )
        {
            println("Value of x is :" +x);
            println("Value of y is :" +y);
        }            
   }  
}


Output:

having Multiple Values Output

Explanation:

In the above example, we use two different ranges in a single loop, i.e., x<- 1 to 4; y<- 7 until 10.

You can also read about mock interview.

Guards in For Loop

Guards in for loop are used to filter out the invalid combinations if there are one set of letters. Let’s see if we don’t use the guard in for loop what all combinations are printed.

Example:

// For loop without guard
object MyClass {
       
    def main(args: Array[String]) {       
        val name = Seq("S", "A", "B")
        for (color < -name) {   
            println(color)
        }  
        for (s1 < -name; s2 < -name; s3 < -name) {   
            print(s "$s1$s2$s3 ")
        }             
    }
}


Output:

Guards in For loop Output

Explanation:

It has printed all possible combinations of letters ‘S’, ‘A’, ‘B’ in a three-letter word, using the Seq we have defined.

And now let's see what will happen if we use the guard in for loop.

// For loop with guard
object MyClass {  
    def main(args: Array[String]) {       
        val name = Seq("S", "A", "B")        
        for {   
            v1 < -name    v2 < -name   
            if v2 != v1    v3 < -name   
            if v3 != v2 && v3 != v1
        } {   
            print(s "$v1$v2$v3 ")
        }   
    }
}


Output:

Guards in For loop Output

Explanation:

As we see, we get the filtered output here as required. We can have as many guards as we want. 

Also check out - YII Framework and Cognizant Eligibility Criteria

Frequently Asked Questions

What is Scala Programming language?

Scala is an object-oriented, high-level programming language that supports the functional programming approach.

What is the difference between the to and until keywords?

In Scala, if we use the to keyword, it includes the last value of the range as well, but if we use until keyword, then the last value of the range is excluded.

What is the use of loops in programming languages?

The loop enables us to perform a number of steps or a block of code or function multiple times without writing it repeatedly.

What is the use of filters in a for loop in Scala?

For loop in Scala allows you to filter your data by passing a conditional expression in your for loop.

What are the different keywords to use with For loop in Scala?

We can use to keyword, until keyword, by keyword, yield keyword, and many more.

Conclusion

Here we come to the end of our article on the topic of for loop in Scala, and we saw different ways of using for loop to iterate over the elements with the help of some examples.

Want to learn more? Refer to the articles below and enhance your skills in the Scala language.

Recommended Articles:

  1. Scala language
  2. Scala and Java
  3. Loops
  4. Scala Interview Questions
  5. What are Loops in Java
     

Check out The Interview guide for Product Based Companies and some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc., on Coding Ninjas Studio.

Also, check out some of the Guided Paths on topics such as Data Structures and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test SeriesInterview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio

Happy learning!

Live masterclass