Recursion is a very common concept in all programming languages. It means a function can call itself repeatedly until it finds a terminating condition.
In this shot, we’ll see how to print 1
to n
using recursion.
Let’s go through the approach to solving this problem first.
n
.n
, until the value of n
is greater than 0
.The code snippet below demonstrates how to print 1
to n
using recursion.
# python3 program to print 1 to n using recursiondef printNumber(n):# check if n is greater than 0if n > 0:# recursively call the printNumber functionprintNumber(n - 1)# print nprint(n, end = ' ')# declare the value of nn = 50# call the printNumber functionprintNumber(n)
printNumber()
that accepts a parameter n
.n
is greater than 0
.true
, we recursively call the function printNumber()
with n - 1
, and print the value of n
on the console. We use the end
attribute in print()
function to format the output.n
.printNumber()
and pass n
as an argument.In the output, we can see all the numbers between 1
and n
are separated by spaces.