I'm trying to write the following 'while' loop:
int x = N-1, y = 0;
while ( y < M ) {
/* Some work */
if ( x > 0 )
x--;
else
y++;
}
as a 'for' loop. This was my failed attempt:
for ( int x = N-1, y = 0 ; y < M ; ((x>0)?x--:y++) ) {
/* Some work */
}
This fails to compile since, as the compiler says, the update rule is not a statement.
Do you see any way to naturally write the 'while' loop above as a 'for' loop?
You can always leave the update rule empty
for ( int x = N-1, y = 0 ; y < M ; ) {
if ( x > 0 )
x--;
else
y++;
}
To combine the conditions.
for(int x = N-1, y = 0; y < M ; y += (x > 0)?0:1, x += (x > 0)?-1:0)
I suspect this should really be two loops calling a common method.
for(int x = N - 1; x >= 0; x--)
someMethod(x, 0);
for(int y = 0; y < M; y++)
someMethod(0, y);
Does
/* Some work */
include the variables x and y? If not, there is an easier way to write the logic of the loop. Currently, your loops counts from N-1 to zero (x) and then from zero to M-1 (y). The entire loop runs (M+N)-1 times.
By combining the initial conditions, you can write:
for (int x = 1; x < M+N; x++) {
/* Some work */
}
and do away with the y variable altogether.
If you need to keep the x and y variables as those values, just use a third variable:
for (int z = 1; z < M+N; z++) {
/* Some work */
(x>0)?x--:y++;
}
Hope this helps!
Jack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With