0

I have two arrays in my code each one of them have 7 elements, I used a for loop:

for (int i = 0; i < 7; i++)
{
    distance = x[++i] - x[i];
    area = trapezoidArea(distance, y[++i],y[i]);
    sum += area;
}

I wanted to calculate the area of a trapezoid. The difference of x[1]-x[0] will give me the height and y[1] is the first side, and y[0] is the second side.

This for loop doesn't work, and I want to know why.

3 Answers3

4

You can't use ++ as post or pre-increment operator in this case.
This will change the value of your i variable, and therefore your for loop won't have the behaviour you want.
The proper way would be :

for (int i = 0; i < 6; i++)
{
    distance = x[i+1] - x[i];
    area = trapezoidArea(distance, y[i+1],y[i]);
    sum += area;
}

Be careful you have to loop until i<6 because if you let 7, you'll try to access x[7+1] = x[8], and you'll have undefined behaviour or segmentation fault.

cocool97
  • 1,201
  • 1
  • 10
  • 22
1

++i increases i. So you increase i thrice in one run through the loop, and on top of that, it might also be undefined behavior because of sequencing. What's the i in x[i] supposed to be? The i before the ++i in x[++i] increased it, or after it was increased?

If you want one more than i without increasing it, do i+1 instead. Replacing x[++i] with x[i+1] and likewise with y[++i] should fix this issue. But without seeing all of your code, it's impossible to say if that's the only issue.

Blaze
  • 16,736
  • 2
  • 25
  • 44
0

When you do ++i in the square brackets, you actually increment the value of i by one. What you should do is i + 1 and leave ++i only in the loop declaration.

basania
  • 125
  • 1
  • 8