Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Oct 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    'While' Loop Question in Basic Javascript Program

    I am having trouble figuring out where to put the 'while' loop. After the program has gone through, i would like to have a prompt for the user to restart the program, Y would restart and N would terminate it. Thanks for the help!

    <script type="text/javascript">
    //<![CDATA[
    function runJS()
    {
    var sum = 0;
    var average = 0;
    var count = parseFloat(prompt("How many numbers do you want to sum up?", "3"));
    var i=0;
    var total=1;
    var number=0;
    {
    for (var i=1; i<=count; i=i+1)
    {
    number=prompt("Enter #"+i, "");
    total=total*parseFloat(number);
    }

    average = sum/3;
    alert("The average is: " + average + ".\nThe sum is: " + sum + ".");
    }
    //]]>

    more= prompt("Would you like to do another calculation? (Y/N)", "Y");}
    </script>
    </head>
    <body onload="runJS();">
    </body>

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,190
    Thanks
    10
    Thanked 569 Times in 550 Posts
    no need for "while"...
    Code:
    <script type="text/javascript">
    //<![CDATA[
    function runJS(){
    var sum = 0;
    var average = 0;
    var count = parseFloat(prompt("How many numbers do you want to sum up?", "3"));
     var i=0;
     var total=1;
     var number=0;
     
     for (var i=1; i<=count; i=i+1) {
         number=prompt("Enter #"+i, "");
         total=total*parseFloat(number);
     }
    
     average = sum/3;
    alert("The average is: " + average + ".\nThe sum is: " + sum + ".");
    if( prompt("Would you like to do another calculation? (Y/N)", "Y") ){runJS();}
    }
    //]]>
    </script>
    </head>
    <body onload="runJS();">
    </body>
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •