the sum of all first n natural numbers js 1

the sum of all first n natural numbers js

// return the sum of the first n even numbers recursively. Assume n > 0

function firstEvenNumbersSum(n) {
    if (n === 0) {
        return 0;
    }
    let num = (n * 2);
    let sum = num + firstEvenNumbersSum(n-1)
    return sum;
}

Here is what the above code is Doing:
1. If n is 0, return 0
2. If n is not 0, multiply n by 2 to get the next even number
3. Add that number to the sum of the first n-1 even numbers

Similar Posts