Joseph Jude

Consult . Code . Coach

Swift Challenge 004: Factorial of n


code . swift

Challenge: Write a program to compute factorial of a number.

Logic: Factorial of n is a product of all positive integers less than or equal to n. Use recursion to calculate product.

Code:

func factorial(n: Int) -> Int {
  if n == 1 {
    return 1
  } else {
    return n * factorial(n - 1)
  }
}

print(factorial(5))

Teaches:

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.

Share this on: Twitter / /

Comments

comments powered by Disqus