Joseph Jude

Technology, Psychology, and Story Telling

Swift Challenge 004: Factorial of n

Posted: Tags: 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:

  • recursion

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.


Comments

comments powered by Disqus