user5947618
user5947618

Reputation:

JAVA using a loop to find the sum from 0 to x

I want to use a loop to find the sum of 0, to X. So if the user prints out 5 then the sum is 15.

int sum = 1;
for (int i=1; i<x; i++) {
    sum=sum+i;
}
System.out.println("The sum of 0 up to " + x + " is: " + sum );

Using this code above I've only been getting 11. What am I doing wrong?

Upvotes: 0

Views: 194

Answers (3)

Isuranga Perera
Isuranga Perera

Reputation: 510

You should use your for loop like this :

for (int i=1; i<=x; i++) {
    sum=sum+i;
}

In addition to that if you need to improve the performance you can replace for loop which has O(n) time complexity with a single formula which has O(1) time complexity.

int x = 5;
int sum = x*(x+1)/2;
System.out.println("The sum of 0 up to " + x + " is: " + sum);

Upvotes: 1

Heri
Heri

Reputation: 4578

Several errors in your code

  1. initialize sum to 0
  2. iterate from 1 to x, not from 1 to x - 1

    int x = 5;
    int sum = 0;
    for (int i=1; i<=x; i++)
    {
       sum = sum + i;
    }
    
    System.out.println("The sum of 0 up to " + x + " is: " + sum);
    

Upvotes: 3

Hellzzar
Hellzzar

Reputation: 195

First of all set sum equals to 0 as you have nothing accumulated yet. Second of all you need to reach the last number so your iterator needs to be les or equals to number.

int sum = 0;
for (int i=1; i<=x; i++)
{
   sum=sum+i;
}
System.out.println("The sum of 0 up to " +x+ " is: " +sum );

Upvotes: 0

Related Questions