You need to decouple your "sum" variable and your index variable.
Introduce another variable to hold the sum:
public void countOneToTen() {
int sum = 0;
int index = 1;
while (index <= 10) {
sum += index;
index++;
}
System.out.println(sum);
}
Also, use for loops to limit variable scope:
public void countOneToTen() {
int sum = 0;
for (int index = 1; index <= 10; index++) {
sum += index;
}
System.out.println(sum);
}
Your approach didn't work because your index should go from 1
to 10
, but the moment you modify it you throw this iteration off course.
Here's what I mean:
index = 1
// index: 1
index = index + index = 2
// index: 2
index = index + index = 4
// We've skipped 3.
// etc.
index = index + index = 8
index = index + index = 16 > 10
1 + 2 + 4 + 8 = 15
Just for fun, here's the Java 8 stream approach:
IntStream.rangeClosed(1, 10).sum();
(thanks to Oleg for pointing out the existence of rangeClosed
)
:)
and here's the single-statement approach using the general summation of an arithmetic sequence:

int sum = terms * (min + max) / 2;