Ad
  • Custom User Avatar

    Thanks Rambutan for still providing golden nuggets of knowledge 6 years later! I'm new too and while I did solve the problem this is a great explaination/break down on incrementing and loops.

  • Default User Avatar

    Its good practice to brake operations into a few function. This would increase readability and reusability. Plus you can unit test functions seperately.

  • Custom User Avatar
  • Custom User Avatar

    thanks! We all start off at the beginning!

  • Custom User Avatar

    Thank you so much, this is an amazing answer! I was forgetting to make it "i += 1" rather that "i + 1" because, as I said, I'm very inexperienced.

  • Custom User Avatar

    var i = 1
    i + 1 = 2

    the value of i is not changed by this.

    the for loop has the following structure

    initial state(i = 1)
    while condition ( i is less than or equal to n)
    increment value (how much i will increase each loop

    i + 1 does not provide a consistent increase. it is an expression that evaluates to the number 2

    the correct why to express this is:

    i = i + 1

    that is take the current value of i (whatever it currently it is) and add 1 to it
    then assign this new value to i

    so if var i = 1
    i = i + 1 // i is now 2
    i = i + 1 // i is now 3

    if you write :

    for (var i = 1; i <= n; i = i + 1)

    the loop will work correctly

    BUT a shorthand for writing i = i + 1 is:

    i += 1

    so this also works

    for (var i =1; i <= n; i += 1)

    and there is a further shorthand for i += 1

    and that is :

    i++

    finally you have the commonest for loop:

    for (var i = 1; i <= n; i++)

    actually, it's not quite the commonest. that would be:

    for (var i = 0; i < n; i++)

    but i + 1 as an incrementer doesn't work

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution