Recursive Functions in Java

in deutsch •  last year 

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();
    }
}




Posted from https://blurtlatam.intinte.org

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  
  ·  last year  ·  

Dear @ozelot47, your content was selected manually by curators @nalexadre, @ten-years-before to receive a curation from BeBlurt 🎉

image
BeBlurt (Blurt frontend): https://beblurt.com
 
BeBlurt Delegation program: manual curation + 85% reward back
 

  ·  last year  ·  

Thank you for your support!


Posted from https://blurtlatam.intinte.org