Wrong output

display the sum of the even intergers between and including two numbers entered by the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

int main ()
{
	//Declare varibles
	int number1=0, number2=0, sum=0;
	int i;

	cout << "Enter the First Number:" << endl;
    cin >> number1;
    cout << "Enter the Second Number:" << endl;
    cin >> number2;

    if (number1 > number2) 
    {
        cout<<"ERROR, First Number must be less than Second Number"<<endl;
    }
   
	//loop through and add even values
   for(i = number1; i < number2; i++)
   {
       if(i%2 == 0)
       {
           sum = sum + i;
       }
   }

   cout << "Sum: " << sum << endl;


	return (0);
}
Last edited on
You should change this: i<number2 to this: i<=number2 cause you need to include the last number (number2).

Another (easier) way of doing this.

1
2
3
4
5
for (i=number1; i<=number2; i=i+2){

sum=sum + i;

}
Last edited on
ty
Topic archived. No new replies allowed.