Reputation: 13
I'm creating a method that's essentially trying to grab the mean of an array. I initialized an integer sum to 0 outside of the for loop, ran the for loop, and tried returning the sum.
This is what my code looks like:
int sum = 0;
for (int i = 0; i < array2.length; i++)
{
sum += array2[i];
return sum;
}
return sum / array2.length;
Upon running, it only returns the value I originally initialized sum to.
(I didn't include the code for array2, just assume I initialized it beforehand.)
Upvotes: 0
Views: 381
Reputation: 26703
int sum = 0;
for (int i = 0; i < array2.length; i++)
{
sum += array2[i]; // sum is increased, but only for i==0
return sum; // loop is left first time, making loop futile
}
return sum / array2.length; // never reached for length > 0
The problem is the return inside the loop, which cannot ever be what you want.
Just delete the return sum;
to have the second return do what you intend it to,
i.e. loop over the length of the array, accumulate sum
and after the loop retrn the average.
By the way, if you observe that sum
is returned as initialised, it can be if array[0]
is 0, otherwise not.
Upvotes: 1