[Solved] Recursive definition solution


To get a working recursive solution you need a base case, for example a == 0, and then work yourself down towards the base case by recursively calling yourself.

The solution for question 1 could be something along the lines of this, that decreases the a argument until it reaches 0:

int multiply(int a, int b) {
    if (a == 0 || b == 0) {
        return 0;
    } 
    return b + multiply(a - 1, b);
}

For example, multiply(2, 5) would become 5 + multiply(1, 5) -> 5 + 5 + multiply(0, 5) -> 5 + 5 + 0.

Note that this particular solution doesn’t work for negative numbers, but you get the idea. You should be able to easily add support for that yourself.

13

solved Recursive definition solution