Question

I'm brand new to Java & series (summing up no.s in a certain way using Java).

The user needs to input n (a positive even integer). This can be 0, 2, 4, and any increment of 2 above.

If I put in 4, Java must calculate 2 + 4 = 6. If I put in 6, Java must calculate 2 + 4 + 6 = 12. Java needs to sum numbers as follows for an input n... 2 + 4 + 6 + ... + n = some sum. I wanted to see how this can be done by a loop. The following was an attempt of mine. We just assume the user will put in a positive even integer like 2, 4, 6, 8, or 10 & so on (so we don't have to test for that).

Scanner console = new Scanner(System.in);
int sum = 0, n;
System.out.println("Give me a positive even integer.");
n = console.nextInt();

while (sum < n) {
    sum = sum + 2;
}

System.out.println(sum);

Again, the point is to sum from 2 up until the positive even number given by the user.

Was it helpful?

Solution

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.

OTHER TIPS

Try it this way:

Scanner console = new Scanner(System.in);
try {
    System.out.println("Give me a positive even integer.");
    int n = console.nextInt() / 2;
    int sum = 0;
    for (int i = 1; i <= n; i++) sum += 2 * i;
    System.out.println(sum);
} finally { console.close(); }

Besides: it handles odd numbers as well and releases the console, which is a resource.

Right now, your code adds always 2 to the sum. However, you want to add numbers that are increased by 2. So basically, you need another variable counting the current element in the series 2, 4, 6 you are at.

int index = 2;
while( index <= n ) {
    sum = sum + index;
    index = index + 2;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top