I am trying to understand recursion, so I have written a simple program to run a for
loop using recursion:
#for loop code
n = 955
for i in range(n+1):
if(i==n):
print(i)
outputs
955
Below code is a recursive version of the for
loop code snippet:
def fun(i,n):
if(i==n):
print(i)
return
fun(i+1,n)
fun(0,999) # calling function by passing index and N
I am getting an error when I set n
to be 999:
Traceback (most recent call last):
File "/home/jdoodle.py", line 5, in <module>
fun(0,999)
File "/home/jdoodle.py", line 4, in fun
fun(i+1,n)
File "/home/jdoodle.py", line 4, in fun
fun(i+1,n)
File "/home/jdoodle.py", line 4, in fun
fun(i+1,n)
[Previous line repeated 995 more times]
File "/home/jdoodle.py", line 2, in fun
if(i==n):
RecursionError: maximum recursion depth exceeded in comparison
But when I run the following code by passing n
as 955:
def fun(i,n):
if(i==n):
print(i)
return
fun(i+1,n)
fun(0,955)
I am getting no error output as
955
Why there is an error when n=999
or above in recursive code in online compilers. How can I avoid these errors? The online compiler that I have used is: https://www.jdoodle.com/python3-programming-online/.