Print Square of Stars Recursively

Print square pattern using recursion.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 2 of 10
print-square-of-stars-recursively.py
1def print_stars(n):
2 if n == 0:
3 return
4 print("*", end="")
5 print_stars(n - 1)
6
7def print_square(n, row=0):
8 # Base case
9 if row == n:
10 return
11
12 # Print row
13 print_stars(n)
14 print()
15 # Recurse for next row
16 print_square(n, row + 1)
17
18# Test
19n = int(input("Enter size: "))
20print_square(n)

Output

Enter size: 4
****
****
****
****

What's going on

Print row of n stars, then recurse for next row.

Key Concepts:

Use helper function for printing stars
Print row, then recurse
Track row number with parameter