I'm learning about recursive methods and I was wondering if it is correct to use many parameters in my recursive method because its not possible to retain information in another way. I am trying to calculate the sum of one array.
public static void main (String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
int sum = arraySum(array, array.length);
System.out.println(sum);
}
public static int arraySum(int[] array, int arrayLength) {
if (arrayLength < 1) {
return 0;
} else {
int x = array[arrayLength-1];
return x arraySum(array, arrayLength-1);
}
}
CodePudding user response:
2 isn't "many", so I'm not quite sure if the question is: "Is this code okay?" or the question is more generic and the code snippet is mostly unrelated.
Yes, that's the way to send info from one recursive call to the next: With parameters.
If you have a ton you can always make an object that contains them all, and then just pass an instance of that. Generally you'd have to make a new
one every time.
CodePudding user response:
You can pretty much use as many parameters as possible, though conventions would probably recommend using as few parameters as possible. But two parameters are for sure no issue. If you absolutely want to reduce the number of parameters used, you could do something like this:
public static void main (String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
int sum = arraySum(array);
System.out.println(sum);
}
public static int arraySum(int[] array) {
if (array.length == 1) {
return array[0];
} else {
return array[array.length - 1] arraySum(Arrays.copyOfRange(array, 0, array.length - 1));
}
}
Basically the thing is, you´re saying "its not possible to retain information in another way." which is not true. The thing is, your first argument, the array, does not change per call of the function. That is not necesseray. You can wrap the information of the second argument, the range of the array for the next function call, into the first the argument, the array, by just giving a part of the array as the new argument, instead of the whole array every call of the function.