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!

Re: Sum of all even integers? Help?

Quote:

prints the sum ...

I think the requirement is the sum.

Quote:

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

Re: Sum of all even integers? Help?

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

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.

[Edit] Yes

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.

Re: Sum of all even integers? Help?

Quote:

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).

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