Java Please specify each part in your code Edit: As this is a java question, ple
ID: 3589455 • Letter: J
Question
Java
Please specify each part in your code
Edit: As this is a java question, please list what is printed when the method is invoked. Do not "trace on paper" (are you kidding me??)
Part 1
Trace the execution of the following method by listing what is printed when the method is invoked with the following parameters:
array = [12, 5, 6, 2, 3, 4, 7]
a=2
b=5
void recMethod(int[] array, int a, int b) {
if(b > a) {
print the array
double the value in the array at position b
recMethod(array, a, b-1)
print the array
} else {
print "done"
}
}
Part 2
Trace the execution of the following method by listing what is printed when the method is invoked with the first node in the following chain: 4 -> 6 -> 5 -> 3 -> 2
void recMethod(Node firstNode) {
print the chain of nodes headed by firstNode
if(firstNode.next!=null) {
double the data in firstNode
recMethod(firstNode.next.next);
} else {
print "done"
}
print the chain of nodes headed by firstNode
}
Explanation / Answer
Given method is
void recMethod(int[] array, int a, int b){
if(b>a){
System.out.println(Arrays.toString(array));
array[b] = 2*array[b];
recMethod(array,a,b-1);
System.out.println(Arrays.toString(array));
}
else{
System.out.println("done");
}
}
let's trace the recursion
a b array
2 5 {12,5,6,2,3,4,7} Now, array[5] is doubled
2 4 {12,5,6,2,3,8,7} array[4] is doubled
2 3 {12,5,6,2,6,8,7} array[3] is doubled
2 2 b>a is false, "done" will be printed
---while tracking back----
2 3 {12,5,6,4,6,8,7}
2 4 {12,5,6,4,6,8,7}
2 5 {12,5,6,4,6,8,7}
2. Given method
void recMethod(Node firstNode){
printNodes(firstNode);
if(firstNode.next!=null){
firstNode.data = 2*firstNode.data;
recMethod(firstNode.next)
}
else{
print("done")
}
printNodes(firstNode)
}
Given chain 4->6->5->3->2
node chain
4. 4->6->5->3->2 4 is doubled
6 8->6->5->3->2 6 is doubled
5 8->12->5->3->2 5 is doubled
3 8->12->10->3->2 3 is doubled
2 8->12->10->6->2
Next Node of 2 is null. So, 'done' is printed
while tracking back
2. 8->12->10->6->2
3 8->12->10->6->2
5 8->12->10->6->2
6 8->12->10->6->2
4 8->12->10->6->2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.