Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

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
****
****
****
****

In this one

  • Separate row and width helpers
  • Track a row argument
  • Use two base cases

How it works

  1. 1

    Stop square generation when row reaches n.

  2. 2

    Print n stars with the width helper and end the line.

  3. 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.