Recursion is a process in which a function calls itself to solve a problem by breaking it into smaller versions of the same problem.
Recursion is a process in which a function calls itself to solve a problem by breaking it into smaller versions of the same problem.
A function factorial() can call itself to calculate
the factorial of a smaller number.
A recursive function normally has two important parts: a base case and a recursive case.
The base case is the condition that stops the recursive calls. Without a proper base case, recursion can continue indefinitely.
In factorial, factorial(0) = 1 can be used as the
base case.
The recursive case is the part of the function where the function calls itself with a smaller or simpler value.
factorial(n) = n * factorial(n - 1)
5 4 3 2 1
Recursion can be understood like solving a large task by repeatedly solving a smaller version of the same task until a simple stopping condition is reached.
A folder can contain subfolders, and each subfolder can contain more subfolders. A program can process them using the same logic repeatedly.
Write a C program to find the factorial of a positive integer using recursion.
Define a function factorial() that returns
1 when n == 0. Otherwise return
n * factorial(n - 1).
Factorial of a non-negative integer n is the product
of all positive integers from 1 to n.
Recursion calculates it by repeatedly reducing the value of
n until the base case is reached.
5! = 5 × 4 × 3 × 2 × 1 = 120
Enter a positive integer: 5
Factorial of 5 = 120
Every recursive function must have a proper stopping condition. The base case prevents the function from calling itself forever.
Recursion can make some problems easier to express when the problem naturally consists of smaller versions of itself.
Problems involving factorial, Fibonacci series, tree structures and divide-and-conquer techniques can be expressed using recursion.
Recursion can use additional memory because each function call remains active until the recursive calls return. Poorly designed recursion can also lead to excessive calls.
A recursive function without a correct base case may continue calling itself until the program runs out of available stack space.
| Recursion | Iteration |
|---|---|
| Function calls itself. | Uses loops such as for or while. |
| Requires a base case. | Requires a loop condition. |
| Uses function-call stack memory. | Usually uses less additional stack memory. |
| Term | Remember |
|---|---|
| Recursion | A function calling itself. |
| Base Case | Stops the recursive calls. |
| Recursive Case | Makes the function call itself again. |
| Factorial | A common example of recursion. |
Watch a beginner-friendly explanation of recursion and recursive functions in C.
A short handwritten-style revision sheet for recursion will be provided here.
Use the mind map for quick revision of recursive call, base case and recursive case.