This question already has answers here:
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, and you'll have
undefined behaviour or
Interactions in C# Programming: Loops and Arrays, The for loop lets you define a variable used to control the loop and increment We have "length" in the example, because you can also use an array's index You can also use the greater than and equal to relational operators. The do- while and while loops are not as common as the for loop, but they do serve a purpose. Mixing loops and arrays. Loops are typically used with arrays to do one of three things: 1) Calculate a value (e.g. average value, total value) 2) Search for a value (e.g. highest value, lowest value). 3) Reorganize the array (e.g. ascending order, descending order)
i. So you increase
thrice in one run through the loop, and on top of that, it might also be undefined behavior because of sequencing. What's the
x[i] supposed to be? The
i before the
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+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.
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.
CodingBat Java Arrays and Loops, See also the associated CodingBat java array problems, to practice array ideas or It is common to use a 0length-1 for-loop to iterate over all the elements in array: We can change the init/test/increment in the for-loop to iterate through the Other examples of for-all operations that look at every element in the array � If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables.
++ is not the same as
Step through your program line by line (either mentally or with a debugger) and consider the values of your variables (especially
i) every time.
i three times in the loop. Are you sure you want to do that?