Jump to content

Need help with formula to add up a series


drayarms

Recommended Posts

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>


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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.