Even Numbers 1-N Recursively
Print even integers through n using recursion. Students trace a smaller call before a parity check and understand why odd limits still produce even output.
1def print_even(n):2 # Base case3 if n == 0:4 return56 # Recursive case7 print_even(n - 1)8 # Print if even9 if n % 2 == 0:10 print(n)1112# Test13n = int(input("Enter n: "))14print_even(n)
Output
Enter n: 10 2 4 6 8 10
In this one
- Filter recursive output
- Print in ascending return order
- Check recursion's domain
How it works
- 1
Stop at n equal to zero.
- 2
Finish the recursive call for n - 1.
- 3
Print n only if its remainder modulo two is zero.
Edge cases
Does n = 5 print five?
Does n = 5 print five?
No. Five fails the parity test.
Does n = 0 print zero?
Does n = 0 print zero?
No. The base case returns before testing parity.
What's going on
The function visits every smaller positive integer first. After that call returns, it prints n only when n % 2 is zero.
For five, pending calls resume in ascending order and print two then four. The call stack is the record of these waiting function calls. Zero stops recursion; negative inputs miss that stopping point and can cause RecursionError.
Does n = 5 print five? No. Five fails the parity test.
Does n = 0 print zero? No. The base case returns before testing parity.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why are evens ascending?
Pick an answer to check it.
Question 2
Does n = 5 print five?
Pick an answer to check it.
Questions people ask
Does n = 5 print five?
No. Five fails the parity test.
Does n = 0 print zero?
No. The base case returns before testing parity.
Why are evens ascending?
The smaller recursive call finishes before the current print.
๐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