Is it correct to use many parameters in a recursive method?

Viewed 63

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);
    }
}
1 Answers

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.

Related