Showing posts with label An introduction to recursive functions in Python. Show all posts
Showing posts with label An introduction to recursive functions in Python. Show all posts

Tuesday, June 18, 2019

An introduction to recursive functions

Code to find the sum of first n natural numbers:
def sum(n,s=0):
    if n==0:
        return s;
    else:
        s=s+n;
        return sum(n-1,s)

#main
n=int(input("Enter a number:"))
s=sum(n)
print(s)



Code to find the largest digit in an integer:
def largest(n,l=0):
    if n==0:
        return l;
    else:
        if n%10>l:
            l=n%10
        return largest(n//10,l)

#main
n=int(input("Enter an integer:"))
p=largest(n)
print("Largest Digit",p)
 


Code to find the HCF between 2 numbers:
def HCF(n,d):
    if n%d==0:
        return d
    else:
        r=n%d
        n=d
        d=r
        return HCF(n,d)

#main
n=int(input("Enter a number:"))
m=int(input("Enter another number:"))
h=HCF(n,m)
print("HCF=",h)
 

  Source Code for :   Displaying all possible fangs of a Vampire Number in Java import java.util.*; class Number {     public static void ma...