Skip to content

Instantly share code, notes, and snippets.

@salzig
Created October 21, 2011 11:54
Show Gist options
  • Save salzig/1303652 to your computer and use it in GitHub Desktop.
Save salzig/1303652 to your computer and use it in GitHub Desktop.
Rekursive Summe von Array Elementen
import java.util.Arrays;
import java.util.List;
public class Test {
/**
* @author Ben Rexin <[email protected]
*/
public static void main(String[] args) {
List<Integer> array = Arrays.asList(1,2,3,4);
System.out.println(sum(array));
}
/**
* @author Ben Rexin <[email protected]
* @param list of Integer
* @return Integer
*/
public static Integer sum(List<Integer> list) { return sum(list,0,0); }
/**
* @author Ben Rexin <[email protected]
* @param list of Integer
* @param index as position within list
* @param accu sum of elements in list from 0 to index
* @return Integer
*/
public static Integer sum(List<Integer> list, Integer index, Integer accu) {
if (list == null || index == null || accu == null) throw new IllegalArgumentException();
return index == list.size() ? accu : sum(list, index +1, accu + list.get(index));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment