Recursion as a loop replacement
We have seen that recursion is the repeated execution of contained instructions in a subroutine. And this, in turn, is similar to the work of the cycle. There are programming languages in which the loop construct is absent altogether. For example, Prolog.
Let's try to simulate the work of the loop
for
.
The
for
loop contains a step counter variable. In a recursive subroutine, such a variable can be passed as a parameter.
# Procedure LoopImitation() with two parameters
# First parameter – step counter, second parameter – total number of steps
def LoopImitation(i, n):
print("Hello N", i) # Statement to be repeated for any value of i
if i < n: # Until the loop counter equals the value n,
LoopImitation(i + 1, n) # call a new instance of the procedure,
# with parameter i+1 (go to next value i)