I am trying to learn recursion, which is a slippery concept for me. I've worked through a number of toy exercises using recursion to manipulate primitive data types and strings. But now I'm pivoting to using recursion and arrays, and here I'm stumped. I'm hoping someone can help me with perhaps the first initial step(s) in thinking about this problem.
Here's the challenge: Use recursion to set all the elements in a 1D int[] array to all 0's. No looping allowed. Conceptually, I think the solution would be:
method clearArray(int[] array)
Check for base case: Is array of size 1?
IF YES: return array
IF NO:
(-) Create array2, size one less than original array
(-) Set first element of array2 to "0"
(-) Then recursively call clearArray(array2)
On paper, this looks great. Here's the actual implementation:
public class RecursiveEx{
public static void main(String[] args){
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
printArray(clear(arr));
}
public static int[] clearArray(int[] arr){
if(arr.length==1){
return arr;
}
else{
int[] arr2 = new int[arr.length-1];
arr2[0]=0;
return clearArray(arr2);
}
}
This returns an array of size 1, set to "0". No good. The problem is that while the code recursively chops the array down to one element, it does not build the original array back up to its original size; I don't know how to append the subarrays.
With a String this would be easy. But the String object allows for easy-to-use concatenation and substring methods. I can't figure out what the array equivalent would be.
FULL DISCLOSURE: I am taking a Java 101 course at Rutgers University, and yes, this is the first of several programming exercises they give us using recursion and arrays. Its not for credit. I'm hoping that if someone can help me get started with this initial exercise, I can see where I'm going wrong and then knock out the others.
Does anyone have some advice or recommendations? Anything would be appreciated.
Many thanks! -RAO
arr2are zero already; settingarr2[0] = 0;is redundant.Arrays.fill(arr, 0)count as using a loop?return new int[arr.length]would work, but it isn't really a recursive solution :)