2+4+6+..+n

n is given. Whats the sum of 2+4+6+..+n? Use only for loop. I have no idea what to put inside the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
int i,n;
cin>>n;
for(i=2;i<n+1;i=i+2){

    cout<<i+n<<endl;



}

return 0;
}
Last edited on
You are very close!
What you lack in your program is a variable that will keep track of the sum.
It is okay for a variable to be used on both sides of an assignment, as long as it has already been declared.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
int main()
{
    int i,n;
    int sum = 0;
    cin>>n;
    for(i=2;i<n+1;i=i+2){
        sum = sum + i;  //or you could use "sum += i" which does the same thing
    }
    cout << sum << endl;
    return 0;
}
Last edited on
Thanks a lot!
Topic archived. No new replies allowed.