Looping instructions

No matter how many sequential or branching instructions a program has, it runs only once before stopping. To keep a program running until you want it to stop, you need to use looping instructions.

Looping instructions make the computer repeat one or more instructions. In a video game, a loop might keep running all the instructions in the program until the game character dies. Then the loop stops and the program (and game) ends.

Besides keeping a program running until the user wants to quit, looping instructions save you from having to type nearly identical instructions over and over again.

Suppose you wanted to print the numbers 1 through 5 on-screen. You could use the following Liberty BASIC program:


PRINT 1
PRINT 2
PRINT 3
PRINT 4
PRINT 5

Typing multiple instructions may be tedious, but still tolerable for a small number of instructions. However, if you want a program that prints the numbers 1 through 1000 on-screen, you would have to type nearly a thousand identical instructions.

Obviously, typing that many instructions over and over again is a waste of time, so that’s where looping instructions come in handy. Looping instructions tell the computer to repeat one or more lines of code, eliminating the need for you to type them yourself. A Liberty BASIC looping program that prints the numbers 1 through 5 on-screen might look like this:


FOR X = 1 TO 5
   PRINT X
NEXT X

Although this looping instruction looks more cryptic than the straightforward list of five instructions that printed the numbers 1 through 5 on-screen, the looping instruction requires much less typing. Even better, if you want to print the numbers 1 though 1000 on-screen, you just have to rewrite the looping instruction like this:


FOR X = 1 TO 1000
   PRINT X
NEXT X

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply



eXTReMe Tracker