Your loop condition (sum < n)
is incorrect since sum
will very soon be greater than the final term value n
.
But, You can do this without a loop:
sum = n / 2 * (2 + (n / 2 - 1))
Where n
is even and positive as you describe. This comes from the formula for an arithmetic progression sum.
If you really want to use a for
loop then use
int sum = 0;
for (int i = 2; i <= n; i += 2){
sum += i;
}
or, if you want a while
then use
int sum = 0;
{ /*extra scoping block so we don't emit i*/
int i = 0;
while ((i += 2) <= n){
sum += i;
}
}
noting that (i += 2)
is an expression evaluated to the incremented value of i
.