w3resource

Scala control flow program: Print Fibonacci series with while loop

Scala Control Flow Exercise-5 with Solution

Write a Scala program to print the Fibonacci series up to a given number using a while loop.

Sample Solution:

Scala Code:

object FibonacciSeries {
  def main(args: Array[String]): Unit = {
    val limit: Int = 20 // Print the Fibonacci series

    var num1: Int = 0
    var num2: Int = 1

    println(s"Fibonacci Series upto $limit:")
    print(s"$num1 $num2")

    var sum: Int = num1 + num2
    while (sum <= limit) {
      print(" " + sum)

      num1 = num2
      num2 = sum
      sum = num1 + num2
    }
  }
}

Sample Output:

Fibonacci Series upto 20:
0 1 1 2 3 5 8 13

Explanation:

In the above exercise -

  • First, we define a variable "limit" and assign it a value (20 in this case) that represents the upper limit up to which we want to print the Fibonacci series. We initialize variables "num1" and "num2" as 0 and 1 respectively, which are the first two numbers of the Fibonacci series.
  • We print the initial values of "num1" and "num2" using println. Then, inside the while loop, we calculate the next Fibonacci number by adding "num1" and "num2", and store it in the variable sum. We print the sum and update num1 and num2 values for the next iteration. The loop continues until the sum exceeds the "limit".

Scala Code Editor :

Previous: Find a factorial with a while loop.
Next: Multiplication table using a for loop.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/control-flow/scala-control-flow-exercise-5.php