Sum of First N Odd Numbers Recursively
Sum the first n positive odd numbers through recursion. Students trace the term formula, a zero-count base case, and unfinished additions on the call stack.
1def sum_odd(n):2 # Base case3 if n == 0:4 return 056 # Recursive case7 # nth odd number is 2*n - 18 return (2 * n - 1) + sum_odd(n - 1)910# Test11n = int(input("Enter n: "))12result = sum_odd(n)13print(f"Sum of first {n} odd numbers: {result}")
Output
Enter n: 5 Sum of first 5 odd numbers: 25
In this one
- Use the nth-odd formula
- Combine smaller sums
- Trace pending additions
How it works
- 1
Return zero at n equal to zero.
- 2
Recurse for n - 1 odd terms.
- 3
Add 2 * n - 1 to the smaller sum.
Edge cases
Does zero terms include -1?
Does zero terms include -1?
No. The base case returns before calculating a term.
What is the sum for n = 4?
What is the sum for n = 4?
Sixteen.
What's going on
The nth positive odd number is 2 * n - 1. The function adds it to the sum of the previous n - 1 odd numbers.
For n equal to three, the addition is five plus three plus one, giving nine. Zero returns zero without producing a negative odd term. Negative counts are outside the intended domain and never reach this stopping case by decrementing.
Does zero terms include -1? No. The base case returns before calculating a term.
What is the sum for n = 4? Sixteen.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which expression gives the nth odd term?
Pick an answer to check it.
Question 2
Does zero terms include -1?
Pick an answer to check it.
Questions people ask
Does zero terms include -1?
No. The base case returns before calculating a term.
What is the sum for n = 4?
Sixteen.
Which expression gives the nth odd term?
2 * n - 1.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum