1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
14
Rep Power
0

#### For loop problem

I have a strange problem when using a for loop:
Code:
`for (int i = 0; i < NUMBER_OF_JOBS; i++, SUM += JOBS[i].getWeight()*JOBS[i].getLength())`
Code:
```	for (int i = 0; i < NUMBER_OF_JOBS; i++)
{
SUM += JOBS[i].getWeight()*JOBS[i].getLength();
}```
after fiddling around I discovered that it was because the former failed to add the first summand (i.e. when i == 0) into the SUM. What is the reason for this? :confused:
2. Code:
```for (int i = 0;
i < NUMBER_OF_JOBS;
i++, SUM += JOBS[i].getWeight()*JOBS[i].getLength())```
It's because the i++ happens BEFORE you do the sum, when you write the loop like this.

Written normally, the i++ is the last thing that happens in the loop.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
14
Rep Power
0
Originally Posted by salem
Code:
```for (int i = 0;
i < NUMBER_OF_JOBS;
i++, SUM += JOBS[i].getWeight()*JOBS[i].getLength())```
It's because the i++ happens BEFORE you do the sum, when you write the loop like this.

Written normally, the i++ is the last thing that happens in the loop.
Thanks for the reply, but then why does
Code:
``` int j = 0;
for (int i = 0; i < 10; i++, j+=1)```
produce the correct output of j = 10?
4. > produce the correct output of j = 10?
Because j doesn't depend on i.

Whereas your previous case, i was used as a subscript, so the second expression was dependent on i.
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
14
Rep Power
0
Originally Posted by salem
> produce the correct output of j = 10?
Because j doesn't depend on i.

Whereas your previous case, i was used as a subscript, so the second expression was dependent on i.
Ah, I get what you mean now, I confused there because I thought that the summation has simply lost the first term, but it has gained an extra last term. Just one last question, this last term - it is out of bounds - so is it because of the default constructor or something that it happens to be zero?
6. It's out of bounds, so anything can happen.
Today, you got zero.
Tomorrow, you might get some random bit of garbage.
Next week, a segmentation fault for an illegal memory access.
7. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2012
Posts
14
Rep Power
0
Originally Posted by salem
It's out of bounds, so anything can happen.
Today, you got zero.
Tomorrow, you might get some random bit of garbage.
Next week, a segmentation fault for an illegal memory access.
Got it, thanks! :)