In computer science and mathematics, two classic problems often introduced to beginners are calculating the factorial of a number and generating the Fibonacci sequence.
Understanding the pseudocode for these problems helps build a strong foundation for learning recursion, loops, and algorithmic thinking.
This article explains both factorial and Fibonacci calculations through simple and clear pseudocode examples.
What is a Factorial?
The factorial of a number n
(written as n!
) is the product of all positive integers less than or equal to n
.
Example:5! = 5 × 4 × 3 × 2 × 1 = 120
Factorials are widely used in combinatorics, probability, and algorithm design.
Pseudocode for Calculating Factorial (Using Loop)
1 2 3 4 5 6 7 8 9 | 1. Start 2. Input n 3. Set factorial = 1 4. For i = 1 to n: a. factorial = factorial * i 5. Output factorial 6. End |
Pseudocode for Calculating Factorial (Using Recursion)
1 2 3 4 5 6 7 8 9 10 11 | 1. Start 2. Function Factorial(n): a. If n == 0 or n == 1: - Return 1 b. Else: - Return n * Factorial(n-1) 3. Input n 4. Output Factorial(n) 5. End |
What is the Fibonacci Sequence?
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1.
Example:0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Fibonacci numbers appear in mathematics, nature (such as flower petals), and even computer algorithms.
Pseudocode for Calculating Fibonacci Sequence (Using Loop)
1 2 3 4 5 6 7 8 9 10 11 12 | 1. Start 2. Input n (number of terms) 3. Set first = 0, second = 1 4. Output first and second 5. For i = 2 to n-1: a. next = first + second b. Output next c. first = second d. second = next 6. End |
Pseudocode for Calculating Fibonacci (Using Recursion)
1 2 3 4 5 6 7 8 9 10 11 12 13 | 1. Start 2. Function Fibonacci(n): a. If n == 0: - Return 0 b. Else if n == 1: - Return 1 c. Else: - Return Fibonacci(n-1) + Fibonacci(n-2) 3. Input n 4. Output Fibonacci(n) 5. End |
Factorial vs Fibonacci: Key Differences
Aspect | Factorial | Fibonacci Sequence |
---|---|---|
Definition | Product of integers up to n | Sum of two preceding numbers |
Common Use | Combinatorics, Permutations | Nature patterns, Algorithm design |
Base Cases | 0! = 1, 1! = 1 | F(0) = 0, F(1) = 1 |
Growth Rate | Very fast (n!) | Moderate (exponential) |
Conclusion
Learning to write pseudocode for factorial and Fibonacci problems is an excellent exercise for beginners in computer science.
- Use loops when you need simple, fast calculations.
- Use recursion when you want a more elegant or theoretical approach.
These fundamental problems also prepare you for advanced topics like dynamic programming, memoization, and algorithm optimization.