Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to do a reverse 'for' loop with an unsigned index?

Tags:

c

for-loop

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:

  1. It should be a backwards for loop.
  2. The loop index should be unsigned.
  3. n is unsigned constant.
  4. It should not be based on the 'obscure' ring arithmetics of unsigned integers.

Any ideas? Thanks :)

like image 715
Auron Avatar asked Mar 20 '09 11:03

Auron


People also ask

How do you run a for loop backwards in C++?

for (int i = myArray. Length - 1; i >= 0; i--) { // Do something ... } You can consider it as the standard way to loop backwards. Worked.

Can you go backwards in a for loop?

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.

How do you reverse a for loop in Java?

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.) }


2 Answers

How about:

for (unsigned i = n ; i-- > 0 ; ) {   // do stuff with i } 
like image 154
Skizz Avatar answered Sep 23 '22 19:09

Skizz


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;     ... }  
like image 31
Lou Franco Avatar answered Sep 21 '22 19:09

Lou Franco