Search code examples
javarecursionnumbersreturnmultiplication

N times of a number using Recursion_how return type of recursion method works


private static int nTimesK(int n, int k) {
System.out.println("n: " + n);
// Recursive Case
if(n > 1) { 
    return k + nTimesK(n - 1, k);
}
// Base Case n = 1
else { 
    return k;
}
}
public static void main(String[] args) {
int result = nTimesK(4, 4);
System.out.println("Result: " + result);
}

Query: it runs like return k+ntimesK(3,4),it runs like return k+ntimesK(2,4),it runs like return k+ntimesK(1,4) where n=1 is the base case. wanted to know how 4+ntimesK(3,4) will result in value 8 followed by 12 and finally 16.


Solution

  • Assume you call the method passing in 4 and 4 (i.e. nTimesK(4,4)), inside the method, since n>1 (4 is greater than 1) it executes return k + nTimes(n-1, k). The statement is replaced by 4 + nTimesK(3,4) (we call this point A). The computation can not return the response because it has to wait for the result of nTimesK(3,4). When nTimesK(3,4) is called, it should return 4 + nTimesK(2,4)(we call this point B) to the first call (A). It has to wait for nTimesK(2,4) to execute before returning the result. So, nTimesK(2,4) is called and it returns 4 + nTimesK(1,4) (we call this point C). When C executes nTimesK(1,4), the call returns 4 (being the base condition. ie. n = 1). So, C can now return 4 + 4 (=8)to B. B can also now return 4 + 8 (=12) to A. A computes 4 + 12 (=16) and returns the answer to the original call. Hence the value 16.