Skip to Content
Support Palestine 🍉  ⬩  In News

Lab 1: Recursion

Target:

geca-labs/lab-daa-01

OR
Continue with your 👇 existing repo

In this lab, we will explore recursion and its applications in algorithm design. We will implement a specific problem using both recursive and non-recursive methods, analyze their time and space complexities, and provide code examples in Python, C++, and JavaScript.

We’ve chosen the factorial function as our example problem, which is a classic case for demonstrating recursion.

We demonstrate both:

  • Recursive implementation (direct application of definition)
  • Non-recursive (iterative) implementation (using loops)

Mathematical Definition:

Let nZ,n0n \in \mathbb{Z}, n \geq 0

factorial(n)={1if n=0nfactorial(n1)if n>0\text{factorial}(n) = \begin{cases} 1 & \text{if } n = 0 \\ n \cdot \text{factorial}(n - 1) & \text{if } n > 0 \end{cases}

Implementation

factorial.py
# Recursive factorial def factorial_recursive(n): if n == 0: return 1 return n * factorial_recursive(n - 1) # Iterative factorial def factorial_iterative(n): result = 1 for i in range(2, n + 1): result *= i return result # Driver n = 5 print("Recursive:", factorial_recursive(n)) print("Iterative:", factorial_iterative(n))

C++

factorial.cpp
#include <iostream> using namespace std; // Recursive factorial int factorial_recursive(int n) { if (n == 0) return 1; return n * factorial_recursive(n - 1); } // Iterative factorial int factorial_iterative(int n) { int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } int main() { int n = 5; cout << "Recursive: " << factorial_recursive(n) << endl; cout << "Iterative: " << factorial_iterative(n) << endl; return 0; }

JavaScript

factorial.js
// Recursive factorial function factorial_recursive(n) { if (n === 0) return 1; return n * factorial_recursive(n - 1); } // Iterative factorial function factorial_iterative(n) { let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Driver const n = 5; console.log("Recursive:", factorial_recursive(n)); console.log("Iterative:", factorial_iterative(n));

Expected Output

When you run the above code for n=5n = 5, you should see the following output:

Recursive: 120 Iterative: 120

Time and Space Complexity Analysis

MethodTime ComplexitySpace Complexity
RecursiveO(n)O(n)O(n)O(n) (call stack)
IterativeO(n)O(n)O(1)O(1)

Sure. Here’s the content reformatted in Markdown for your documentation or study notes.


Practice

LeetCode

CodeChef

References

  1. Python Official Documentation

  2. C++ Reference

  3. JavaScript MDN

  4. C++ Standard Template Library

  5. CS50x Week 3: Algorithms. (2025). Harvard University. Retrieved from https://cs50.harvard.edu/x/2025/weeks/3/

  1. Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C.
    Introduction to Algorithms, 3rd/4th Edition, MIT Press.


💡

Some of my latest posts on LinkedIn

Last updated on