Negative/positive step sizes in loops

phudgens

Member
Joined
Nov 19, 2013
Messages
19
Programming Experience
10+
I am needing to convert the following For loop from VB to C#. Depending on externally derived circumstances, the step size may be positive or it may be negative. The value of iFirstVal may be less than iLastVal, or vice versa, and can change within a given run.

C#:
        For iCnt = iFirstVal To iLastVal Step iStep
...
        Next iCnt

I have done a fair amount of searching and am not finding a way in C# that allows me to do the same thing. Code could be written that would call different methods depending on the first and last values. Since I end up using this sort of code a lot, I was hoping there would be a more direct way to do this in C#.

Thanks,
Paul Hudgens
 
Have a read here: for (C# Reference)
for (initializer; condition; iterator)
A variable can be used in each expression part, iterator is the step.

In this example first/limit/step is variables, where first/limit can be both lower or higher values and step can be positive or negative.
for (var i = first; i != limit; i += step)

It may be easier to arrange for either a 'less than' or 'greater than' condition, though.
 
Have a read here: for (C# Reference)

A variable can be used in each expression part, iterator is the step.

In this example first/limit/step is variables, where first/limit can be both lower or higher values and step can be positive or negative.
for (var i = first; i != limit; i += step)

One point worth noting is that JohnH's code could create an infinite loop. If 'step' was such that 'i' was never equal to 'limit' then the loop would go on forever. The most equivalent code to your original VB code would be this:
for (var iCnt = iFirstVal; (iStep < 0 ? iCnt >= iLastVal : iCnt <= iLastVal); iCnt += iStep)
{

}
That will ensure that the loop will always* terminate whether iStep is greater than or less than zero.

* An infinite loop will still occur if iStep is zero but the same would occur in VB.
 
As I wrestled with this around 2 AM this morning, I came to the conclusion that the "!=" option was the only thing that would work, although I didn't know if it was correct C# code. That assumes that before iLastVal is used it must be incremented by the value of iStep (either positive or negative) so that the loop would still go all the way through all required iterations. In my case, the absolute value of iStep is always 1, and my first and last vals will always be >= to 1, so I don't have to worry about infinite loops. I'm going to incorporate jmcilninney's code though, since at some point in the future a step size other than 1 may become necessary. Thanks very much for the help.
 
Back
Top Bottom