This list of observations:
for (int x=1,y=1;y<=20;x+=2,y++) it is correct,works!
for (int x=1,y=1;x<=20;x+=2,y++) it is false and it is stop on 20th number(19). it(x<=20) should be deleted and it(y<=20) need to add to it.
for (int x=1;x<=20;x+=2) it is false and it is stop on 20th number(19). due to, x+=2.
These are not related to any C++ language issue. This has nothing to do with the "for" loop.
This is a matter of math.
That all work, but merely don't provide what you expected because you didn't quite recognize the math differences in each statement.
In the first one, you are testing y. Y starts at 1 and will continue to execute until y == 21. The loop will not execute when y == 21, which means the code in that loop performs 20 steps, from 1 to 20 in Y.
At that point, notice, that x started at 1, such that when y was, say, 18, x was 35. When y was 20, x was 39.
What you said was the "correct" version of the 3 examples executed the loop until the point when x was 39,
not 20, where y was 20
So, in order for the loop to function as you
expected, the loop must continue running until x is at least 39. You tested for x <=
20, when the loop would have finished as the first example if you merely tested for <= 39.
That has nothing to do with "for" loops, or with C++.
You were testing for the wrong end point of the loop.
Prove by trying this comparison:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
int main()
{
// your working version
for( int x = 1, y = 1; y <= 20; x += 2, y++ )
{
cout << "x " << x << ", y " << y << endl;
}
cout << endl << endl;
// the version you said failed
for( int x = 1, y = 1; x <= 20; x += 2, y++ )
{
cout << "x " << x << ", y " << y << endl;
}
cout << endl << endl;
// what you should have tried
for( int x = 1, y = 1; x <= 39; x += 2, y++ )
{
cout << "x " << x << ", y " << y << endl;
}
}
| |
Note, in the first example (as you wrote it), the last line from that output will be x 39, y 20.
That's what you said was correct.
Note that the second ends just as you said, with x at 19 and y at 10.
Then, note that the 3rd example runs until x 39, y 20, just as the first example, executing 20 steps.
The second example stops with x at 19 because you told it to stop when x > 20 ( testing x <= 20 ).
Part of this is because you're starting at 1, not 0 (which is fine, that's not a problem, you need x to start at 1)
However, you merely need to test for the endpoint
value of x you require, not the number of steps to perform.