# Thread: Sum of all even integers? Help?

1. Member Join Date
Oct 2012
Posts
50
Rep Power
0

## Sum of all even integers? Help?

The assignment says, "Design and implement and application that reads an integer value and prints the sum of all even integers between 2 and the input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly." Okay. I don't understand exactly what they want. Do they want the output to be the sum of all the numbers between 2 and the inputted number, so for instance if the user enters 10, the output would be 30 because 2+4+6+8+10 = 30. Or do they want you to have the output list all of the even numbers between two and the inputted number (inclusive), so that the output is 2, 4, 6, 8, 10...? I know you can two the second option with a for loop, but could someone steer me in the right direction on how to do the first option (if that's what it's asking for)? Thanks!  Reply With Quote

2. ## Re: Sum of all even integers? Help?

prints the sum ...
I think the requirement is the sum.
how to do the first option
Define a variable to hold the sum
write a loop
add the even numbers to the sum
end loop
print the sum  Reply With Quote

3. Member Join Date
Oct 2012
Posts
50
Rep Power
0

## Re: Sum of all even integers? Help?

Nevermind. I got it. A for loop is the best way to do it, right?  Reply With Quote

4. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Re: Sum of all even integers? Help?

You are supposed to print "the sum of all even integers" ie 30.

If you know how to list the even numbers in a for loop, try using the for loop but instead of printing the numbers add them to some variable like total. After the loop finishes total should contain he desired sum.

 Yes  Reply With Quote

5. Senior Member Join Date
Jun 2007
Location
Bali, Indonesia
Posts
762
Rep Power
13

## Re: Sum of all even integers? Help?

I believe they want the first option, print the sum of all event integer. And you can also do it using a for-loop if you want to. Or any other loop statement will be fine.  Reply With Quote

6. Senior Member Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: Sum of all even integers? Help? Originally Posted by psx2514 A for loop is the best way to do it, right?
Well, not really because it runs in linear time. But then it wouldn't be much of a programming exercise. Since you are working with integers, you can use the following to check your answer (assuming of course I didn't make a mistake).

Java Code:
```int n; // initialize to the top range of your series
int k = n/2;  // the number of even numbers to sum. (k will be the same for n where n = 2r or 2r+1)
int sum = k * (k + 1); // the sum of even numbers from 2 to n inclusive```
Regards,
Jim
Last edited by jim829; 04-03-2013 at 06:50 PM.  Reply With Quote

loops 