Answer:
Here is the recursive function:
def PrintNumbers(n): #function definition
if n==1: #base case
print(n)
elif n>1: #recursive case
PrintNumbers(n-1)
print(n)
else: #if value of n is less than 1
print("Invalid input")
Step-by-step explanation:
Here is the complete program:
def PrintNumbers(n):
if n==1:
print(n)
elif n>1:
PrintNumbers(n-1)
print(n)
else:
print("Invalid input")
PrintNumbers(5)
If you want to take input from user then you can use these statements in place of PrintNumbers(5)
num = int(input("Enter value of n: "))
PrintNumbers(num)
I will explain the program with an example:
Lets say value of n = 3
Now the base condition n==1 is checked which is false because n is greater than 1. So the program moves to the recursive part which works as follows:
PrintNumbers(n-1) this line calls PrintNumbers recursively to print numbers from 1 to n=3. So the output is:
1
2
3
The screenshot of program along with its output is attached.