Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left
Apply NowLogin using Social Account
     Continue with GoogleLogin using your credentials
Loop statements are used to run a program code in a loop which can break or continue subject to certain conditions.
Scala has 3 types of loop statements:
for loop
is using the left-arrow operator. The left-arrow ? operator is called a generator, so named because it's generating individual values from a range.Example 1:
object Hello {
def main(args: Array[String]) {
// Local variable declaration:
var a = 5;
// while loop execution
while( a < 10 ){
a = a + 1;
println( "Value of a: " + a );
}
}
}
Example 2:
object Hello {
def main(args: Array[String]) {
// Local variable declaration:
var a = 5;
// do loop execution
do {
a = a + 1;
println( "Value of a: " + a ); }
while( a < 10 )
}
}
Example 3:
object Hello {
def main(args: Array[String]) {
var a = 0;
// for loop execution with a range
println("Loop 1 - simple loop")
for( a <- 1 to 5){
println( "Value of a: " + a );
}
println("Loop 2 - loop with custom incremental value")
for( a <- 1 to 10 by 2){
println( "Value of a: " + a );
}
println("Loop 3 - loop in reverse, decreasing order")
for( a <- 5 to 1 by -1){
println( "Value of a: " + a );
}
println("Loop 4 - loop using until, one iteration less than simple loop")
for( a <- 5 until 1 by -1){
println( "Value of a: " + a );
}
println("Loop 5 - loop over collections")
val myList = List(1,2,3,4,5);
for( a <- myList ){
println( "Value of a: " + a );
}
println("Loop 6 - loop over multiples ranges, loop within loop")
for( a <- 1 to 5; b <- 1 to 3){
println( "Value of a: " + a );
println( "Value of b: " + b );
}
}
}
Taking you to the next exercise in seconds...
Want to create exercises like this yourself? Click here.
No hints are availble for this assesment
Answer is not availble for this assesment
Loading comments...