0% found this document useful (0 votes)
18 views6 pages

Recursion

The document explains recursion and provides examples of both recursive and non-recursive implementations of factorial and the sum of N numbers. It includes syntax for defining functions and tracing the execution of the algorithms. The examples illustrate how to compute factorial and sum using both approaches, along with detailed tracing of the calculations.

Uploaded by

Manu My
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

Recursion

The document explains recursion and provides examples of both recursive and non-recursive implementations of factorial and the sum of N numbers. It includes syntax for defining functions and tracing the execution of the algorithms. The examples illustrate how to compute factorial and sum using both approaches, along with detailed tracing of the calculations.

Uploaded by

Manu My
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

18-03-24

-------------
Recursion:
A function calling itself
Syntax:
def function_name():
--------------
function_name()
-------------------
ex:
def f1():
----------
f1()
----------

Non Recursive Factorial:


def fact(n):
fact=1
i=1
while(i<=n):
fact=fact*i
i=i+1
print('factorial of given number is',fact)
#main
n=int(input('enter any positive number'))
fact(n)#function calling

Tracing:
n=5
fact(5)
fact=1
i=1
Iter-1
while(1<=5): True
fact=1*1=1
i=1+1=2
Iter-2
while(2<=5): True
fact=1*2=2
i=2+1=3
Iter-3
while(3<=5) True
fact=2*3=6
i=3+1=4
Iter-4
while(4<=5) True
fact=6*4=24
i=4+1=5
Iter-5
while(5<=5) True
fact=24*5=120
i=5+1=6

while(6<=5) False
print('factorial of given number is 120)

#factorial Recursive
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)

#main
n=int(input('enter n'))
print('factorial of given number is',fact(n))
Tracing;
n=5
fact(5):
5==1 False
return 5*fact(4)
fact(4):
return 4*fact(3)
fact(3):
return 3*fact(2)
fact(2):
return 2*fact(1)
fact(1):
return 1

Ex2:
Sum of N Numbers
input output
0 0
1 0+1=1
2 0+1+2=3
3 0+1+2+3=6
4 0+1+2+3+4=10

#Non Recursive Sum of N numbers


def sum(n):
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print('sum of n numbers is',sum)
#main
n=int(input('enter n'))
sum(n)

Tracing:
n=5
sum(5)
i=1
sum=0
Iter-1
while(1<=5)True
sum=0+1=1
i=1+1=2
Iter-2
while(2<=5) true
sum=1+2=3
i=2+1=3
Iter=3
while(3<=5) true
sum=3+3=6
i=3+1=4
Iter-4
while(4<=5) true
sum=6+4=10
i=4+1=5
Iter5
while(5<=5) true
sum=10+5=15
i=5+1=6

while(6<=5) false

You might also like