AlgoViz

Print name N times using recursion

Easy

The same shape, with a payload

Problem

Print a given name N times using recursion.

In simple words

Print the name, decrease the counter, and call yourself until the counter hits zero.

The idea

Identical to counting down: do the work for this call, then recurse on n-1. Where the work sits — before or after the recursive call — is what decides the output order, which is the point worth noticing here.

The trick

  • Work before the call happens on the way down; work after happens on the way back up.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

4
0

Step 1 of 2. Here's the example — n = 4, name = 'Ram' Values: 4.

1/2
Optimal
timeO(n)spaceO(n)
1f(i):2  if i>n: return3  print(name)4  f(i+1)

Input

array
[4]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
name = "Raj", n = 3
Output:
Raj Raj Raj
Explanation:
Print once, then recurse n-1 more times.

Example 2

Input:
name = "Ana", n = 1
Output:
Ana
Explanation:
A single print.

Example 3

Input:
name = "Bo", n = 2
Output:
Bo Bo
Explanation:
Twice.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.