VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-1-to-n-without-using-loops/

⇱ Print 1 to n using Recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print 1 to n using Recursion

Last Updated : 30 Sep, 2025

Given an integer n. Print numbers from 1 to n using recursion.

Examples:

Input: n = 3
Output: [1, 2, 3]
Explanation: We have to print numbers from 1 to 3.

Input: n = 10
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Approach:

To solve this problem using recursion, we define a function that takes an integer n as an argument. The function first checks for a base case (n == 0) to stop the recursion. If not, it makes a recursive call with n - 1, ensuring smaller numbers are handled first. After the recursive call returns, the function prints the current value of n. This process continues until all numbers from 1 up to the given value are printed in order.


Output
1 2 3 

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: