In: Computer Science
Guided Assignment Problem 3: Call Stack
Your Tasks:
Answer the following questions. Include a function stack chart/diagram for each question to verify your answers.
int example(int n) {
if (n == 0)
return 0;
else
return example(n – 1) + n * n * n;
}
int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n – 1));
}
1. example(3)
This function finally returns 36 that can be seen from the below diagram:
example(3) calls 2, 2 calls 1, and 1 calls 0, finally example(0) returns 0 and the values are computed as shown in the figure above. Then example(1) returns 1, example(2) adds 8 to 1 and returns 9, and finally example(3) adds 9 to 27 and returns 36 as the final ans.
2. Factorial(5)
After factorial(5) is invoked, method factorial invokes itself 5 times more as shown:
When call reaches factorial(0), it starts to return values. 1 is returned to factorial(1), which again returns 1 to factorial(2), it then returns 2 to factorial(3), which returns 6 to factorial(4), which returns 24 to factorial(5), which then finally returns the final answer as 24*5 = 120