Factorial Program in Swift
Jul 19, 2023
In this code, we define a function factorial
that takes an integer n
as input and returns its factorial. The function uses recursion to calculate the factorial, by multiplying n
with the factorial of n-1
until it reaches the base case where n
is equal to 0, and returns 1.
We then use the function to calculate the factorial of 5, and print the result to the console.
func factorial(_ n: Int) -> Int {
if n == 0 { return 1 }
else { return n * factorial(n - 1) }
}
// Example usage
let n = 5
let result = factorial(n)
print("The factorial of \(n) is \(result)") // 5*4*3*2*1 = 120