Recursion

Hello everyone here !
I am new to this forum and I have a beginner's question about a simple recursive (Call by ref) function : x and y are int and x times y is y + y + y +.... x times. Here is my function :

int mult(int x, int y, int &prd) {
if (x == 0) // case: x = 0 product is 0
prd = 0;
else
prd = y + mult(x - 1, y, prd);
return prd;
}

My question is : when x decreases to 0 the return value of prd should be 0 but instead I (happily) get x times y product. I don't understand.
Thanks for reading.
Alain
Well passing prd around as a reference, as well as returning the same as a value makes no sense.
One thing is almost certainly overwriting the other in some unexpected way.

Also,
1
2
3
if ( x == 0 ) prd = 0;
else if ( x == 1 ) prd = y;
else prd = y + mult(x - 1, y, prd);
Get rid of prd altogether. Just return the value. You don't need a special case for x == 1. The recursion handles it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int mult(int x, int y) {
    if (x == 0) // case: x = 0 product is 0
	return 0;
    else
	return y + mult(x - 1, y);
}


int main() {
    int fact1, fact2;
    while (std::cin >> fact1 >> fact2) {
	std::cout << fact1 << '*' << fact2 << " = " << mult(fact1, fact2) << '\n';
    }
}


Your code will explode if x is negative. Consider whether you want to handle that case.

BTW, I recommend always coding recursive functions with the pattern that you're using:

1
2
3
4
5
if (base case) {
    do the base case
} else {
    do the recursive case
}


This makes the code easy to read and it forces you to think about the base and recursive cases separately.
Thank you very much. It was just a little example I found using Call by reference + Recursion. Getting rid,of variable prd makes the program simpler.
Topic archived. No new replies allowed.