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();
}
}
Dear @ozelot47, your content was selected manually by curators @nalexadre, @ten-years-before to receive a curation from BeBlurt 🎉
Thank you for your support!