Need help with formula to add up a series

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
drayarms
Forum Contributor
Posts: 134
Joined: Fri Dec 31, 2010 5:11 pm

Need help with formula to add up a series

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


User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Need help with formula to add up a series

Post 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.
Post Reply