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

Print Line of N Stars Recursively

Print a line of n stars with a recursive function. Students trace printing before the next call and separate the terminating newline from repeated output.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 1 of 10
print-line-of-n-stars-recursively.py
1def print_stars(n):
2 # Base case
3 if n == 0:
4 return
5
6 # Recursive case
7 print("*", end="")
8 print_stars(n - 1)
9
10# Test
11n = int(input("Enter n: "))
12print_stars(n)
13print()

Output

Enter n: 5
*****

In this one

  • Print without newlines
  • Reduce a width recursively
  • End output in the caller

How it works

  1. 1

    Return at width zero.

  2. 2

    Print one star and recurse for n - 1.

  3. 3

    After all calls return, print the final newline.

Edge cases

What does n = 0 print?

What does n = 0 print?

Only the caller's final newline.

What happens for negative n?

What happens for negative n?

It moves away from zero and eventually raises RecursionError.

What's going on

print_stars writes one star and calls itself with n - 1. At zero it returns without printing another character.

end empty keeps stars on one line. The caller's final print supplies the newline after all calls return. Each call occupies the call stack, so this simple line is better for understanding recursion than for printing huge widths.

What does n = 0 print? Only the caller's final newline.

What happens for negative n? It moves away from zero and eventually raises RecursionError.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What reduces the remaining width?

Pick an answer to check it.

Question 2

What does n = 0 print?

Pick an answer to check it.

Questions people ask

What does n = 0 print?

Only the caller's final newline.

What happens for negative n?

It moves away from zero and eventually raises RecursionError.

What reduces the remaining width?

n - 1.