Scala program to find the Fibonacci series

1. Introduction

The Fibonacci series is a sequence of numbers in which each number after the first two is the sum of the two preceding ones. Often represented as: 0, 1, 1, 2, 3, 5, 8, ... and so on. In this blog post, we'll explore a Scala program that generates the Fibonacci series up to a given number.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to hold the main function.

3. Define a recursive function fibonacci to calculate Fibonacci series.

4. Within the main function, iterate to the desired number and print each Fibonacci number.

5. Run the program.

3. Code Program

object FibonacciApp {
  def main(args: Array[String]): Unit = {
    val terms = 10  // number of terms to print
    println(s"Fibonacci series of $terms terms:")

    // Print the Fibonacci series
    for(i <- 0 until terms) {
      println(fibonacci(i))
    }
  }

  // Recursive function to find Fibonacci of a number
  def fibonacci(n: Int): Int = {
    if (n <= 1) n
    else fibonacci(n-1) + fibonacci(n-2)
  }
}

Output:

Fibonacci series of 10 terms:
0
1
1
2
3
5
8
13
21
34

Explanation:

1. The program starts with an object named FibonacciApp. In Scala, the main method, which is the entry point of the program, resides inside an object.

2. We've defined a recursive function fibonacci that calculates the Fibonacci number for a given position n. If n is 0 or 1, it returns n as Fibonacci numbers. For other values of n, it returns the sum of Fibonacci of n-1 and n-2.

3. In the main function, we've specified we want to print the first 10 terms of the Fibonacci series. We use a loop to iterate 10 times, and for each iteration, we calculate and print the Fibonacci number.

4. The program prints the Fibonacci series for the specified number of terms when executed.


Comments