w3resource

Scala control flow program: Print Fibonacci series with while loop


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


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • Variables in Scala: Knowledge of declaring and initializing variables using var for mutable values.
  • While Loops: Understanding how to use while loops for repetitive tasks.
  • Arithmetic Operations: Ability to perform addition and update variables during program execution.
  • Fibonacci Series Concept: Awareness of how each number in the series is the sum of the two preceding numbers.
  • Printing Output: Familiarity with the print() and println() functions to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Main Object: Create an object with a main method, which serves as the entry point of the program.
  • Initialize Variables: Declare variables to store the first two numbers of the Fibonacci series (0 and 1) and another variable to calculate the next number in the series.
  • Print Initial Numbers: Display the first two numbers of the series before entering the loop.
  • Use a While Loop: Use a while loop to calculate and print subsequent numbers in the series until the limit is reached.
  • Update Variables: Update the variables to hold the last two numbers of the series for the next iteration.
  • Display the Output: Use print() to display the Fibonacci series in a readable format, ensuring numbers are separated by spaces.
  • Test with Different Limits: Change the value of the limit to verify the program works for various cases, including small and large numbers.

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?



Follow us on Facebook and Twitter for latest update.