Scala program to find factorial of a number

1. Introduction

Finding the factorial of a number is a fundamental problem in computing and mathematics. The factorial of a number n is the product of all positive integers less than or equal to n. In Scala, we can compute the factorial using recursion.

2. Program Steps

1. Create an object to hold the main function.

2. Define a recursive function factorial that takes an integer n.

3. If n is 0, the factorial is 1.

4. Else, multiply n with the factorial of n-1.

5. Call the function with the desired input and print the result.

3. Code Program

object FactorialApp {
  def main(args: Array[String]): Unit = {
    val number = 5
    println(s"The factorial of $number is: ${factorial(number)}")
  }

  // Recursive function to find factorial of a number
  def factorial(n: Int): Int = {
    if (n == 0) 1
    else n * factorial(n - 1)
  }
}

Output:

The factorial of 5 is: 120

Explanation:

1. The program starts with defining an object FactorialApp that houses the main function.

2. Within this object, a recursive function factorial is defined. The base condition of recursion is when n is 0, it returns 1.

3. For any other number, it multiplies the number with the factorial of the preceding number (n-1).

4. In the main function, we've chosen 5 as the number whose factorial we want to determine. The result is printed on the console.


Comments