sum of array recursion java

‮h‬ttps://www.lautturi.com
sum of array recursion java

To find the sum of all the elements of an array using recursion in Java, you can define a recursive function that takes the array and the index of the current element as arguments, and returns the sum of the elements of the array starting from the current index.

Here's an example of how to define a recursive function to find the sum of all the elements of an array:

public static int sumArray(int[] array, int index) {
    if (index == array.length) {
        return 0;
    }
    return array[index] + sumArray(array, index + 1);
}

In this example, the sumArray function takes an array and an index as arguments and returns the sum of the elements of the array starting from the current index. The base case of the recursion is when the index reaches the end of the array, in which case the function returns 0. In the recursive case, the function returns the value of the current element plus the sum of the remaining elements.

To use this function to find the sum of all the elements of an array, you can call it with the array and an initial index of 0:

int[] array = {1, 2, 3, 4, 5};
int sum = sumArray(array, 0);
System.out.println(sum);  // prints 15

You can find more information about recursion in Java in the Java documentation.

Created Time:2017-10-17 20:18:56  Author:lautturi