Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting down in for-loops

Tags:

c++

for-loop

I believe (from some research reading) that counting down in for-loops is actually more efficient and faster in runtime. My full software code is C++

I currently have this:

for (i=0; i<domain; ++i) {

my 'i' is unsigned resgister int, also 'domain' is unsigned int

in the for-loop i is used for going through an array, e.g.

array[i] = do stuff

converting this to count down messes up the expected/correct output of my routine.

I can imagine the answer being quite trivial, but I can't get my head round it.

UPDATE: 'do stuff' does not depend on previous or later iteration. The calculations within the for-loop are independant for that iteration of i. (I hope that makes sense).

UPDATE: To achieve a runtime speedup with my for-loop, do I count down and if so remove the unsigned part when delcaring my int, or what other method?

Please help.

like image 404
ohit Avatar asked Apr 29 '09 23:04

ohit


People also ask

How do you count downwards in a for loop in Python?

Using the reversed() function to count down in a for loop in Python. The reversed() function takes a sequence and reverses its order. We can create a simple sequence using the range() function and reverse it using this function. After reversing the sequence, we can iterate over it using the for loop to count down.

Which is better for a for loop count up or count down?

A: Always, count Down to Zero loops are better.


1 Answers

There is only one correct method of looping backwards using an unsigned counter:

for( i = n; i-- > 0; )
{
    // Use i as normal here
}

There's a trick here, for the last loop iteration you will have i = 1 at the top of the loop, i-- > 0 passes because 1 > 0, then i = 0 in the loop body. On the next iteration i-- > 0 fails because i == 0, so it doesn't matter that the postfix decrement rolled over the counter.

Very non obvious I know.

like image 188
Don Neufeld Avatar answered Dec 08 '22 01:12

Don Neufeld