Print Square of Stars Recursively
Draw a square with recursive row and star helpers. Students trace a row index, a width counter, and two distinct stopping conditions without nested loops.
1def print_stars(n):2 if n == 0:3 return4 print("*", end="")5 print_stars(n - 1)67def print_square(n, row=0):8 # Base case9 if row == n:10 return1112 # Print row13 print_stars(n)14 print()15 # Recurse for next row16 print_square(n, row + 1)1718# Test19n = int(input("Enter size: "))20print_square(n)
Output
Enter size: 4 **** **** **** ****
In this one
- Separate row and width helpers
- Track a row argument
- Use two base cases
How it works
- 1
Stop square generation when row reaches n.
- 2
Print n stars with the width helper and end the line.
- 3
Request the next row with row + 1.
Edge cases
What happens for n = 0?
What happens for n = 0?
The square helper returns immediately.
Which helper ends a row's stars?
Which helper ends a row's stars?
print_stars stops when its width reaches zero.
What's going on
print_square tracks completed rows from zero. Each row calls print_stars(n), ends the line, then requests the next row.
The square stops when row equals n; the star helper stops at width zero. With size three, three rows each contain three stars. These helpers share Python's call stack, and negative sizes can miss their equality-based stopping points.
What happens for n = 0? The square helper returns immediately.
Which helper ends a row's stars? print_stars stops when its width reaches zero.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What controls the total row count?
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 square helper returns immediately.
Which helper ends a row's stars?
print_stars stops when its width reaches zero.
What controls the total row count?
The row argument in print_square.
๐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