adding even numbers

April 12, 2010 at 17:39:23
Specs: Windows 7
I have to modify a program:

#include <iostream>
using namespace std;
int main ()
int num = 0, i = 1, sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
while (i <= num)
sum += i;
cout << "The sum is " << sum << endl;
return 0;

to ask for a number, then add all even numbers less than that

any tips and help will be much appreciated

See More: adding even numbers

Report •

April 12, 2010 at 18:27:09
nvm figured it out

Report •

April 12, 2010 at 18:36:10
Edit:Beaten to it....

Since this looks like all the numbers are supposed to be positive I would suggest unsigned int types.

You will also need to set a limit for the input number, because if i understand correctly you plan to output the sum of all even numbers less than the input. This could easily exceed the capacity of the variables if a fairly large number is input.

It may help to use a larger int type like an unsigned long int or unsigned long long int, but you will still need to work out a limit on input numbers.

The rest is fairly simple with a loop and counter(there may be an equation to work it out in a single step but haven't looked into it).

Report •

Related Solutions

Ask Question