Program for computing sum of even numbers upto n numbers

The code taught to us is-
#include
using namespace std;
int main () {
int sum=0;
int n;
cin>>n;
int x=2;
while (x<=n){
sum = sum+x;
x=x+2;
}
cout<<"Sum is "<<sum<<endl;
return 0;
}

If I write the code as-
#include
using namespace std;
int main () {
int sum=0;
int n;
cin>>n;
int x=2;
while (x<=n){
x=x+2;
sum = sum+x;
}
cout<<"Sum is "<<sum<<endl;
return 0;
}

The output comes out to be different . May I know what is wrong in my approach of placing x=x+2; above sum=sum+x ; instead of vice versa and what difference does it make.
Thank You

If have doubt about the execution of your program. I would you to dry run your program for different values of inputs.

Now, about your question.

  1. If you write x=x+2 before sum=sum+2
    Suppose, n = 11
    Initially, sum=0 and x=2

1st iteration of while loop (2<11):
x=x+2=2+2=4
sum=sum+x=0+4=4
// logical error

The first even number is 2 but you are adding 4 to sum.

  1. But, if you write x=x+2 after sum=sum+2
    1st iteration(2<11):
    sum=sum+2=0+2=2
    x=x+2=4
    // this is logically correct

  2. If you want the same order of statements as specified in the above code, you have to apply one of the below mentioned modification:
    (A). Write sum=2 rather sum=0
    (B). Write x=0 rather x=2

Hope this would help.
If you still have doubts, feel free to ask

Mark your doubt as resolved if you are satisfied.
N if possible give a like to me and pass your reviews about me​:sweat_smile::blush: