Recursive Multiplication C++
Recursive Multiplication
Write a recursive funct ion 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 repea ted addition:
7 * 4 = 4 + 4 + 4 + 4 + 4 + 4 + 4
Answer:
// Recursive Multiplication
#include <iostream>
using namespace std;
// Function prototype
long multiply(int, int);
int main()
{
// Let's multiply 7 by 4...
cout << multiply(7, 4);
cout << endl;
return 0;
}
//*******************************************
// Function multiply *
// This function uses recursion to multiply *
// x by y. The multiplication is performed *
// as repetitive addition. *
//*******************************************
long multiply(int x, int y)
{
if (x == 1)
return y;
else
return y + multiply(x - 1, y);
}
Leave a reply