Menu
Coddy logo textTech

Recap - Factorial

Part of the Fundamentals section of Coddy's Swift journey — lesson 47 of 86.

Time to put your loop skills to the test! The factorial is a classic programming problem that's perfect for practicing loops.

A factorial of a number n (written as n!) is the product of all positive integers from 1 to n. For example:

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 3! = 3 × 2 × 1 = 6
  • 1! = 1

To calculate a factorial with a loop, you start with a result of 1 and multiply it by each number in the range:

var result = 1
let n = 5

for i in 1...n {
    result *= i
}
print(result)  // Output: 120

The loop multiplies result by 1, then 2, then 3, and so on until it reaches n. Each iteration builds on the previous result.

challenge icon

Challenge

Easy
Write a function factorial that takes n and returns the factorial of that number.

Use a loop to multiply all positive integers from 1 to n together.

Parameters:

  • n (Int): A positive integer (1 or greater)

Returns: The factorial of n (Int)

For example, if n is 4, the function calculates 1 × 2 × 3 × 4 = 24 and returns 24.

Cheat sheet

A factorial of a number n (written as n!) is the product of all positive integers from 1 to n:

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 3! = 3 × 2 × 1 = 6
  • 1! = 1

To calculate a factorial with a loop, start with a result of 1 and multiply it by each number in the range:

var result = 1
let n = 5

for i in 1...n {
    result *= i
}
print(result)  // Output: 120

Try it yourself

func factorial(n: Int) -> Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals