In this tutorial, we will learn how to calculate the factorial of a number using recursion in Swift. We will understand the concept of recursion, write an algorithm for calculating factorial, and implement the solution step by step with a complete Swift program.


What is Factorial?

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. For example:

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 3! = 3 × 2 × 1 = 6
  • 0! = 1 (by definition)

Factorials are widely used in mathematics, especially in combinatorics, probability, and algebra.


What is Recursion?

Recursion is a technique in which a function calls itself to solve smaller instances of the same problem. A recursive function must have a base case to terminate and a recursive case that breaks the problem into smaller parts.

To calculate the factorial of a number using recursion:

  1. Base Case: If n is 0 or 1, return 1 because 0! = 1 and 1! = 1.
  2. Recursive Case: Multiply n by the factorial of n - 1 (i.e., n × factorial(n - 1)).

Step-by-Step Implementation in Swift

1. Define the Base Case

Create a function that returns 1 when n is 0 or 1. This ensures the recursion terminates:

</>
Copy
func factorial(_ n: Int) -> Int {
    if n == 0 || n == 1 {
        return 1 // Base case: factorial(0) and factorial(1) are 1
    }
    return 0 // Placeholder for recursive case
}

2. Add the Recursive Case

Add logic to call the factorial function recursively for n - 1:

</>
Copy
func factorial(_ n: Int) -> Int {
    if n == 0 || n == 1 {
        return 1 // Base case
    }
    return n * factorial(n - 1) // Recursive case
}

Explanation:

  • factorial(_ n: Int): Defines a recursive function that calculates the factorial of n.
  • if n == 0 || n == 1: Stops the recursion when n is 0 or 1, returning 1 as the result.
  • n * factorial(n - 1): Recursively calls the factorial function for n - 1 and multiplies the result by n.

3. Test the Function

Let’s test the function with some example inputs:

</>
Copy
// Test cases
print("Factorial of 5: \(factorial(5))") // Output: 120
print("Factorial of 3: \(factorial(3))") // Output: 6
print("Factorial of 0: \(factorial(0))") // Output: 1

Complete Swift Program

Here’s the complete Swift program to calculate the factorial of a number using recursion:

</>
Copy
import Foundation

// Function to calculate factorial using recursion
func factorial(_ n: Int) -> Int {
    if n == 0 || n == 1 {
        return 1 // Base case
    }
    return n * factorial(n - 1) // Recursive case
}

// Test cases
print("Factorial of 5: \(factorial(5))") // Output: 120
print("Factorial of 3: \(factorial(3))") // Output: 6
print("Factorial of 0: \(factorial(0))") // Output: 1

Output:

Factorial of 5: 120
Factorial of 3: 6
Factorial of 0: 1

Xcode Screenshot

Swift Program to Calculate Factorial using Recursion