Recursion is when a function calls itself. It solves a big problem by solving a smaller copy of the same problem, again and again, until the problem is small enough to answer directly.
This page explains recursion with a countdown and a factorial. You will see the base case, the recursive case, the call stack in a small table, and the same code in Java and Python.
Recursion explained simply
Think of a queue of people at a cinema. You want to know your position, but you cannot see the front. So you ask the person in front of you, "What is your position?" That person asks the person in front of them. This goes on until the question reaches the first person, who says "1". Then each person adds 1 and passes the answer back.
That is recursion:
- Each person asks the same question to the next person.
- The question gets smaller each time (fewer people ahead).
- The first person knows the answer without asking anyone. This is the stopping point.
- The answers come back in reverse order.
In code, the "person" is a function call. The function calls itself with a smaller input and uses the result to build its own answer.
Base case and recursive case
Every recursive function has two parts.
| Part | What it does | Countdown example |
|---|---|---|
| Base case | Stops the calls and returns directly | When n is 0, print "Go!" and stop |
| Recursive case | Calls the function again with a smaller input | Print n, then call countdown(n - 1) |
If you forget the base case, the function never stops. If the recursive case does not move towards the base case, it also never stops. Both mistakes crash the program.
Example 1: countdown
The countdown prints numbers from n down to 1 and then prints "Go!".
Recursion in Java
public class Recursion {
static void countdown(int n) {
if (n == 0) { // base case
System.out.println("Go!");
return;
}
System.out.println(n);
countdown(n - 1); // recursive case
}
static int factorial(int n) {
if (n <= 1) { // base case
return 1;
}
return n * factorial(n - 1); // recursive case
}
public static void main(String[] args) {
countdown(3);
System.out.println(factorial(5));
}
}
Output:
3
2
1
Go!
120
Recursion in Python
def countdown(n):
if n == 0: # base case
print("Go!")
return
print(n)
countdown(n - 1) # recursive case
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
countdown(3)
print(factorial(5))
Output:
3
2
1
Go!
120
Both programs do the same work. countdown(3) prints 3 and calls countdown(2). That prints 2 and calls countdown(1). That prints 1 and calls countdown(0), which hits the base case and prints "Go!".
Example 2: factorial
The factorial of n, written n!, is the product of all whole numbers from 1 to n.
5! = 5 x 4 x 3 x 2 x 1 = 120
Look closely and you will see a smaller factorial inside it:
5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2!
2! = 2 x 1!
1! = 1 <- base case
That pattern is exactly the recursive case: factorial(n) = n * factorial(n - 1). The base case is factorial(1) = 1. The code above uses n <= 1 so that factorial(0) also returns 1, which is the correct value for 0!.
The call stack in a small table
When a function calls another function, the computer keeps a note of where it was. These notes are stored on the call stack. A stack works like a pile of plates: the last plate placed is the first one removed.
Here is what happens for factorial(4).
Going down (calls are added to the stack):
| Step | Call | What it waits for | Stack size |
|---|---|---|---|
| 1 | factorial(4) | 4 x factorial(3) | 1 |
| 2 | factorial(3) | 3 x factorial(2) | 2 |
| 3 | factorial(2) | 2 x factorial(1) | 3 |
| 4 | factorial(1) | Nothing, base case returns 1 | 4 |
Coming back up (calls finish and leave the stack):
| Step | Call that finishes | Calculation | Returns |
|---|---|---|---|
| 5 | factorial(1) | base case | 1 |
| 6 | factorial(2) | 2 x 1 | 2 |
| 7 | factorial(3) | 3 x 2 | 6 |
| 8 | factorial(4) | 4 x 6 | 24 |
Notice that no multiplication happens on the way down. Each call waits. The real work happens on the way back up, once the base case gives the first answer.
Pro tip: When you trace recursion on paper, draw one box per call. Write the input in the box and leave the return value empty. Fill the boxes from the bottom up once you reach the base case.
More short recursion examples
Sum of digits in Java
To add the digits of 472, add the last digit (2) to the sum of the digits of 47.
public class SumDigits {
static int sumOfDigits(int n) {
if (n < 10) { // one digit left
return n;
}
return n % 10 + sumOfDigits(n / 10);
}
public static void main(String[] args) {
System.out.println(sumOfDigits(472));
}
}
Output:
13
The calls are sumOfDigits(472), then sumOfDigits(47), then sumOfDigits(4). The last one returns 4. Then 7 + 4 = 11, and 2 + 11 = 13.
Reverse a string in Python
To reverse "code", reverse "ode" and put "c" at the end.
def reverse(text):
if text == "":
return ""
return reverse(text[1:]) + text[0]
print(reverse("code"))
Output:
edoc
The input gets one character shorter each call, so it always reaches the empty string, which is the base case.
What happens without a base case
This function has no base case:
def broken(n):
return broken(n - 1)
Each call adds a new entry to the call stack. The stack has a limited size, so the program eventually crashes.
| Language | What you see |
|---|---|
| Python | RecursionError: maximum recursion depth exceeded. The default limit is 1000 calls (check with sys.getrecursionlimit()). |
| Java | java.lang.StackOverflowError. The depth depends on the stack size of the JVM. |
The same crash happens if the base case exists but the input never reaches it. For example, calling countdown(-1) with the code above would skip past 0 and keep going down. A safer base case is if n <= 0.
Common mistake: Writing
return factorial(n)instead ofreturn n * factorial(n - 1). The input never gets smaller, so the base case is never reached.
Recursion vs loop
Any recursive function can be rewritten with a loop, and the reverse is also true. Here is factorial with a loop in Python:
def factorial_loop(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial_loop(5)) # 120
| Point | Recursion | Loop |
|---|---|---|
| Code length | Often shorter for tree-like problems | Often shorter for simple counting |
| Memory | Uses one stack entry per call | Uses a fixed amount |
| Speed | Slightly slower because of call overhead | Usually faster |
| Risk | Stack overflow on very deep input | Infinite loop if the condition is wrong |
| Best for | Trees, folders, divide and conquer | Counting, simple repetition |
For factorial and countdown, a loop is fine and often better. Recursion shines when the data itself is nested, such as a folder that contains folders, or a tree where each node has children.
A warning about repeated work
The simple recursive Fibonacci function calls itself twice per step:
static long fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
It is easy to read but very slow for bigger n, because it solves the same smaller values many times. We counted the calls:
| n | fib(n) | Number of calls |
|---|---|---|
| 10 | 55 | 177 |
| 20 | 6,765 | 21,891 |
| 30 | 832,040 | 2,692,537 |
The number of calls grows very fast. You can fix this by storing answers you have already found (called memoization) or by using a loop. Our guide on time complexity and Big O explains how to measure this kind of growth.
How to write a recursive function
Follow these steps for any new problem:
- Find the smallest input you can answer without thinking. That is your base case.
- Assume the function already works for a smaller input.
- Use that smaller answer to build the answer for the current input.
- Check that every call moves closer to the base case.
- Trace a small input by hand, such as n = 3, before running the code.
Step 2 feels strange at first. You do not need to follow every call in your head. Trust that factorial(4) returns 24, and you only need to write how factorial(5) uses it.
Where recursion is used
- Folders and files: listing every file inside a folder and its sub-folders.
- Trees: visiting every node of a binary tree or a family tree.
- Sorting: merge sort and quick sort split the list and sort each half recursively.
- Searching: binary search can be written recursively, and depth-first search in graphs is often recursive.
- Nested data: reading JSON or HTML, where items can contain more items.
The call stack that recursion uses is the same last in, first out idea covered in stack vs queue.
Practice and next steps
Recursion builds on functions, so make sure you are comfortable with parameters and return values first. Our functions for beginners guide covers that. Then try writing these yourself: power of a number, sum of an array, counting down to 1, and checking a palindrome.
When you can write a base case and trace the call stack without help, move on to the data structures and algorithms guide and test yourself with the DSA interview questions.
Frequently Asked Questions
What is recursion in simple words?
What is a base case in recursion?
What happens if there is no base case?
Is recursion better than a loop?
Where is recursion used in real programs?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — View the Java Full Stack curriculum

