Home »
Scala
Recursion function in Scala
By IncludeHelp Last updated : October 10, 2024
Recursion function
Recursion function is a function that calls itself again and again until a specific condition becomes true. In functional programming, recursion plays a big role and being a functional programming language Scala also supports recursion function.
How does Recursion function work?
So, Recursion function is calling the same block of code again till the end condition becomes true. Most programs that require adding or doing some specific calculations multiple times use recursion. It is a better choice instead of an infinite while loop that need a break condition. In Scala break is prone to exceptions and programming is a little bit tricky so it is good to practice to use recursion function in place of it.
Syntax
def recFun(arguments){
if(condition )
return value
else
return argument * recFun(next_arguments)
}
Syntax explanation
Here the recFun is a recursion function that uses a set of arguments. These set of arguments are mostly a single argument that is an integer that is to be used for calculation. Then in the body of the function, there is an if condition that is used to check whether to recall the recursion function or not. For TRUE value of the condition the final return is executed and the code flow goes back to the calling block of code. For FALSE value the condition calls the recursion function again doing the task specified (here we have used * ) by the program.
Example 1: Print Factorial of a number using Recursion in Scala
object myClass {
def factorial(n: BigInt): BigInt = {
if (n == 1)
1
else
n * factorial(n - 1)
}
def main(args: Array[String]) {
println( "Factorial of " + 25 + ": = " + factorial(25) )
}
}
Output
Factorial of 25: = 15511210043330985984000000
Example explanation
The above code is to print the factorial of a number. Since factorial may take huge values, we have used BigInt for the result. To avoid overflow condition. This increase the memory of the code but is important as the factorial of 25 as an example will result in an error if Int would be used as a datatype.
Example 2: Print Fibonacci of a number using Recursion in Scala
object myClass {
def fibonacci(previous1 : Int, previous2 : Int , counter : Int , condition : Int ){
print( ", "+(previous1 + previous2))
if((counter+1) < condition){
fibonacci(previous2, (previous1 + previous2), (counter+1) , condition)
}
}
def main(args: Array[String]) {
println( "Fibonacci series till " + 15 + ": = ")
print("0 , 1")
fibonacci(0,1,2,15)
}
}
Output
Fibonacci series till 15: =
0 , 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377