Recursive Function

Previous
Next

Recursion:

  • Function calling itself is called recursion.
  • Calling the function from the definition of same function.
def fun():
    print("Start")
    fun() #recursive call
    print("End")
    return

fun()
  • In any programming language, functions execute in stack memory.
  • While program is executing, if the Stack memory is full, program terminates abnormally.

In recursion, where program execution starts, there it ends:

def abc(a):
    print("a val :",a)
    if a>0:
 
        abc(a-1)
    return

abc(3)
defabc(a):
    print("Forward :",a)
    if a>0:
abc(a-2)
    print("Backward :",a)
    return

abc(6)

Factorial using recursion:

def fact(n):
    res=0
    if n==0:
        res=1
    else:
        res = n*fact(n-1)
    return res

n = int(input("Enter n val : "))
res = fact(n)
print("Factorial value is :",res)

Write output and flow:

def test(a):
    print(a-1)

    a=a+1
    if a<=7:
        test(a+1)

    print(a-1)
    return

test(3)
Previous
Next

Add Comment

Courses Enquiry Form