I am studying old examination papers from my university to be able to prepare for my upcoming exams. Everything is easily understandable from the simplest problems to the most complicated ones. However, I can not, for the life of me, figure the following one out.
class k{
static int g(int n) {
if (n==0){
return 1;
} else {
return 2*g(n-1);
}
}
public static void main(String[] args) {
System.out.println(g(3));
}
}
Why does this code return 8 as an answer. I get that its basically a power function where the number input is calculated as 2 to the power of that number and hence the answer in this case is 8. But what is really going on. I don't get it. Could someone please explain it in simple English? I'd really appreciate it.
By the way, the question only asks what the output is, not why. But I would feel more comfortable if I knew why it is the way it is.
PS: The reason people are giving answers using 5 as an example is that I had mistakenly put 5 instead of 3 in the code above, which I have corrected now.