+= in for loop


Hello. Can someone explain to me why this code in the body of the for loop doesn't produce the sum of all numbers but only that of the first two? But when I write sum+= (num1+num2) it works? Why the loop with += continues looping while and the first doesn't?

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;

int main () 
{   
	int num1, num2;
	int sum=0;
    cout<<"Enter the first integer number: ";
    cin>>num1;
    cout<<"Enter the second integer number(bigger than the first): ";
    cin>>num2;
    
    for (; num1<=num2; ++num1, --num2)
         sum=(num1+num2); 
         
         cout<<"The sum of all integers is "<< sum<<".";
    
	
	
	return 0;
}
The way your code is written, every time line 14 executes, it throws away the old value of sum, and overwrites it with the new value of (num1+num2).
The two statements are not the same. The following two are equal:
1
2
sum += num1 + num2;
sum = sum + num1 + num2;


In any case you might want to rethink your loop -- sum from 2 to 8 should be 35, for example, and not 40 like your program outputs (with +=). Just focus on incrementing or decrementing one var and using just its value.
Last edited on
Looping from both ends might seem like a clever idea at first but you'll run into problems when the number of values are odd.
Thank u all for the useful tips
You're welcome. Hope it cleared everything up for you?
It surely did!
Topic archived. No new replies allowed.