Reputation: 19
I want to write a program that adds all the numbers between 0 and 100 but my code does not add everything correctly. How do I add the next number to the number and then print the sum?
This is the code I have:
for(int i = 0; i <= 100; i++){
i+=i;
println(i);
}
The result of this shows 0, 2, 6, 14... and I need the sum of all the numbers 1 through 100.
Upvotes: 0
Views: 908
Reputation: 951
The reason you are getting this odd result is that you add those numbers to i instead of having a dedicated collector.
int collector = 0;
for (int i = 0; i <= 100; i++) {
collector += i;
println(collector);
}
If you only want to print the sum once, move the println(collector) expression outside the loop.
There is also a mathematical formula to directly compute the sum of the first n numbers
Sum(1, n) = n * (n+1) / 2
In Processing:
int Sum(int n){
return n * (n + 1) / 2;
}
The formula works because the numbers 1 to N can be rearranged and added like this:
(1 + N) + (2 + N-1) + (3 + N-2) + . . . . + (N + N/2+1) = total
for N = 100:
(1 + 100) + (2 + 99) + (3 + 98) + . . . . + (50 + 51) = 5050
101 + 101 + 101 + . . . . + 101 = 5050
Upvotes: 3