1// Method 1: Mathematical -> Sum up numbers from 1 to n
2int sum(int n){
3 return (n * (n+1)) / 2;
4}
5
6// Method 2: Using a for-loop -> Sum up numbers from 1 to n
7int sum(int n){
8 int tempSum = 0;
9 for (int i = n; i > 0; i--){
10 tempSum += i;
11 }
12 return tempSum;
13}
14
15// Method 3: Using recursion -> Sum up numbers from 1 to n
16int sum(int n){
17 return n > 0 ? n + sum(n-1) : 0;
18}