A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
Welcome to the Fibonacci in Scala page! Here, you’ll find the source code for this program as well as a description of how the program works.
import javax.xml.bind.ValidationException
object TestClass {
def fibonacci_rec(n: Int): Int = {
if (n < 0) {
// If invalid input throw an exception
throw new ValidationException("Index should be positive")
} else if (n == 1 || n == 2) {
// Recursion anchors
return 1
} else {
// Definition of Fibonacci sequence (sum of two previous numbers in the sequence)
return fibonacci_rec(n - 1) + fibonacci_rec(n - 2)
}
}
def main(args: Array[String]): Unit = {
// Takes the first argument and uses it as index
if (args.length == 0) {
println("Please enter an index as an argument")
}
val index = args(0).toInt
println(fibonacci_rec(index))
}
}
Fibonacci in Scala was written by:
If you see anything you’d like to change or update, please consider contributing.
Note: The solution shown above is the current solution in the Sample Programs repository as of Oct 27 2019 19:46:35. The solution was first committed on Oct 25 2019 15:33:55. As a result, documentation below may be outdated.
No ‘How to Implement the Solution’ section available. Please consider contributing.
No ‘How to Run the Solution’ section available. Please consider contributing.