One of the most common errors in computer programming is running into an infinite Do or While loops. These are parts of the source code that is usually meant to loop for a certain number of times until the condition of the loop is met. These loops are utilized for specific purposes in the logic of a source code/program. However, there may be times when you encounter a loop that goes on and on unintentionally. In rare occasions, infinite loops are utilized to keep a program running forever for whatever purpose it may be and again, let me reiterate, it’s quite rare.
If you happen to have an infinite loop in your code and want to fix it, there are some steps can you can do to try and debug or fix it so that the Do or While loop will end. Let’s say you want to run the loop 10 times but when you run the program, it continues to run the loop continuously instead of stopping after 10 times.
Before you move on, it’s always good to do some real-time debugging for Do and While loops. Place a command that will show you the value of the index. It depends on what programming language you are using but for the sake of our example, you can use print, writeln, msgbox, etc. to display the value of the index. This way, you’ll know how many times the loop has run or what values the index acquires after each loop. If it goes way over the number of intended times it’s supposed to run, you may possibly have an infinite loop. The index is the variable that we usually assign to count the number of the times the loop has run.
Let’s use a While Wend loop as an example (for the BASIC programming language).
While X = 0
In this case, the loop will run while the value of X = 0. Let’s call X as the index of the loop. If the value of X changes, the loop will terminate. In this While loop, it will print the word Hello infinitely because the value of X is 0 and it does not change. To verify this, add Print X below the Print “Hello” statement. The program will display the value of X (which is 0) after it displays Hello. You’ll know immediately that the loop will run forever since the value of X will always be 0. But if you place X = X + 1 before Wend, after the first execution of the loop, the loop will end because the value of X is now 1. So when your conditions are met within the loop you’re trying to make, make sure you change the value of the index.
For Do Until loops, it’s the other way around. It will continue to run until the index is equal to the value in the Until statement. For the For Next loop, you don’t have to … Read the rest