In: Computer Science
The following code was meant to print out the elements in an array in reverse order. However, it does not behave correctly.
public static void reverse(int[] a, int index) {
if (index == (a.length - 1))
System.out.printf("%d%n", a[index]);
else {
reverse(a, index);
What does it do? Explain why it behaves in this way and There is more than one error in the code. Correct the code so that it will recursively print out the elements of the array in reverse order. Highlight your changes clearly (in bold with yellow highlight) and complete the following main method to show how you would invoke your corrected reverse method to test that it now works correctly.
public static void main(String[] args) {
int [] array = { 1, 2, 3, 4, 5 };
//Part c: call reverse to print array in reverse order
<corrected code here>
}
What does it do?
It keeps on printing the last element and finally a stackoverflow error will occur.
Explain why it behaves in this way?
The reason is the index is not decremented. After each print, the index needs to be decremented and call the function recursively. There is no need for the else part. It will never go to the else part as the index is not decremented and hence recursive call will not take place here.
The corrected code in Java pasted below. The corrected function is shown in red color.
class ArrayReverse1{
public static void reverse(int[] a,
int index) {
if (index >0)
{
index= index - 1; // Decrementing the index
System.out.printf("%d%n", a[index]);
reverse(a, index); // Recursive call
}
return;
}
public static void main (String args[])
{
int [] array = { 1, 2, 3, 4, 5 };
int n=array.length;
reverse(array,n); // function call
}
}
Output Screen