# Sum with for-loop, while-loop and recursion

Question:
Write three functions that compute the sum of the numbers in a list using a for-loop.

## For loop

For loop consists of three parts: declaration (int i = 0), the condition (i < input.size) and update (i++). Separate these three with a semicolon, and you're good to go!

## While loop

Very similar to a for-loop without the added convenience of a one-liner.

## Recursion

Remember to declare the base case and go from there.

import java.util.ArrayList;

public class Sum {
public static void main(String[] args) {
ArrayList<Integer> test = new ArrayList<>();
for (int i = 0; i < 5; i++) {
}

System.out.println(sumForLoop(test));
System.out.println(sumWhileLoop(test));
System.out.println(sumRecursion(test, 0));
}

static int sumForLoop(ArrayList<Integer> test) {

int sum = 0;

for (int i = 0; i < test.size(); i++) {
sum += test.get(i);
}

return sum;

}

static int sumWhileLoop(ArrayList<Integer> test) {

int i = 0;
int sum = 0;

while (i < test.size()) {
sum += test.get(i);
i++;
}

return sum;
}

static int sumRecursion(ArrayList<Integer> input, int index) {

if (index == input.size()) {
return 0;
} else {
return input.get(index) + sumRecursion(input, index+1);
}

}
}

Came up with a better solution or have a question? Comment below!