Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

JavaScript crashes while squaring number

  1. Sep 10, 2012 #1
    Is this a legit code for printing out squares of numbers betwean 100 and 150 ??? Seems to crash everytime.

    for (var i=100; i<151; i*i)
    {
    var square = i;
    console.log(square);
    }

    Need help :)
     
  2. jcsd
  3. Sep 10, 2012 #2

    phinds

    User Avatar
    Gold Member
    2016 Award

    No, the upper limit on your loop is a function of the loop variable, which doesn't make sense, and you have no code IN the loop that is actually squaring anything.
     
  4. Sep 10, 2012 #3

    uart

    User Avatar
    Science Advisor

    The problem is not really the upper limit (i<151) but the lack of an increment for the loop variable.

    Your "increment" seems to be "i*i", but that's not assigned to anything, so it makes no changes to "i".

    If you had written "i=i*i" then it still wouldn't work, but at least it wouldn't crash (presumably due to the infinite loop).

    You need to increment "i" within the loop, and assign "i*i" to your variable "square" within the loop body.
     
    Last edited: Sep 10, 2012
  5. Sep 12, 2012 #4
    The general syntax of the for loop might be expressed like:

    for ( start; stop; increment) {
    //do stuff
    }


    By "You need to increment "i" within the loop" you mean i should increment within the body of the statement?

    Like:

    for (var i=100; i<151; i=square)
    {
    var square = i*i;
    console.log(square);
    }


    I guess not. Since I get the error: "TypeError: Property 'eval' of object [object Window] is not a function".

    I didn't know what to put into the "increment" part of the for loop - so I assigned square (or tried to assign, if it is not allowed).

    I would very much appreciate clarifications :)
     
    Last edited: Sep 12, 2012
  6. Sep 12, 2012 #5

    uart

    User Avatar
    Science Advisor

    Ok it's just your "increment" that's wrong now. The increment is extremely important. The loop variable "i" must be increased each time the loop is executed otherwise it will never reach 151 and therefore the loop with never end. (this is why your program is "hanging").

    Try
    Code (Text):

    for (var i=100; i<151; i=i+1)
    {
        var square = i*i;
        console.log(square);
    }
    BTW. Most people prefer to use the increment operator "i++", which does the same as thing "i=i+1". I used the "i=i+1" for clarity, but either "i++" or "i+=1" will work the same way.
     
    Last edited: Sep 12, 2012
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: JavaScript crashes while squaring number
  1. Javascript Help (Replies: 4)

  2. Frontpage JavaScript (Replies: 3)

  3. Javascript problem (Replies: 6)

Loading...