104k views
3 votes
Write code to complete raise_to_power(). Note: This example is for practicing recursion; a non-recursive function, or using the built-in function math.pow(), would be more common. Sample output with inputs: 4 2 4^2 = 16

User Scott H
by
6.4k points

1 Answer

4 votes

Answer:

See the explanation

Step-by-step explanation:

Note that, given a base number
b and and exponent
e we have that
b^e consists of multyplying b, e times. This means, to call the function e times of multiplying the result by b. Then consider the following code

int raise_to_power(int base, int exponent){

if exponent =0

then return 1

else

return base * raise_to_power(base,exponent-1)

}

Note that if base = 4 and exponent = 2

At first, we have that 2 is not 0, so it will multiply 4 times raise_to_power(4,1). But raise_to_power(4,1) will return 4 times raise_to_power(4,0). And raise_to_power(4,0)=1. So, the final result will be 4 * 4 * 1 = 16 which is de desired result.

User Alcides
by
6.6k points