Java Program to Compute the Sum of Numbers in a List Using Recursion
ArrayList is a part of the Collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package.
Input : [1, 3, 9] Output : 13
Here the naive method can be to add up elements of List and maintain a counter in which sum is stored while traversing List. The step ahead method can be to convert the List to the array and do the same. Now more optimal method can be to use recursion while doing so in which subpart of List or array is automatically computed by recursion principles. Here this optimal approach is described and implemented as shown.
- Converting ArrayList to arrays and using recursion principles over arrays.
- Using ArrayList.add() method
Method 1: Converting ArrayList to arrays and using recursion principles over arrays.
It is achieved by converting ArrayList to arrays and using recursion principles over arrays. Recursion in the list to array conversion and computing sum of elements using add() method.
- Take the elements of the list as input from the user.
- Convert the list into an array of the same size.
- Add the elements to it.
- Compute the sum of arrays using recursion principles.
Elements in List : 1 2 3 4 5 Sum of elements : 15
Method 2: Using ArrayList.add() method
This method appends the specified element to the end of this list
public boolean add(E element) ;
Parameter: Object to be appended to this list.
Return Type: It will always return a boolean true and the signature is as so because other classes in collections family need a return type.
Elements in List : [10, 90, 30, 40, 70, 100, 0] Sum of elements in List :340