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> 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. 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!! 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
Archived
This topic is now archived and is closed to further replies.