Recursive Functions in Java
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
!LOL
!SLOTH
!BEER
Learn more about the SLOTHBUZZ Token at Sloth.Buzz and consider sharing your post there or using the #slothbuzz next time
(1/2)
lolztoken.com
Boara Boara.
Credit: reddit
@ozelot47, I sent you an $LOLZ on behalf of dotwin1981
(8/10)
ENTER @WIN.HIVE'S DAILY DRAW AND WIN HIVE!
Recursive Functions are also a great way to loop through data without the use of literal loops. Great article.