sum of even numbers between two integers

ok now i have to output the sum of all even numbers between num1 and num2
heres what i have.
#include <iostream>
using namespace std;
void main()

{
int num 1, num 2;

cout << "Enter first integer: ";
cin >> num1;
cout << "Enter second integer: ";
cin >> num2;

while (num1 <= num2) {
if(num1%2 != 0)
cout << num1 << " is odd." endl;
num1++;
}
{
while (num1 <= num2)
if (num1%2 == 0)



Continuing from: http://cplusplus.com/forum/beginner/54491/ ? You still have the same problem where your variables are defined "num 1" and "num 2". Your names cannot have spaces. Replace them with num1 and num2 as you use in the rest of your code.

After you close your first while loop, things don't really make sense anymore. Still, I can see you've been able to identify which numbers are odd so lets go from there:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
void main()

{
	int num1, num2, sum = 0; //Sum starts at 0 and contains the sum of all even numbers

	cout << "Enter first integer: ";
	cin >> num1;
	cout << "Enter second integer: ";
	cin >> num2;

	while (num1 <= num2)	{
		if(num1%2 != 0)	cout << num1 << " is odd." endl;
		else 		sum += num1; //If even, add this number to the sum

		num1++;
	}
	cout << "The sum of all even numbers between " << num1 << " and " << num2 << " is " << sum << "." << endl;
	cin.get();
}


Also, using [code ] and [/code ] when posting makes it easier to read. This will help you to encourage feedback when you have problems in the future.
Last edited on
thanks..you've been a big help
then again..how do you declare sum? im getting an error that tells me to declare it when i run it
int num1, num2, sum = 0; //Sum starts at 0 and contains the sum of all even numbers

the sum declaration is in that line of code. =)
ohhh..sorry =]
Topic archived. No new replies allowed.