CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

Interesting Example in Recursion


There are two cases :

# Example 1:
def fun(n):
    if(n == 0):
        return
    print(n)
    fun(n-1)
fun(5)


# Example 2:
def fun(n):
    if(n == 0):
        return
    fun(n-1)
    print(n)
fun(5)



In Example-1 the print statement will execute first then the fun(n-1) will run and it will go into the stack.

Interesting Example in Recursion



In Example-2 fun(n-1) will execute first so the stack will be created and the print will execute after the result of the fun(n-1) is returned. Till then the print statement will wait in the stack. Hence in this case the output's order will be reversed.

Interesting Example in Recursion



No comments:

Post a Comment