0% found this document useful (0 votes)
7 views3 pages

Recursion

Recursion basics

Uploaded by

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

Recursion

Recursion basics

Uploaded by

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

Print 1 to n without using loops:

def printNos(n):
if n>0:
printNos(n-1)
print(n)

Print n to 1 without using loops:


def printNos(n):
if n>0:
print(n)
printNos(n-1)

Sum of array elements


def _sum(arr,n)
if n<=0:
return 0
return (_sum(arr,n-1) + arr[n-1])
res = _sum(arr,len(arr))
print(res)

Fibonacci number:
def fib(n):
if n <2:
return n
else:
return fib(n-1) + fib(n-2)
Reverse the number:
sum = 0
def rev(n):
if n == 0:
return
rem = n%10
sum = sum*10 + rem
rev(n//10)

Count Set-bits of number using recursion :


def helper(N,cou):
if N==0:
return cou
else:
if N%10 == 1:
return helper(N//10,cou+1)
return helper(N//10,cou)

Decimal to binary number using recursion


def dec_bin(n):
if n ==0:
return ‘0’
if n ==1:
return ‘1’
return dec_bin(n//2) + str(n%2)

Product of 2 Numbers using recursion


def prod(x,y):
if x<y :
return prod(y,x)
elif x>y and y!=0:
return x+prod(x,y-1)
else:
return 0

reverse the String:


def rev_str(str,len):
if len == 0:
return “”
return str[len-1] + rev_str(str,len-1)

Palindrome
def ispal(str,i):
if(i>len(str)//2):
return True
ans = False
if((str[i] == str[len(str)-i-1)) and ispal(str,i+1):
ans = True
return ans

Sum of digits:
def _sum(n):
if n == 0:
return 0
return _sum(n//10) + n%10

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

You might also like