12. Write a recursive function to implement the recursive algorithm of Exercise
ID: 3649214 • Letter: 1
Question
12. Write a recursive function to implement the recursive algorithm of Exercise 13 (multiplying two positive integers using repeated addition). Also, write a program to test your function.Exercise 13:
Write a recursive algorithm to multiply two positive integers m and n using reapeated addition. Specify the base case and the recursive case.
The algorithm is in code in the attached cpp file - function RecMultiply(unsigned int m, unsigned int n) implements the algorithm and main() tests it.
The base case is the multiplication by 0 - then the output is 0.
The recursive case is n > 0: m is added to the product of m and (n-1)
(since the input is supposed to be positive integers, the function always goes through the recursion at least once)
Answer to Exercise 13:
#include <iostream>
using namespace std;
int RecMultiply(unsigned int m, unsigned int n)
{
if( 0 == n ) // base case
return 0 ;
// recursive case
return m + RecMultiply(m, n-1) ;
}
int main()
{
printf("Hello World! ");
int m, n ;
cout << "Type m =" << endl ;
cin >> m ;
cout << "Type n =" << endl ;
cin >> n ;
cout << "Product = " << RecMultiply(m,n) << endl ;
return 0;
Explanation / Answer
#include using namespace std; int RecMultiply(unsigned int m, unsigned int n) { if( 0 == n ) // base case return 0 ; // recursive case return m + RecMultiply(m, n-1) ; } int main() { int m, n ; coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.