My first attempt of reverse for loop that does something n times was something like:
for ( unsigned int i = n-1; i >= 0; i-- ) { ... }
This fails because in unsigned arithmetic i
is guaranteed to be always greater or equal than zero, hence the loop condition will always be true. Fortunately, gcc compiler warned me about a 'pointless comparison' before I had to wonder why the loop was executing infinitely.
I'm looking for an elegant way of resolving this issue keeping in mind that:
Any ideas? Thanks :)
for (int i = myArray. Length - 1; i >= 0; i--) { // Do something ... } You can consider it as the standard way to loop backwards. Worked.
Let's discuss certain ways in which this can be done. Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting.
public class Reverse { public static void main(String [] args){ int i, j; System. out. print("Countdown\n"); int[] numIndex = new int[10]; // array with 10 elements. for (i = 0; i<11 ; i++) { numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.) }
How about:
for (unsigned i = n ; i-- > 0 ; ) { // do stuff with i }
for ( unsigned int loopIndex = n; loopIndex > 0; --loopIndex ) { unsigned int i = loopIndex - 1; ... }
or
for ( unsigned int loopIndex = 0; loopIndex < n; ++loopIndex ) { unsigned int i = n - loopIndex - 1; ... }
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