← Back to Arena
Claude
Winner
987 votes (45.1%)
ChatGPT
765 votes (35.0%)
Gemini
321 votes (14.7%)
Llama
114 votes (5.2%)
"Explain recursion in programming with an example"
Recursion is when a function calls itself to solve a smaller version of the same problem.
Imagine you're in a line and want to know your position. You could count everyone, OR you could ask the person in front: 'What's your position?' They ask the person in front of them, and so on. The first person says '1', and each answer comes back with +1.
In code (factorial):
```
def factorial(n):
if n <= 1: # Base case: stop recursing
return 1
return n * factorial(n-1) # Recursive case
```
factorial(5) calls factorial(4) calls factorial(3)... until factorial(1) returns 1, then it all multiplies back up: 1×2×3×4×5 = 120.
Two rules: 1) Always have a base case (or it loops forever). 2) Each recursive call must move toward that base case.
**Recursion** is when a function calls itself to solve smaller instances of a problem.
**Example - Factorial:**
```python
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
return n * factorial(n - 1)
```
**How it works:**
```
factorial(4)
= 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * 2 * factorial(1)
= 4 * 3 * 2 * 1
= 24
```
**Key components:**
1. **Base case** - When to stop (prevents infinite loop)
2. **Recursive case** - Function calls itself with modified input
Recursion is a function calling itself. To understand recursion, you must first understand recursion. (That's the joke, but it's also the concept.)
Real example - countdown:
```
def countdown(n):
if n == 0: # Base case: STOP
print('Blastoff!')
else:
print(n)
countdown(n-1) # Call yourself with smaller number
```
countdown(3) prints: 3, 2, 1, Blastoff!
Every recursive function needs: 1) A base case (the 'stop' condition), 2) Movement toward that base case (n-1 gets us closer to 0). Without both, you get infinite recursion and a crashed program.
Recursion is when a function calls itself. It needs a base case to stop and must move toward that base case each time.
Example:
```
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
```
factorial(4) = 4 * 3 * 2 * 1 = 24
Cast Your Vote
Which AI gave the best response? Your vote counts!
Thanks for voting!
Your vote has been recorded