September 13, 2010
Recursive Multiplication C++
Problem
Write a recursive function to compute the product of two positive integers.
Solution
The product of two positive integers (A*B) is nothing but the sum of the first integer (A), (B) times
Code
Here is the code in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
//Includes #include <iostream> //STD using namespace std; float RecursiveProduct(int a, int b) { //Base case if (a == 0 || b == 0) { return 0; } if (b == 1) { return a; } return a + RecursiveProduct(a, b-1); } //Main function void main() { cout << RecursiveProduct(3, 4) << endl; } |