Reverse for

When one writes a for loop for ascending order it will probably be like this:

for (int i = 0; i < count; i++)

But what if you want to do it in reversed order? The first option would be:

for (int i = count - 1; i >= 0; i--)

I personally prefer the form below, as it’s more concise, uses comparison without equals and doesn’t need -1 after count (being more similar to ascending loop), while it does the same thing (descending traversal). And it’s not difficult to memorize either:

for (int i = count; i-- > 0; )

What I don’t like about this one is that the number of characters its code uses is actually lower than that of the ascending loop, since there is no need for a third expression.

Do you have a better solution? (Define better first.) 🙂


About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in C# and tagged , , , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s