Help Needed Please!

Sorry guys but i have a bit of a dumb question for the life of me I cannot get my head around the following

function sumFirstN(n) {
    let sum = 0;
    if ( n < 0 ) {
        sum = NaN;
    } else {
        for ( let i = 1;i <= n;i += 1){
            sum += i;

        }
    }
    return sum;
}

sumFirstN(5)
15

my question is how does the output = 15 i just dont get it ??
I understand it is a loop but i dont see how it came to equallying 15
if i = 1; i <= n(which i presume is now 5); 1+=1
sum +=1
i dont understand how it gets to 15

Hey @OzzieAl, hope you are well.

For each iteration on the loop, the loop will continue until is equal to n, so each iteration, it will add the value of i to sum.

Its easier to see the functionality if you add some few console lines to see the behavior on each iteration:

function sumFirstN(n) {
    let sum = 0;
    if ( n < 0 ) {
      console.log("N is less than 0")
        sum = NaN;
    } else {
      console.log(`else: (${n})`)
        for ( let i = 1;i <= n;i += 1){
            sum += i;
          console.log(`iterator:${i}, sum[${sum}]`);
        }
    }
    return sum;
}

Console result:
image

Hope this helps :nerd_face:

Carlos Z

Hmmm thanks a little
what i cant understand is the following bit of code

let i = 1;i <= n;i += 1 to me that looks like i=1 and i is less than and equal to the ( number inputed (n ) and then i = (i+i) +1

so looking at your console I suppose i struggle to understand how sum[3] actually became three

The for loop has the following syntax:

for ( *statement 1* ;  *statement 2* ;  *statement 3* ) {
  //  *code block to be executed*
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

So, in our code, it fulfill the same concept:

for ( let i = 1;i <= n;i += 1){
            sum += i;
          console.log(`iterator:${i}, sum[${sum}]`);
        }

Our definitions are:
let i = 1 iterator variable and starting value.
i <= n while i is less or equal to n
i +=1 add 1 to i value for every iteration.

Carlos Z

Ah Ha
yes that now makes sense
Thanks Carlos
greatly appreciated

1 Like