Course contentsShow
← Computer Science
Lesson 217 of 2,8725. Functions and ModularityFree lesson

What is Recursion?

Define recursion as a function calling itself and understand the concept of self-referential problem solving.

What is Recursion?

What you'll learn: You'll discover how functions can solve problems by calling themselves, creating elegant solutions to complex challenges.

The Core Idea

Recursion is when a function calls itself during its own execution. Instead of using a loop to repeat steps, a recursive function breaks a problem into smaller versions of the same problem, solves those smaller pieces, and combines the results.

Think of it like Russian nesting dolls (matryoshkas). To open all the dolls, you:

  1. Open the current doll
  2. If there's a smaller doll inside, repeat the process with that doll
  3. If there's no doll inside, you're done

Each time you "repeat the process," you're doing the exact same task (opening a doll) but on a smaller scale.

How It Works

A recursive function has two essential parts:

  1. Base case: A condition that stops the recursion (like finding the smallest doll with no doll inside)
  2. Recursive case: The function calling itself with a simpler or smaller version of the original problem

Without a base case, the function would call itself forever—just like an infinite loop you learned about earlier.

Self-Referential Problem Solving

Recursion is powerful for problems that naturally divide into smaller, similar subproblems. Instead of thinking "do this step over and over," you think "solve this small piece, then solve the rest the same way."

This self-referential approach feels circular at first, but it's incredibly elegant for certain types of problems you'll encounter throughout computer science.

Key Takeaway: Recursion is a function calling itself to solve problems by breaking them into smaller, identical subproblems, always requiring a base case to stop the self-calling process.