We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
Sum Array (Read 1147 times)
Sum Array
Apr 16th, 2006, 12:25pm
 
Hi,
I'm relatively new to processing (about 3 months) and am experiencing difficulties 'summing' the values stored in an array. A very basic question I'm sure but I'm struggling none the less. Does anyone have any suggestions?
Many thanks

Andy
Re: Sum Array
Reply #1 - Apr 16th, 2006, 1:54pm
 
For a previously declared array, try:

Code:


int sum = 0;

for (int i=0; i<array.length; i++) {
sum += array[i];
}

println ("sum of array values = " + sum);


Re: Sum Array
Reply #2 - Apr 16th, 2006, 2:18pm
 
Hi again,
thanks for the quick reply. I have already tried the 'for' loop idea, which certainly works, but (probably due to my code layout) continuously adds to the array total.

For example:

int[] points = new int[3];
points[0] = 1;
points[1] = 0;
points[2] = 0;

Obvously the sum of this array is 1, but with my setup the calculation adds 1 with every frame.

I have set up a void() to calculate the sum of the array, and then call upon the void() within the draw command.  Any ideas why the array keeps on adding '1' each time and hence does not give me the sum?

Many thanks
Re: Sum Array
Reply #3 - Apr 16th, 2006, 6:48pm
 
Have you got more code, just to see what's happening in context?
Re: Sum Array
Reply #4 - Apr 16th, 2006, 8:31pm
 
are you resetting the sum variable to 0 before the loop? if not you will keep adding the next calculation to the last.
Page Index Toggle Pages: 1