Scala Loop control statements – while, do while and for loops

Filed Under: Scala

In software programming, certain situations may arise where we need to execute a block of code several times. The loop statements helps in this repetitive tasks and are executed sequentially. Loop control statements include while, do while and for loop. Let’s look into how we use them in Scala programming language.

Scala while loop

A while loop statement is executed repeatedly until the condition is false.

The syntax for while loop is


while(condition) {
	statement
}

The condition can be an expression, boolean value or a non zero value. The statement can be a single statements or a group of statements. When the specified condition becomes false the control is transferred to the next statement outside the loop.

Consider an example below.


object Stu{
 def main(args:Array[String])  {
 var sid = 5 ;
 while(sid < 15 ) {
 println("Student Id is:" +sid);
 sid = sid + 1;
 }
}
}

We are declaring and initializing a variable sid with an initial value of 5. In the while loop the condition if sid less than 15 is checked and the value of id is printed after which sid is incremented. The loop stops when sid is greater than 14

Run the above code by typing Stu.main(null) in scala shell and you will see below output.


Student Id is:5
Student Id is:6
Student Id is:7
Student Id is:8
Student Id is:9
Student Id is:10
Student Id is:11
Student Id is:12
Student Id is:13
Student Id is:14

Scala-while-loop

You can also save the above code in Stu.scala file and run as shown in below image.

Scala-while-loop-program

Scala do while loop

The do while loop statements executes at least once and then the while loop is executed till the condition is true.

The syntax for do-while loop is;


do{
  
 statements;

}while( condition );

The statements enclosing the do loop is executed first and then the while condition is checked.

Consider an example below.


object Stud {
	def main(args:Array[String]) {
	var sid = 4;
	do {
    	println("Student Id is:"+sid);
    	sid = sid + 1
    	}while(sid < 10)
}
}

The value of student id is displayed and the value is incremented by 1 and then the condition in while loop is checked.

Run the above code by typing Stud.main(null) and you will see output as in below image.

scala-do-while-example

Scala for loop

For loop is a repetitive structure which allows us to execute a block of code multiple times similar to the other loops we saw.

Since for loop is widely used, there are various forms of for loop in Scala.

For loop with ranges:

The syntax of for loop is


for(variable <- Range){
   statements
}

Range represents numbers as x to y or x until y. The left arrow operator( <- ) is called generator as it generates individual values from a range. Consider an example below.


object Student {
def main(args:Array[String]) {
	var sid = 0
for (sid <- 6 to 12){
	println(“Student Id is :”+sid)
}
}
}

In this example we are printing student id specifying the range as 6 to 12.

Run the above code as shown in below image with output.

scala-for-loop-example

Alternatively for loop range can also be written as x until y.


object Student {
def main(args:Array[String]) {
	var sid = 0
for (sid <- 9 until 14){
	println("Student Id is :"+sid)
}
}
}

Here we specify range as 9 until 14 so that the values from 9,10,11,12 and 13 will be displayed.


scala> object Student {
     | def main(args:Array[String]) {
     |  var sid = 0
     | for (sid <- 9 until 14){
     |  println("Student Id is :"+sid)
     | }
     | }
     | }
defined object Student

scala> Student.main(null)
Student Id is :9
Student Id is :10
Student Id is :11
Student Id is :12
Student Id is :13

scala> 

Multiple ranges can be specified using semicolon (;) as the separator and the loop iterates for all possible combinations.

For example


object Student {
   def main(args: Array[String]) {
      var id = 0;
      var  marks = 60;
     
      for( id <- 1 to 2; marks <- 70 to 72){
         println( "Student Id is : " + id );
         println( "Marks is : " + marks );
      }
   }
}

Here we are specifying ranges for id and marks together separated by a semicolon.

Run the above code by as shown below.


scala> object Student {
     |    def main(args: Array[String]) {
     |       var id = 0;
     |       var  marks = 60;
     |      
     |       for( id <- 1 to 2; marks <- 70 to 72){
     |          println( "Student Id is : " + id );
     |          println( "Marks is : " + marks );
     |       }
     |    }
     | }
defined object Student

scala> Student.main(null)
Student Id is : 1
Marks is : 70
Student Id is : 1
Marks is : 71
Student Id is : 1
Marks is : 72
Student Id is : 2
Marks is : 70
Student Id is : 2
Marks is : 71
Student Id is : 2
Marks is : 72

For Loop with collections:

for loop can be used efficiently to iterate over collections. The syntax is


for( var a <- List ){
   statement
}

List represents collection having list of all the elements to iterate using for loop.

Consider an example below.


object Student {
def main(args:Array[String]) {
	var marks = 0;
	val Listmarks = List(60,65,70,75,80,85);
	for( m1 <-Listmarks) {
    	println("Marks :"+m1);
}
}
}

Below image shows the output produced by above example.

scala-for-loop-collection-example

for loop with Filters

Some elements can be filtered in the for loop using if statements.

The syntax is;


for( var a <- List
      if condition1; if condition2...
   ){
   statement;
}

For example;


object Student {
 def main(args:Array[String]) {
 var id = 0;
 val Listid = List(4,5,6,7,8,9,10,11,12);
 for(id <- Listid
     if id > 6; if id !=11 ) {
     println("Id:"+id);
}
}
}

Here we are using filter conditions as id greater than 6 and id not equal to 11.

Run the above code by and you will see output as shown below.


scala> Student.main(null)
Id:7
Id:8
Id:9
Id:10
Id:12

for loop with yield:

The return values can be stored in a variable or can be returned through a function. To do this use the keyword yield as


var result = for{ var i <- List
     if condition1; if condition2...
}yield i

For example;


object Student {
 def main(args:Array[String]) {
 var id =0;
 val Listid = List(4,5,6,7,8,10);
 var result = for{ id <- Listid
           if  id <9; if id !=7
 }yield id

for(id <- result) {
 println("Student Id:"+id);
}
}
}

The value of id is stored in the variable id using the keyword yield. Below image shows the output produced.

scala-for-loop-yield-example

That’s all for loop control statements in Scala programming, we will look into more Scala features in coming posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages