[Solved] Can’t understand how this works [closed]


The code behaves as expected, the power function is recursive. For arguments 4 and 2, it calls itself recursively twice:

   power(4, 2)
-> 4 * power(4, 1)
-> 4 * (4 * power(4, 0))
-> 4 * (4 * 1)
-> 16

You might be more familiar with an iterative approach:

int power(int base, int powerRaised) {
    int res = 1;
    while (powerRaised > 0) {
        res = res * base;
        powerRaised--;
    }
    return res;
}

3

solved Can’t understand how this works [closed]