O'Reilly logo

Beginning Programming ALL-IN-ONE DESK REFERENCE FOR DUMMIES® by Wallace Wang

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter II.5. Repeating Commands by Looping

To write any program, you must specify what the computer needs to do at any given time. Sometimes, you may need to write the same command multiple times. For example, suppose you want to print your name five times. You could just write the same command five times like this:

PRINT "John Smith"
PRINT "John Smith"
PRINT "John Smith"
PRINT "John Smith"
PRINT "John Smith"

Writing the same five commands is cumbersome. Even worse, what if you suddenly decide you want to print your name not just five times, but five thousand times? Do you really want to write the same command five thousand times?

Probably not, which is why computer scientists invented loops. A loop is just a shortcut for making the computer run one or more commands without writing those commands multiple times. So rather than type the same command five times as in the preceding example, you could use a loop like this:

FOR I = 1 TO 5
  PRINT "John Smith"
NEXT I

This tells the computer to run the PRINT "John Smith" command five times. If you want to print John Smith five thousand times, you just have to change the number of times you want the loop to run by replacing the 5 with 5000, such as

FOR I = 1 TO 5000
  PRINT "John Smith"
NEXT I

Loops basically make one or more commands run more than once, as shown in Figure 5-1.

A loop can run one or more commands over and over.

Figure II.5-1. A loop can run one or more commands over and over.

Looping ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required