Recursive Functions in Java

avatar

In a recursion, the same function is called over and over again until a suitable termination condition is reached. If this is missing, a so-called stack overflow occurs. Examples of recursions are the Fibonacci numbers or this example here. Numbers from the list are summed up until only one number remains.

import java.util.List;
import java.util.ArrayList;

public class Recursion {

    private List<Integer> numbers;

    public Recursion(){
        numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        numbers.add(10);
        System.out.println("Sum : " + addRecursive(numbers));
    }

    private Integer addRecursive(List<Integer> numbers){
        if(numbers.size() >= 2){
            Integer one = numbers.get(0);
            Integer two = numbers.get(numbers.size()-1);
            Integer sum = one.intValue() + two.intValue();
            numbers.set(0, sum);
            numbers.remove(numbers.size()-1);
            addRecursive(numbers);
        }
        return numbers.get(0);
    }

    public static void main(String[] args) {
        new Recursion();
    }
}



0
0
0.000
4 comments
avatar

!LOL
!SLOTH
!BEER

0
0
0.000
avatar

Recursive Functions are also a great way to loop through data without the use of literal loops. Great article.

0
0
0.000