A Scala factorial recursion example

I'm actually on vacation this week, but last night I showed a friend how to write software in Scala. He's familiar with recursion, so we jumped right into a simple factorial recursion example:

object FactorialRecursion {

  def main(args: Array[String]) {
    println(factorial(5))
  }

  def factorial(n: Int): Int = {
    if (n == 0) 
      return 1
    else
      return n * factorial(n-1)
  }
}

Since I'm on vacation this week I won't take the time to explain this, but I'll provide this hint, that shows how to factorial function works for each number:

/**
 * 5 * factor(4) = 5 * 24 = 120
 * 4 * factor(3) = 4 * 6 = 24
 * 3 * factor(2) = 3 * 2 = 6
 * 2 * factor(1) = 2
 */

Post new comment

The content of this field is kept private and will not be shown publicly.