PPractick

DSA interview question

Print 1 to N Using Recursion

Easy · Algorithms · Topics: recursion, basics

The problem

A classroom display counts up from 1 to N on screen, and the exercise is to generate the sequence recursively, without a loop. It's the classic problem for learning that the position of the recursive call matters. Printing before the recursive call produces one order, and printing after it (on the way back up the call stack) produces the reverse. Here you'll write both versions, one that counts up by carrying an index forward and one that reaches 1 first and prints while unwinding, and understand why both print 1 to N.

Example: N = 5 → 1 2 3 4 5.

Function signature

void printForward(int i, int n);  // print i, then recurse on i + 1 (call as printForward(1, n))
void printByBacktracking(int n);  // recurse on n - 1 first, then print n

Test cases

Input nOutputExplanation
51 2 3 4 5Both versions
11
0(nothing)Base case immediately
101 2 3 4 5 6 7 8 9 10

(Confirm: n ≥ 0; numbers separated by spaces; no loops.)

How interviewers phrase it

Clarifying questions to ask

  1. Can I use an extra parameter?
  2. How large can N be? (Recursion depth.)
  3. What separator between numbers?

Follow-ups to expect

  1. "Why does printing after the recursive call still give 1 to N?"
  2. "What's the difference between the two approaches?"
  3. "What happens for N = 10^6?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in