Scala – Recursion

  • date 27th April, 2021 |
  • by Prwatech |
  • 0 Comments

Recursion is a strategy that breaks the problem into more modest sub problem and calls itself for every one of the problem. That is, it essentially implies function calling itself. We can utilize recursion rather than loops. Recursion avoids variable state related with loops. Recursion is very basic in practical programming and gives a characteristic method to describe numerous Algorithms. Recursion is considered as to be significant in functional programming. Scala upholds Recursion very well.

use case 1:

// Scala program of factorial using recursion
object prwatech {
def fact(n:Int): Int=
{
if(n == 1) 1
else n * fact(n - 1)
}
// Main method
def main(args:Array[String])
{
    println(fact(4))
}
}

output:

24

use case 2:

// Scala program of GCD using recursion
// Creating object
object eduprwa {
// Function defined
def gcd(a:Int, b:Int): Int=
{
if (b == 1) a
else gcd(b, a % b)
}
// Main method
def main(args:Array[String])
{
    println(gcd(10, 17))
}
}

output

3

use case 3:

// Scala program of sum all numbers
// using recursion
// Creating object
object prwa
{
// Function defined
def sum(num: Int): Int=
{
if (num == 1)
1
else
sum(num - 1) + num
}
// Main method
def main(args:Array[String])
{
    println(sum(15))
}
}

output:

120

Quick Support

image image