user10833638
user10833638

Reputation:

How do I calculate the sum of all numbers from 0 to n?

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

Answers (8)

ernest_k
ernest_k

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

Mureinik
Mureinik

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

vjanovec
vjanovec

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

Ismail
Ismail

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

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

Since you want from 0 to n you could use IntStream e.g.

IntStream.rangeClosed(0, n).sum()

Upvotes: 1

HerickC
HerickC

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

Ruslan
Ruslan

Reputation: 6290

You could use sum from IntStream:

return Arrays.stream(params).sum();

Upvotes: 2

Rakesh Mothukuri
Rakesh Mothukuri

Reputation: 159

int sum = 0;
for (int i = 0; i <= n; i++) {
 sum = sum + i;
}
System.out.println(sum);

Upvotes: 0

Related Questions