OneCompiler

Loops

For

For loop is used to iterate a set of statements based on a condition, in short it is used to iterate, filter and return an iterated collection.

Syntax

for(var <- range){  
//code  
} 

Example

object Loops {
	def main(args: Array[String]): Unit = {
	   for( x <- 1 to 10 ){  
       println(x);  
	   }
	}
}

Try Yourself here

Using until keyword

object Loops {
	def main(args: Array[String]): Unit = {
	   for( x <- 1 until 10 ){  
       println(x);  
	   }
	}
}

Try Yourself here

For loop filtering

object Loops {
	def main(args: Array[String]): Unit = {
	   for( x <- 1 until 10 if x % 2 != 0){  
       println(x);  
	   }
	}
}

Try yourself here

For loop for collections like lists, sequence etc

object Loops {
	def main(args: Array[String]): Unit = {
	 var l = List(10,20,30,40,50)  
   for( i <- l){             
      println(i)  
   }  
	}
}

Try yourself here

While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

Syntax

while(condition){  
//code 
}  

Example

object Loops {
	def main(args: Array[String]): Unit = {
  	 var i : Int = 1;
     while ( i <= 10) {
        println(i);
        i = i+1;
     }

	}
}

Try Yourself here

Do-while

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

Syntax

do{  
//code 
}while(condition); 

Example

object Loops {
	def main(args: Array[String]): Unit = {
	    var i : Int = 1;
      do {
        println(i);
        i = i+1;
      } while (i<=10);
    
	}
}

Try Yourself here