+ 1

# Recursion

public int result(int n) { if(n==1) return 2; else return 2*result(n-1); } What’s is the output of result(5)? Can you please show me the steps as well! 🙏🏼

3 Antworten

+ 5

The first time the function runs this happens
n=5;--> return 2*result(4)
n=4--> return 2*result(3) therefore. n=5->return 2*2*result(3).
n=3--> return 2*result(2) therefore. n=5-> return 2*2*2*result(2)
n=2-->return 2*result(1) therefore. n=5-> return 2*2*2*2*result(1)
n=1-->return 2 therefore. n=5->return 2*2*2*2*2 =2^5=32.
result(5)=32.

+ 3

the result of result(5) is
(2*result (4))
(2*(2*result(3)))
(2*(2*(2*result(2))))
(2*(2*(2*(2*result(1)))))
(2*(2*(2*(2*(2)))))
32

+ 2

The secret of recursion is to start counting at the stop condition. It works in most cases.
if(n==1) means that your inputs have to be equal to or bigger than 1, so start counting at 1. The next number will always depend on the one you calculated before:
n==1 -> 2
n==2 -> 2*2=4
n==3 -> 2*4=8
n==4 -> 2*8=16
n==5 -> 2*16=32
You're basically calculating the powers of 2 here, so you could add this to complete it:
if(n==0)
return 1;