Factorial

OVERVIEW

Factorial is a number accompanied by an exclamation mark. For example, four factorial is written as 4! which simply means 4*3*2*1 = 24.

The mathematical formula is as follow

n! = n(n−1)...2×1

Now if we are given number 5 in our case, it will look like this

5! = 5(5-1)(5-2)(5-3)(5-4)
   = 5 * 4 * 3 * 2 * 1
   = 120

Coding Section

Some of the steps taken below are:

  1. Create a function that takes in a number as a parameter
  2. Creating a variable of total by setting it at 0
  3. Create a for loop starting from 1 with condition that if total is not equal to 0 – here we want our total to be 1.
  4. If it’s 1, it will go into the if statement and calculate it accordingly
func factorial(number: Int) -> Int {
    var total = 0
    for x in 1...number{
        if total != 0 {
            total = total * x
        } else {
            total = 1
        }
    }
    return total
}

factorial(number: 5)

I’ll give you an idea how the program actually works

Loop count > Total value > Programs > Calculation

  1. For 1 -> Total is 0 -> Else -> Total is 1
  2. For 2 -> Total is 1 -> If -> 1 * 2 = 2
  3. For 3 -> Total is 2 -> If -> 2 * 3 = 6
  4. For 4 -> Total is 6 -> If -> 6 * 4 = 24
  5. For 5 -> Total is 24 -> If -> 24 * 5 = 120

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*