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 = 1203!= 3 × 2 × 1 = 61!= 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: 120The loop multiplies result by 1, then 2, then 3, and so on until it reaches n. Each iteration builds on the previous result.
Challenge
EasyWrite 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 = 1203!= 3 × 2 × 1 = 61!= 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: 120Try it yourself
func factorial(n: Int) -> Int {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input