SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Recursion
Exercise:
Programming Exercises
Question:2 | ISBN:9780132576376 | Edition: 2

Question

Design a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. Remember, multiplication can be performed as repeated addition as follows:
7 x 4 = 4 + 4 + 4 + 4 + 4 + 4 + 4
(To keep the function simple, assume that x and y will always hold positive nonzero integers.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

#Create a multiply function with accepts
#two arguments:
# The function should return the value of x times y. 
def multiply(x, y):
    if y == 1:
        return x
    else:
        #Recursive call, multiply
        return x + multiply(x, y - 1)

# Test the function
x = int(input("Enter the first positive number: "))
y = int(input("Enter the second positive number: "))
result = multiply(x, y)
print("Product:", result)

Executed Output:

Enter the first positive number: 500
Enter the second positive number: 200
Product: 100000

 

0 0

Discussions

Post the discussion to improve the above solution.