Explain the glitch

[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;

while (j<=x)
sum = sum+j; j++;

cout<<"Value: ="<<sum;
return 0;
}
]
Last edited on
[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.
}

Hi dhayden! (:
I've put square brackets just to differentiate that it's a code.
Anyway what I was asking is the difference b/w

sum = sum+j, j++ //By which sum of the natural no. program can run.

sum=sum+j; j++ //A different outcome because of ; operator.How does the compiler interprets the code this time?

Yea..for loops provides specific locations for the input unlike while but then I was asked to do with while loop only.

Ps: I'm just a beginner.So I wrote in a layman language instead of technical ones.Please don't mind.Have a nice day!
Last edited on
These two lines are identical in behavior:

sum = sum+j, j++;

sum = sum+j; j++;
I don't think so..Try compiling in this site
http://www.compileonline.com/compile_cpp_online.php
Please use code tags to highlight code.

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)
Topic archived. No new replies allowed.