Print Triangle (Bottom-Up) Recursively
Print decreasing star rows by delaying work until recursive calls return. Students trace a row helper and compare return order with the growing-triangle version.
1def print_stars(n):2 if n == 0:3 return4 print("*", end="")5 print_stars(n - 1)67def print_triangle(n, row=1):8 # Base case9 if row > n:10 return1112 # Recurse first13 print_triangle(n, row + 1)14 # Then print current row15 print_stars(row)16 print()1718# Test19n = int(input("Enter rows: "))20print_triangle(n)
Output
Enter rows: 5 ***** **** *** ** *
In this one
- Print during return
- Reverse visible row order
- Trace pending row state
How it works
- 1
Request the next row before output.
- 2
Stop when row exceeds n.
- 3
As calls return, print the saved row width.
Edge cases
What happens for n = 0?
What happens for n = 0?
The first call returns without output.
Is row one printed first?
Is row one printed first?
No. It waits until all larger rows finish.
What's going on
The function requests row + 1 before printing its own row. Once row exceeds n, the base case returns and pending rows begin to print.
For n equal to three, row three prints first, then two, then one. The star helper still prints a chosen width normally. The call stack is the saved list of unfinished row calls; placing output after recursion reverses their visible order.
What happens for n = 0? The first call returns without output.
Is row one printed first? No. It waits until all larger rows finish.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why does the widest row appear first?
Pick an answer to check it.
Question 2
What happens for n = 0?
Pick an answer to check it.
Questions people ask
What happens for n = 0?
The first call returns without output.
Is row one printed first?
No. It waits until all larger rows finish.
Why does the widest row appear first?
Printing happens while calls return.
๐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