Page 1 of 1

Need help with formula to add up a series

Posted: Sat Apr 14, 2012 3:46 pm
by drayarms
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.

Code: Select all


		<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>



Re: Need help with formula to add up a series

Posted: Sat Apr 14, 2012 6:18 pm
by requinix
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.