0

In the week 4, lecture ,at 27:30

for (int i=1; i<=m; i++)
{
     sum +=i;
}
return sum;

Q1: why do I need a equal sign after + ? why not just "sum + i;"?

Q2: Because I want to create another expression like this i*(i-1)*(i-2)*...*1, but there's no character like this *=. That means can I just do it like sum * i;?

2 Answers 2

2

Q1: why do I need a equal sign after + ? why not just "sum + i

As curiouskiwi does a great job pointing out, sum += i is really the same as sum = sum + i. (just a little syntactic sugar meaning it's easier to type and computer scientists are lazy by nature).

So really you are asking what is the difference between sum = sum + i and sum + i. And the difference is the assignment operator "=". The first option tells the processor to add i to sum and the STORE IT in the variable sum (well the address that sum points to technically). Whereas the second option tells the processor to add i to sum, but then doesn't say anything else.

It's kind of the equivalent of opening up a document, writing your essay and then closing it without saving.

Hope that helps.

2

sum+=i is shorthand notation for sum = sum + i

Similarly:

sum -= i    sum = sum - i
sum *= i    sum = sum * i
sum /= i    sum = sum / i
1
  • 1
    I wanna emphasize that sum + i; (removing the =) by itself will just sum up the values of sum and i then do nothing unlike sum += i; and sum = sum + i; which assign the result back to sum.
    – kzidane
    Mar 23, 2015 at 1:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .