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.
The simplest loop runs one or more commands a fixed number of times, such as five or ten times. Such loops that run a fixed number of times are FOR-NEXT
loops and look like this:
FOR Variable = InitialValue TO EndValue Command NEXT Variable
The first line serves two purposes. The first time the FOR-NEXT
loop runs, this line sets the value of the variable to an initial value, such as 1
. The second and all additional times the FOR-NEXT
loop runs, it checks if its variable is still within a range of values, such as between 1
and 10
. If so, the FOR-NEXT
loop runs again.
The second line consists of one or more commands that you want to run multiple times.
The third line tells the FOR-NEXT
loop to increase the value of its variable by 1 and run the FOR-NEXT
loop again.
The FOR-NEXT
loop defines four items:
A variable
The initial value of the variable (usually 1)
The ending value of the variable
One or more commands that run multiple times
Like all variables, the name of a FOR-NEXT
loop variable can be anything, although it's best to use a descriptive name if possible. So if you want to print the names of all the employees of a company by using a FOR-NEXT
loop, you could use EmployeeID
as a descriptive variable name, such as
FOR EmployeeID = 1 TO 150 PRINT EmployeeName NEXT EmployeeID
This example would print out each name (EmployeeName
) starting with the employee who has the EmployeeID of 1 and continuing until it prints the employee with the EmployeeID of 150.
If your FOR-NEXT
loop variable is meant only for counting and doesn't represent anything, like employee numbers, you can just use a generic variable name, such as I or J, such as
FOR I = 1 TO 15 PRINT "John Smith" NEXT I
This FOR-NEXT
loop just prints the name "John Smith"
on-screen 15 times.
Never change the value of a FOR-NEXT
loop's variable within the loop or else you risk creating an endless loop — the computer keeps running the same commands over and over again without stopping. This makes your program appear to freeze or hang, essentially stopping your program from working altogether. The following example creates an endless loop:
FOR I = 1 TO 5 PRINT "John Smith" I = 3 NEXT I
This FOR-NEXT
loop runs five times. The first time the FOR-NEXT
loop runs, the value of the I
variable is set to 1
. But within the FOR-NEXT
loop, the value of the I
variable is then set to 3
. So each time the FOR-NEXT
loop runs again, it checks to see if the I
variable's value is between 1 and 5.
Because the FOR-NEXT
loop always resets the value of the I
variable to 3
, the I
variable never falls outside the range of 1 to 5, so this FOR-NEXT
loop runs indefinitely.
The curly bracket language family creates a FOR-NEXT
loop that looks slightly different than the way other languages do. For example, this is how BASIC creates a FOR-NEXT
loop:
FOR I = 1 TO 15 PRINT "John Smith" NEXT I
This is the equivalent FOR-NEXT
loop in C:
for (i = 1, i <= 15, i++) { printf("John Smith"); }
The first line consists of three parts:
i = 1
: Sets the value of the i
variable to 1
i <= 15
: Makes the FOR-NEXT
loop keep repeating as long as the value of the i
variable is less than or equal to 15
i++ −−
: Increases the value of the i
variable by 1
In any programming language, you can add 1 to any variable by doing this:
I = I + 1
The curly bracket language family gives you a shortcut for adding 1 to any variable, which is known as the increment operator, such as
i++
This is equivalent to
i = i + 1
The increment operator is used more often than writing out the entire i = i + 1
command because it's much shorter. There's also a similar decrement operator that looks like
i--
This is equivalent to
i = i - 1
Normally, the FOR-NEXT
loop counts from 1 to another number, such as 15. However, you can also count from any number range, such as 23 to 41, 102 to 105, or 2 to 8. The main reason to use a different range of numbers is if those numbers represent something in your program.
For example, suppose employees are assigned an employee number starting with 120 and there are four employees, as shown in Table 5-1.
Table II.5-1. A Database of Employee Names Assigned with Specific Employee ID Numbers
Employee Name | Employee ID Number |
---|---|
John Smith | 120 |
Maggie Jones | 121 |
Susan Wilson | 122 |
Emir Kelly | 123 |
You could use a FOR-NEXT
loop like this:
FOR EmployeeID = 120 TO 123 PRINT EmployeeName (EmployeeID) NEXT EmployeeID
Each time this FOR-NEXT
loop runs, it prints the employee name associated with a particular employee number, so it prints out the following:
John Smith Maggie Jones Susan Wilson Emir Kelly
Counting by different number ranges is useful only if those numbers mean something to your program. If you just need to count a fixed number of times, it's much clearer to count from 1 to a specific value instead. The following FOR-NEXT
loop actually runs four times (120, 121, 122
, and 123
):
FOR EmployeeID = 120 TO 123 PRINT EmployeeName NEXT EmployeeID
Notice that counting from 120 to 123 doesn't make it clear exactly how many times the FOR-NEXT
loop runs. At first glance, it appears that the FOR-NEXT
loop may repeat only three times.
To clarify exactly how many times the FOR-NEXT
loop runs, it's always much clearer to count from 1, such as
FOR EmployeeID = 1 TO 4 PRINT EmployeeName NEXT EmployeeID
Normally, the FOR-NEXT
loop counts by 1. So consider the following FOR-NEXT
loop:
FOR I = 1 TO 4 PRINT "The value of I = ",I NEXT I
This FOR-NEXT
loop would print
The value of I = 1 The value of I = 2 The value of I = 3 The value of I = 4
If you want to count by a number other than 1, you must define an increment. So if you want to count by 2, you'd have to define an increment of 2, such as
FOR I = 1 TO 4 STEP 2 PRINT "The value of I = ",I NEXT I
This modified FOR-NEXT
loop would only print
The value of I = 1 The value of I = 3
Although many languages, such as BASIC, assume the FOR-NEXT
loop always increments by 1 unless you specifically tell it otherwise, the curly bracket languages always force you to define an increment value. To define a FOR-NEXT
loop in C to increment by 2, you can define i = i + 2, as follows
for (i = 1, i <= 4, i = i + 2) { printf("The value of i = %d", i); }
Rather than count forward from 1 to 4, you can also make a FOR-NEXT
loop count backward, such as
FOR I = 4 DOWNTO 1 PRINT "The value of I = ",I NEXT I
Much like using different number ranges, such as 34 to 87, counting backward makes sense only if those numbers have a specific meaning to your program, such as
FOR I = 10 DOWNTO 1 PRINT I NEXT I PRINT "BLASTOFF!"
This example would print
10 9 8 7 6 5 4 3 2 1 BLASTOFF!
Although languages, such as BASIC, use a specific keyword (DOWNTO)
to make a FOR-NEXT
loop count backward, curly bracket languages let you count backward by changing both the initial and ending value of the for-next
variable and then defining an increment that subtracts instead of adds, such as
for (i = 10, i >= 1, i = i - 1) { printf("%d ", i); } printf("Blastoff!");
The FOR-NEXT
loop is great when you know exactly how many times you want to run one or more commands. However, what if the number of times you want to run a loop can vary?
For example, you might have a loop that asks the user for a password, as shown in Figure 5-2. How many times should this loop run?
The answer is that the loop should keep running until the user types in a valid password. Because you don't know how many times the loop needs to run, you need to use a WHILE
loop to check a True
or False
(Boolean) expression. In this case, the Boolean expression is, "Did the user type in a valid password?" If the answer is yes (True
), the user can run the program. If the answer is no (False
), the loop asks the user to try typing in a password again.
The WHILE
loop typically looks like this:
WHILE (True or False Boolean expression) Command Command to change Boolean expression WEND
With the curly bracket languages, the WHILE
loop looks like this:
while (True or False Boolean expression) { command command to change Boolean expression }
The WHILE
loops consists of four parts:
The beginning of the WHILE
loop, which checks a Boolean expression for a True
or False
value
One or more commands to run
One or more commands that can change the Boolean expression in the beginning of the WHILE
loop
The end of the WHILE
loop
Before the WHILE
loop runs even once, it checks a Boolean expression for a True
or False
value. If this value is True
, the WHILE
loop runs. If this value is False
, the WHILE
loop doesn't run.
Within the WHILE
loop there must be one or more commands that can change the Boolean expression of the WHILE
loop to False
.
If a WHILE
loop doesn't include at least one command that can change its Boolean expression, the WHILE
loop runs indefinitely, creating an endless loop that hangs or freezes your program.
The following WHILE
loop keeps asking for a password until the user types SECRET:
DIM Answer as String PROMPT "Enter password: ", Answer WHILE (Answer <> "SECRET") PRINT "Invalid password!" PROMPT "Enter password: ", Answer WEND
Right before most WHILE
loops is usually a line that sets an initial value to a variable used in the loop's Boolean expression. In the preceding example, the value of the Answer
variable is set (initialized) to Answer
, which is whatever the user types in response to the Enter password:
prompt. Then the WHILE
loop checks if the value of the Answer
variable is SECRET
.
The first line defines the Answer
variable as a string
data type. The second line asks the user for a password and stores that answer in the Answer
variable.
The WHILE
loop first checks if the Answer
variable is SECRET
. If not, the loop runs the two commands that print Invalid password
and then asks Enter password:
on-screen once more.
Whatever reply the user types gets stored in the Answer
variable. Then the WHILE
loop checks this Answer
variable again before running.
You can make a WHILE
loop count like a FOR-NEXT
loop. Suppose you had the following FOR-NEXT
loop:
FOR I = 10 DOWNTO 1 PRINT I NEXT I PRINT "BLASTOFF!"
The equivalent WHILE
loop might look like this:
I = 10 WHILE (I >= 1) PRINT I I = I - 1 WEND PRINT "BLASTOFF!"
Although the WHILE
loop can count, notice that it takes more lines of code to do so, and the WHILE
loop isn't as easy to understand as the FOR-NEXT
loop. If you need a loop to run a fixed number of times, use the FOR-NEXT
loop. If you aren't sure how many times you need a loop to run, use the WHILE
loop.
Before a WHILE
loop runs, it checks a Boolean expression to see if it's True
or False
. If this Boolean expression is False
, the WHILE
loop never runs at all. What if you want to insure that the loop runs at least once? In that case, you must use a DO
loop.
A DO
loop acts like an upside-down WHILE
loop. First the DO
loop runs once and then it checks a Boolean expression. A typical DO
loop looks like this:
DO Command Command to change the Boolean expression LOOP WHILE (True or False Boolean expression)
This DO
loop keeps repeating while a Boolean expression remains False
. As long as this Boolean expression stays False
, the DO
loop keeps running.
You could use a DO
loop to ask the user to type in a password like this:
DIM Password as String Password = "" DO PROMPT "Enter password: ", Password LOOP WHILE (Password <> "SECRET")
This DO
loop always prints Enter your password:
at least once before checking its Boolean expression Password = "SECRET"
. If this Boolean expression is False
, the DO
loop stops running. If this Boolean expression is True
, the DO
loop repeats again.
Like the WHILE
loop, you often need to initialize a variable right before the DO
loop. This variable is usually part of the loop's Boolean expression to determine when the loop can stop running.
In the curly bracket language family, the DO
loop looks like this:
do { command command to change Boolean expression } while (True or False Boolean expression);
This DO
loop keeps repeating while a Boolean expression is True
. The moment this Boolean expression becomes False
, the DO
loop stops running.
Every loop (FOR-NEXT, WHILE
, and DO
) can run one or more commands multiple times. Therefore, it's possible for a loop to run another loop (which in turn can run a third loop, and so on).
The following shows a FOR-NEXT
loop nested inside another FOR-NEXT
loop, as shown in Figure 5-3:
FOR I = 1 TO 4 PRINT "Outer loop run #"; I FOR J = 1 TO 3 PRINT " Nested loop run #"; J NEXT J NEXT I
When one loop is nested inside another loop, the inner (nested) loop runs first. Then the outer loop runs once. Then the outer loop repeats running the nested loop again.
With nested loops, the nested (inner) loop runs more often than the outer loop.
In the preceding example, the outer loop runs 4 times and the nested loop runs 3 times, so the nested loop ultimately runs 12 times (3 * 4), as shown here:
Outer loop run #1 Nested loop run #1 Nested loop run #2 Nested loop run #3 Outer loop run #2 Nested loop run #1 Nested loop run #2 Nested loop run #3 Outer loop run #3 Nested loop run #1 Nested loop run #2 Nested loop run #3
Outer loop run #4 Nested loop run #1 Nested loop run #2 Nested loop run #3
The more nested loops you have, the harder it can be to tell exactly what your program actually does. As a general rule, it's best to nest only one loop inside another.
Loops normally run a fixed number of times (with a FOR-NEXT
loop) or until a Boolean expression changes (with a WHILE
or DO
loop). However, it's possible to exit prematurely out of a loop by using a special EXIT
command.
Prematurely exiting a loop means not waiting for the loop to stop on its own, such as
DO Play video game IF Player wants to quit THEN EXIT LOOP UNTIL (Game over)
In this case, the loop ends in one of two ways: when the game ends or when the user specifically quits the game.
To prematurely exit a loop, you always need to check if another Boolean expression is True
or False
. Generally, it's not a good idea to prematurely exit out of a loop because it can make your program harder to understand.
The curly bracket languages don't have an EXIT
command but a break
command, which works the same way, such as
do { Play video game; if (Player wants to quit) break; } while (Game over <> True);
Although loops eliminate the need to write the same command multiple times, loops also introduce the risk of making your program harder to understand as a result (and also harder to fix and update). So when using loops, keep these points in mind:
To loop a fixed number of times, use a FOR-NEXT
loop.
To loop zero or more times, use a WHILE
loop.
To loop at least once, use a DO
loop.
Both WHILE
and DO
loops usually need a variable that's used to check a Boolean expression to determine when the loop ends.
A WHILE
or DO
loop always needs a command that changes its Boolean expression that determines when the loop will eventually stop.
A loop that never stops running is an endless loop.
Some programming languages let you use an EXIT
(or break
command) to stop a loop prematurely. Use this with caution because it can make your program harder to understand.
When using a loop, always make sure you know how that loop will eventually stop.
Almost every program needs to use loops, so make sure you understand the differences between all the different loop variations you can use. Ultimately, loops let you run multiple commands without explicitly writing them all out, so think of loops as a programming shortcut.