Reputation:
So I'm trying to calculate all the numbers from 0 to a given number (n) with a loop as seen in my code but I just can't seem to manage how.
public static int sumOfNumbers(int... params) {
int sum = 0;
for (int i : params) {
sum = i;
};
return sum;
}
Upvotes: 2
Views: 19360
Reputation: 45309
This is the sum of numbers in a series, so you can do this in O(1) using:
int sum = n * (n + 1) / 2;
Where n
is the highest number in params
, params
being an array/collection of numbers from 0
to n
.
Upvotes: 4
Reputation: 311073
You're overwriting sum
, not adding to it. You should use the +=
operator instead of the =
operator:
sum += i;
Alternatively, you can treat this as a mathematical problem, and use the formula for the sum of an arithmetic progression:
public static int sumZeroToN(int n) {
return n * (n + 1) / 2;
}
Upvotes: 14
Reputation: 16
Use for loop, not for each loop! For each loop use with a List.
int sum = 0;
for(int i=0; i<n; i++) {
sum += i // same as sum = sum + i;
}
return sum;
Or simply use:
int sum = n * (n + 1) / 2;
Upvotes: 0
Reputation: 2962
you are trying to calculate an arithmetic series sum so you can just do this without a loop:
sum=((param+1)*param)/2;
param is the given number.
Upvotes: 2
Reputation: 37584
Since you want from 0 to n you could use IntStream
e.g.
IntStream.rangeClosed(0, n).sum()
Upvotes: 1
Reputation: 344
You are overwriting the var sum each loop, and forgetting to sum, you need alter your code to something like this:
public static int sumOfNumbers(int... params) {
int sum = 0;
for (int i : params) {
sum += i; //Same as sum = sum + 1;
};
return sum;
}
Upvotes: 1
Reputation: 6290
You could use sum
from IntStream
:
return Arrays.stream(params).sum();
Upvotes: 2
Reputation: 159
int sum = 0;
for (int i = 0; i <= n; i++) {
sum = sum + i;
}
System.out.println(sum);
Upvotes: 0