954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

add even (or odd) numbers from input

Hello
Please help. I am having a hard time making the leap from where I am to then picking out numbers (in this instance adding even numbers). Any suggestions or pointers would be greatly appreciated.

#include
using namespace std;
// program computes the sum of all even numbers from input number

int compute_sum(int n);
int main()
{
int n;

cout << "enter a number" << endl;

cin >> n;

if (n % 2 == 0)
cout <<"even "<

cynthann
Newbie Poster
3 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 
// program computes the sum of all even numbers from input number

This part of the objective does not make sense to me. Care giving a sample input number, like 12, and explaining what the expected result would be?
Right now it gives the result

1 + 2 + 3 + ... + 11 + 12  = 78


for the input of 12.

WolfPack
Postaholic
Moderator
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115
 

So, if you input 12 it would add

2 + 4 + 6 + 8 + 10 + 12

cynthann
Newbie Poster
3 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 

You can do that by just changing these lines.I am not giving you the answer because if you wrote the above program yourself, you can surely do this part using the hint I have given you.

count = 1;
count = count + 1;
WolfPack
Postaholic
Moderator
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115
 

duh! Thank you for your help. You know when you have been sitting in front of something for so long that the screen begins to melt?

count = 2;
count = count + 2;

cynthann
Newbie Poster
3 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 

I can think of a better way. if you wish to calculate the sum of all numbers in a range, the formula is
n( (First+Last)/2 )

in your case, the first number is always going to be 2 ... 'n' is the "number of numbers" in the range.. eg, from 2-to-12, n=6 ... or 2-to-100, n=50... or 2-to-10000, n=5000.. (see a pattern there?)

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

Hi cynthann,

Can you give me the complete working program of that if you get it right? Thanks.

ruhneb03
Newbie Poster
1 post since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You