200k views
5 votes
Write a recursive function called sum_values that takes in a list of integers and an index of one element in the list and returns the sum of all values/elements in the list starting with the element with the provided index and ending with the last element in the list.

1 Answer

6 votes

Answer:

Step-by-step explanation:

The following code is written in the Java programming language and actually takes in three parameters, the first is the list with all of the int values. The second parameter is the starting point where the adding needs to start. Lastly is the int finalSum which is the variable where the values are all going to be added in order to calculate a final int value. Once the recursive function finishes going through the list it exits the function and prints out the finalSum value.

public static void sum_Values(ArrayList<Integer> myList, int startingPoint, int finalSum) {

if (myList.size() == startingPoint) {

System.out.println(finalSum);

return;

} else {

finalSum += myList.get(startingPoint);

sum_Values(myList, startingPoint+1, finalSum);

}

}

User Tomfanning
by
4.4k points