# Counter that adds 2 in 2

5

It is my first post in this forum, I am starting to program, and this question has arisen in an exercise. I have to find the sum of the next 20 numbers to a number entered by keyboard, and the sum of the next 20 even numbers. This is my code:

``````if(numero%2==0){
boolean par=true;
}else{
boolean par=false;
}

if(par==true){

for(int i=numero, j=numero+40;i<=j;i+2){   //Este i+2 es lo que tengo mal
total_par=total_par+i;
}
}else{

for(int i=numero+1,j=numero+40;i<=j;i+2){  //Aquí también
total_par=total_par+i;
}
}
``````

Thanks

asked by MigherdCas 01.11.2016 в 14:11
source

11

`i+2` should be changed to

``````i = i + 2
``````

or

``````i += 2
``````

Choose the one you prefer.

source
4

You can also use a formula:

``````int total;
if (num % 2 == 0) {
// k + k + 2 + k + 4 + k + 6 + ... + k + 40
// k + 20k + 2 + 4 + 6 + ... + 40
// k + 20k + 20 * (20 + 1)
// 21k + 420
total = 21 * num + 420;
} else {
// k + k + 1 + k + 3 + k + 5 + ... + k + 39
// k + 20k + 1 + 3 + 5 + ... + 39
// k + 20k + 20 * 20
// 21k + 400
total = 21 * num + 400;
}
System.out.println(total);
``````
• If `num = 1` , then `1` plus the next 20 even numbers is `1 + 2 + 4 + 6 + 8 + 10 + 12 + 14 + 16 + 18 + 20 + 22 + 24 + 26 + 28 + 30 + 32 + 34 + 36 + 38 + 40 = 421` .
• If `num = 2` , then `2` plus the next 20 even numbers is `2 + 4 + 6 + 8 + 10 + 12 + 14 + 16 + 18 + 20 + 22 + 24 + 26 + 28 + 30 + 32 + 34 + 36 + 38 + 40 + 42 = 462` .
2

I would do it this way. Adding one, but reducing the number of steps in half, changing this `j=numero+40` for this `j=numero+20` .

It would stay like this.

``````for(int i=numero, j=numero+20;i<=j;i++)
{
total_par+=2*i;
}
``````

The `if` should not exist since it does the same in both cases ... That is, if it is pariiero, and if it is not even, also itero, when it can be said, itero, no matter what happens .

Note: I just realized that the `if` , yes, should exist, because if it's true, `int i=numero` , but if it's false, `int i=numero+1` .

The next line ...

``````for(int i=numero+1,j=numero+40;i<=j;i+2){
``````

It can be corrected in the following way (step by step):

``````for(int i=numero+1,j=numero+40;i<=j;i+=2){
for(int i=numero+1,j=numero+40;i<=j;i+=2){
for(int i=numero+0,j=numero+39;i<=j;i+=2){
for(int i=numero+0,j=numero+40;i< j;i+=2){
for(int i=numero+0,j=numero+20;i< j;i+=1){

for(int i=numero,j=numero+20;i<j;i++){
``````

1

``````private Integer obtenerSuma(Integer intNumero, Integer intCantidadASumar) {
Boolean intSeed = false;