Exercise 2 The point of this exercise is to use a stack diagram to understand th
ID: 3563917 • Letter: E
Question
Exercise 2 The point of this exercise is to use a stack diagram to understand the
execution of a recursive program.
public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
}
}
1. Draw a stack diagram showing the state of the program just before the last
instance of prod completes. What is the output of this program?
2. Explain in a few words what prod does.
3. Rewrite prod without using the temporary variables recurse and result .
Explanation / Answer
Recursion: A function call by self is called a recursive function.
The given program result Factorial of a number.
public class Prod {
public static void main(String[] args) {
System.out.println(prod(1, 4));
}
public static int prod(int m, int n) {
if (m == n) {
return n;
} else {
int recurse = prod(m, n-1);
int result = n * recurse;
return result;
}
It returns result : 24
i.e 4*3*2*1= 24
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.