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?
#include <iostream>
usingnamespace 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 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.