Question:
c++ recursive function help!!! 5 stars?
John
2011-02-15 18:18:47 UTC
Write 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:
7 * 4 = 7 + 7 + 7 + 7
in c++ language
Three answers:
Cubbi
2011-02-15 19:09:05 UTC
Multiplication can surely be performed as repeated addition, but it is very inefficient (linear complexity). It is much faster to do it by repeated doubling (logarithmic complexity):



int mult(int x, int y)

{

     if(y<0)

         return -mult(x, -y);

     else if(y==0)

         return 0;

     else

         return mult(x+x, y>>1) + (y&1) * x;

}
2016-04-27 02:02:13 UTC
As indicated in another answer and hinted at in your question, the problem is you're printing out the return value from your function. The minimal solution to your problem is change your line: cout << print_asterisks(input)<< endl; To the lines: print_asterisks(input); cout << endl; That should start yielding a warning when you compile though, if you have a good compiler and the warning level wound up to 11. The problem being that your print_asterisks returns an int, wihch you don't want. The solution to the warning (if you're getting it) is one of two actions. Firstly you change print_asterisks to return void. void is C++'s special non-value type, so you're return statement becomes just return; If sometimes when you call print_asterisk you sometimes want the return value, the other option is to pun the return to null. (void)print_asterisk(input); I would also note that if it were me coding the print_asterisk function, I would write it more like: void print_asterisks(int hAmount)// Prints Horizontal line { if (hAmount >= 1) { cout << "*"; print_asterisks(hAmount-1); } } This is a little simpler than the version you have. It also obeys the structured programming concept of one entrance, one exit, so you know if you hit one opening {, you will definitely hit the corresponding closing }. When you functions start getting more complex, this becomes important when maintaining your code.
tfloto
2011-02-15 18:37:58 UTC
I would rather you do this and ask questions about code, but I like recursive functions so here's one approach.



#include

using namespace std;



// the second parameter controls the number of recursions

// so how would you choose to call this method?

int multA(int x, int y)

{

if(y == 1)

return x;

return x + multA(x, y-1);

}

int main ()

{

cout << multA(12,9);

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...