user4823446
user4823446

Reputation:

How to sum an ArrayList<Integers> using recursion?

I want my method to sum a list of integers using recursion and return that list.

Here is my attempt:

    public static int sumListRecursive(List<Integer> numbers) {
        if (numbers.isEmpty() == true ) {
            return 0;
        }
        else {
            System.out.println(numbers.get(0) + sumListRecursive(numbers.subList(1, numbers.size())));
            return numbers.get(0) + sumListRecursive(numbers.subList(1, numbers.size()));
        }
    }

And in my main method I have this:

        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        sumListRecursive(numbers);

And when i run the program I get this in console: 10 4 7 4 9 4 7 4

So what's wrong?

Upvotes: 4

Views: 4267

Answers (1)

Raf
Raf

Reputation: 7649

I have provided the explanation in the code in the form of comment. He has to print the sum in the main after recursive function finished. Putting the print statement in the recursive function causes a value to be printed in the console every time.

See the correction below:

 public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        //print the sum in here 
        System.out.println(sumListRecursive(numbers));


    }

    public static int sumListRecursive(List<Integer> numbers) {
        if (numbers.isEmpty() == true ) {
            return 0;
        }
        else {
            /* removed the print statement from here as it prints each time the function is called and else is executed. */
            return numbers.get(0) + sumListRecursive(numbers.subList(1, numbers.size()));
        }
    }

Upvotes: 3

Related Questions