r/visualbasic • u/Avantgardedane • Oct 20 '16
Reasoning behind backwards loop
I am running some code to look through our bank and match it to our accounting, and i am using a for i=m to 1...next loop - step -1. When i change it to go forward ( step+1) it messes everything up. I've seen this before, but why?
2
u/chrwei Oct 20 '16
there's a few good reasons for that. removing elements from a queue inside the loop is one, another could be the source data is sorted descending and you want to process it ascending. looping back is more efficient than re-sorting.
a better way to loop over a queue while removing items is a while loop, then you add to the end and remove from the front without issue.
1
u/tweq Oct 20 '16
Impossible to answer without source and more context. "it messes everything up" is completely meaningless.
2
u/Avantgardedane Oct 20 '16
I was wondering, if there was a general reasoning behind looping backwards, but i think i found it. It is because i delete rows, and when i go forward, it messes up my count :)