Hey there!

Welcome to ** ClearUrDoubt.com**.

In this post, we will look at a Scala program to print Fibonacci series using Tail Recursion.

Fibonacci Series: Finding n’th element: f(n) = f(n-1) + f(n-2)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.clearurdoubt object Fibonacci extends App { def fibonacci(n: Int): Int = { def fibonacci(n: Int, a: Int, b: Int): Int = n match { case 0 => a case _ => print(a + " "); fibonacci(n-1, b, a+b) } fibonacci(n, 0, 1) } fibonacci(10) } |

Output:

The inner function fibonacci() is a tail recursive function as it has its own function call as it’s last action.

Happy learning.

Please leave a reply in case of any queries.