Neko Neko - 1 year ago 101
C++ Question

c++ Recursively multiply 2 integers using addition

I'm trying to write code for homework that uses recursion and addition to multiply two integers together. But, I'm currently getting a lot of error messages, and I'm not even sure if I'm on the right track. And, just to double-check, this is recursive, right? I wrote another program for this problem which worked great until I realized it wasn't actually recursive. Here's the full code:

#include <iostream>
#include <iomanip>
using namespace std;
int result;
int m;
int n;

int rmultiply(int m, int n)
if(n > 1)
return(m + (rmultiply(n - 1)));

else if ((m == 0) || (n == 0))
return 0;
else if (n == 1)
return m;

int main(m, n)
cout << "Enter two integers to multiply" << endl; //prompt user to input 2 integers
cin >> m >> n; //store them in variable m and n

result = rmultiply(m,n);
cout << result;

Error 1: Too few arguments to function 'int rmultiply(int, int)'

return(m + (rmultiply(n - 1)));

Warning: control reaches end of non-void function

Error 2(for code lines below): Expression list treated as compound expression in initializer

Error 3: Expected ',' or ';' before'{' token

Warning: left operand of comma operator has no effect

int main(m, n)

Any help would be appreciated!

Answer Source

When you are calling the function again in this line,

return(m + (rmultiply(n - 1)));

You have to pass another variable.

Also, it will be a good idea to name the global variables m and n something different. It wont affect the programming, but just for better understanding. Because the m and n variable inside function rmultiply will always be different than the global m and n (unless passed by reference).

For the other errors, define a type of variable in line,

main(m, n)

As an integer perhaps.

And, in the main make sure that an integer is returned. Because in the function definition you have int main

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download