Scala - Loop Statements Example

1. Introduction

Loop statements are fundamental constructs in programming languages, enabling the execution of a sequence of statements multiple times. Scala offers several loop constructs, including while, do-while, and for loops, each serving different purposes based on the use-case requirements. This blog post aims to elucidate Scala's loop statements and illustrate their usage with examples.

Scala - Loop Statements

- while loop: Repeatedly executes a target statement as long as a given condition is true.

- do-while loop: Similar to the while loop, but it guarantees to execute the loop body at least once before checking the condition.

- for loop: Scala's for loop is powerful and flexible. It can iterate over a range or collection and is capable of iterating with conditions and generating new collections.

2. Program Steps

1. Describe each loop type with an example.

2. Define a condition or range for the loops.

3. Implement the loop logic to demonstrate iteration.

4. Execute the code to verify the functionality of each loop type.

3. Code Program

object LoopDemo extends App {
  // while loop example
  var counter = 5
  println("while loop output:")
  while (counter > 0) {
    print(counter + " ")
    counter -= 1
  }

  // do-while loop example
  var doCounter = 5
  println("\ndo-while loop output:")
  do {
    print(doCounter + " ")
    doCounter -= 1
  } while (doCounter > 0)

  // for loop example
  println("\nfor loop output:")
  for (i <- 1 to 5) {
    print(i + " ")
  }

  // for loop with conditions and yield
  println("\nfor loop with condition and yield:")
  val evenNumbers = for { i <- 1 to 10 if i % 2 == 0 } yield i
  println(evenNumbers)
}

Output:

while loop output:
5 4 3 2 1
do-while loop output:
5 4 3 2 1
for loop output:
1 2 3 4 5
for loop with condition and yield:
Vector(2, 4, 6, 8, 10)

Explanation:

1. while loop: We initialize counter to 5 and create a while loop that prints and decrements counter until it is no longer greater than 0. The loop prints the numbers in descending order.

2. do-while loop: doCounter starts with the same value as counter. The do-while loop ensures that the body is executed once, printing the numbers in descending order, similar to the while loop.

3. for loop: We define a for loop that iterates over a range from 1 to 5. This loop prints numbers from 1 to 5 in ascending order.

4. for loop with conditions and yield: A more complex for loop that iterates from 1 to 10, but only yields even numbers, resulting in a Vector of these numbers. yield generates a new collection containing only the elements that meet the if condition specified.


Comments