Python Program to Find the Product of two Numbers Using Recursion

This is a Python Program to find the product of two numbers using recursion.

Problem Description

The program takes two numbers and finds the product of two numbers using recursion.

Problem Solution

1. Take two numbers from the user.
2. Pass the numbers as arguments to a recursive function to find the product of the two numbers.
3. Give the base condition that if the first number is lesser than the second, recursively call the function with the arguments as the numbers interchanged.
4. If the second number isn’t equal to 0, again call the function recursively, else return 0.
5. Print the final product of the two numbers.
6. Exit.

advertisement
Program/Source Code

Here is source code of the Python Program to find the binary equivalent of a number using recursion. The program output is also shown below.

def product(a,b):
    if(a<b):
        return product(b,a)
    elif(b!=0):
        return(a+product(a,b-1))
    else:
        return 0
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
print("Product is: ",product(a,b))
Program Explanation

1. User must enter two numbers.
2. The two numbers are passed as arguments to a recursive function to find the product of the two numbers.
3. The base condition that if the first number is lesser than the second, the function is recursively called with the arguments as the numbers interchanged.
4. If the second number isn’t equal to 0, the function is called recursively, else 0 is returned.
5. The final product of the two numbers is printed.

Runtime Test Cases
 
Case 1:
Enter first number: 12
Enter second number: 10
Product is:  120
 
Case 2:
Enter first number: 12
Enter second number: 11
Product is:  132

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter