[sum=sum+j;]
1.semicolon shouldn't be put here but then if we put how do you explain the outcome?
2.Instead of [sum=sum+j, j++] we can also just put [sum += j++].
The comma operator is not need in the latter one..Why?
3.Please explain the difference b/w += and =+ operators.
[
//Sum of the first x natural numbers
#include <iostream>
using namespace std;
int main ()
{
int x, j(1), sum(0);
cout<<"Enter: \n";
cin>> x;
[sum=sum+j;]
1.semicolon shouldn't be put here but then if we put how do you explain the outcome?
Sorry, I don't understand the question. sum=sum+j; is a legal statement. [sum=sum+j;] is not. Is that what you're asking about?
The comma operator is not need in the latter one..Why?
sum += j++ adds j to sum and then increments j.
I like to use the for statement for loops like this. It makes it clear what you're looping through vs. what you're doing in each iteration of the loop:
1 2 3
for (j=1; j<=x; ++j) { // it's clear that you're looping from 1 to x
sum += j; // This is what you're doing each time through the loop.
}
The differenence is that sum = sum+j,j++ is an expression. It's value is the value of the right hand side of the comma operator. You could assign it to another value: x = (sum = sum+j,j++) is equivalent to
1 2
sum = sum+j;
x = j++;
I've found the comma operator handy in for loops (there I go again!) e.g. to walk a linked list and count the items at the same time: for (node = top, count=0; node; node=node->next,++count)