Reputation:
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
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
Reputation: 4578
Several errors in your code
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
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