drayarms Posted April 14, 2012 Share Posted April 14, 2012 Hello, I'm trying to use the for loop below to add up a series of numbers, but all I get is the sum of the first number only. How can I accomplish this? How can I make the function recursive? Thanks. <script type = "text/javascript"> function sum(){ for(j=1; j<5; j++){ x=0; //Initialize the horizontal displacement x += j; return x; } }//Function end alert(sum()); </script> Quote Link to comment https://forums.phpfreaks.com/topic/260946-need-help-with-formula-to-add-up-a-series/ Share on other sites More sharing options...
requinix Posted April 15, 2012 Share Posted April 15, 2012 As I answered elsewhere, You're initializing x inside the loop. That means it initializes every single time. Move it outside (before) the loop. Then you return the value inside the loop. That means the code doesn't get a chance to sum up everything. Move it outside (after) the loop. Quote Link to comment https://forums.phpfreaks.com/topic/260946-need-help-with-formula-to-add-up-a-series/#findComment-1337429 Share on other sites More sharing options...
drayarms Posted April 15, 2012 Author Share Posted April 15, 2012 @requinix. thanks, that was it!! Quote Link to comment https://forums.phpfreaks.com/topic/260946-need-help-with-formula-to-add-up-a-series/#findComment-1337472 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.