52.3k views
3 votes
Design a recursive function that accepts an integer argument, n, and prints the numbers 1

up through n.

User Mussa
by
4.5k points

1 Answer

5 votes

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.

Design a recursive function that accepts an integer argument, n, and prints the numbers-example-1
User Elements
by
4.7k points