Scala

24 / 53

Scala - Loop Statements Examples

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:

  • while loop Repeats a statement or group of statements as long as a given condition is true. It tests the condition before executing the loop body.
  • do-while loop Same as a while statement, except that it tests the condition at the end of the loop body.
  • for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
    One way to run a 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 );
      }
   }
}

No hints are availble for this assesment

Answer is not availble for this assesment

Loading comments...