Python Program to Find 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.

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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
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
advertisement
Subscribe to our Newsletters (Subject-wise). 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!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.