Software Engineering

# How to Calculate the Summation of a Number in Java

## The challenge#

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

``````summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
``````

## The solution in Java#

``````public class Solution {

public static int summation(int n) {
int runningTotal = 0;

for (int i=1; i<=n; i++) runningTotal += i;

return runningTotal;
}
}
``````

A simpler alternative is to do the following:

``````public class Solution {

public static int summation(int n) {

return  n*(n+1)/2;
}
}
``````

This can also be solved using recursion:

``````public class Solution {

public static int summation(int n) {
if (n == 1)
return 1;
return summation(n-1) + n;
}
}
``````

## Test cases to validate our code#

``````import java.util.Random;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class SolutionTest {
@Test
public void test1() {
assertEquals(1,
Solution.summation(1));
}
@Test
public void test2() {
assertEquals(36,
Solution.summation(8));
}
}
``````