In this tutorial, we will explore a method to print numbers from 1 to N without utilizing loops, employing recursion instead.
Understanding the Problem: The task is to print all numbers from 1 to N, where N is a given integer.
Approach: To achieve this recursively, we will define a function named printNos()
that takes N as a parameter. Within this function, we will call itself recursively with the value of N decremented by 1 until N reaches 0.
Implementation Steps:
- Define the
printNos()
function, which accepts an integer N as an argument. - Base Case: If N equals 0, the recursion terminates.
- Recursive Step: Inside the function, print the current value of N and recursively call
printNos()
with N-1.
Here’s the Python code implementing this approach:
python code
def printNos(N):
if N == 0: # Base Case: If N equals 0, stop recursion
return
printNos(N - 1) # Recursive Step: Call printNos with N-1
print(N, end=" ") # Print the current value of N
# Example usage:
N = 10
printNos(N)
Explanation of the Code:
- In the
printNos()
function, if the value of N becomes 0, the function terminates. - Otherwise, it recursively calls itself with N-1 until the base case is reached.
- After the recursive call, it prints the current value of N.
Time and Space Complexity Analysis:
- The time complexity of this solution is O(N) because the function is called recursively N times.
- The space complexity is also O(N) due to the recursive function calls.
Conclusion: Recursion offers an elegant solution for problems like printing numbers from 1 to N without loops. By breaking down the problem into smaller subproblems, recursion allows for concise and efficient code.