Lost in translation

Microsoft said it will stop developing the Visual Basic language . So, it's time to rewrite the code in Citylink .



Regardless of this landmark decision, I myself needed to translate one pet project from VBA to C #. I usually prototype everything in MS Access, and then the code moves to a more serious database (read: SQL Server) and another programming language.



And here are the cycles.

In Basic and Pascal there is a loop procedure

 

for i = Lower to Upper step Step

              ...

next



It is universal in the sense that it can go both from bottom to top and from top to bottom. It can be used both if Step> 0 and if Step <0.



How do you write the same thing in C / C ++ / C # / JavaScript notation? It turns out that their for loop is not at all equivalent to the Basic one:



  for (i = Lower; i <Upper + 1; i + = Step) {โ€ฆ}



How to modify this to work for the case when Step <0? The following, not the most elegant, solution comes to mind:



for(i = Lower; Sign (Step) * i <= Sign (Step) * Upper; i + = Step) {โ€ฆ}



It, like the original forโ€ฆ next, will loop at Step = 0.



Colleagues suggested another option:



for (i = Lower; Step> 0? I <= Upper: i> = Upper; i + = Step) {...}



In fact, since we need the last value of the loop variable to be Upper, and it also participated in the body of the loop, it can be programmed as a loop with a postcondition:



i = Lower - Step;

do

i + = Step;

...

while (i! = Upper)



but this code will not work if Step does not completely divide the range Lowerโ€ฆ Upper



It turns out that the loop using range in Python also does not allow moving from a larger value to a smaller value, range (b, a) with b> a simply sets an empty range.



What solution would you suggest?



All Articles