Swift Program to Find Factorial of a Number

1. Introduction

The factorial of a non-negative integer ( n ), denoted as ( n! \), is the product of all positive integers less than or equal to ( n ). It's a fundamental concept in mathematics and computer science with applications ranging from basic combinatorics to algorithm complexities. In this tutorial, we'll be creating a Swift program to compute and display the factorial of a given number.

2. Program Overview

Our Swift program's aim is to compute the factorial of a given number. 

The factorial of 0 is 1, and the factorial of any positive integer ( n ) is ( n times (n-1)! ). 

With this recursive definition in mind, we can either use a recursive or iterative method to find the factorial. Here, we'll use the iterative method.

3. Code Program

// Declare the number for which the factorial is to be computed
let number = 5
var factorial = 1

// Check if the number is negative, zero or positive
if number < 0 {
    print("Factorial does not exist for negative numbers.")
} else if number == 0 {
    print("The factorial of 0 is 1.")
} else {
    for i in 1...number {
        factorial *= i
    print("The factorial of \(number) is \(factorial).")


The factorial of 5 is 120.

4. Step By Step Explanation

1. let number = 5: We start by declaring a constant number and assigning it the value 5.

2. var factorial = 1: We initialize a variable factorial to 1. This variable will store the computed factorial value.

3. if number < 0 { ... } else if number == 0 { ... } else { ... }: Here, we're handling three scenarios: when the number is negative, when it's zero, and when it's positive.

- For negative numbers, factorials are undefined, so we display a relevant message.

- The factorial of 0 is 1, so we directly display that.

- For positive numbers, we use a loop to iteratively compute the factorial.

4. for i in 1...number { ... }: This loop runs from 1 to the specified number. In each iteration, the current value of i is multiplied by the factorial variable, effectively computing the factorial.

5. print("The factorial of \(number) is \(factorial)."): Once the factorial is calculated, it's displayed using Swift's string interpolation.