Module 4 - Project
Assignment 4.10


Objectives: After studying the Module 1 Preparation Chip, you will be able to:

  1. List the three fundamental logic structures used in computer programming.
  2. Define the following terms: counter, start value, increment value, terminal value.
  3. Describe the syntax of the FOR-NEXT loop.
  4. Identify the three elements of the FOR-NEXT loop flowchart symbol.
  5. Predict the output of simple FOR-NEXT loop programs.
  6. Explain two ways the increment value can control how a FOR-NEXT loop counts.

YOUR LESSON

Introduction

There are three fundamental logic structures in computer programming: the sequence structure, the decision structure, and the loop structure.

  • The sequence structure is used when the path of the program follows a straight line, one statement after another. That is what you have been doing up to this point in the course.
  • The decision structure is used when programs need to "branch" off of the main path of the program based on a condition so that one set of code is executed if the condition is true and another set of code is executed if the condition is false. You will learn about decision statements in Module 5.
  • The looping structure is used when one or more statements (a block) need to be repeated a specific number of times. You will be introduced to looping structures in this Module of Basic 1, but loops are primarily covered in Basic 2.

Any program can be written using a combination of these three structures.

Loops can really increase the efficiency of a computer program as you will soon see. They will also make your programs somewhat shorter because you won't need so many variables.


Looping

A simple program is shown below. A little preview of Basic 2 is included--the RND function, which generates a random number. Programming languages have numerous built-in functions like RND to simplify programming tasks. The code that executes functions like RND is hidden from your view, but that's okay; right now, we are just interested in what it can do for us.

Try typing in the following short program, run it and observe the results. In fact, run it 3 or 4 times to see if you get the same results each time.

REM Random Number Generator
REM Your Name Here
REM Today's Date Here
RANDOMIZE TIMER
LET newnumber = RND
PRINT "The random number is: "; newnumber

LET newnumber = RND
PRINT "The random number is: "; newnumber

LET newnumber = RND
PRINT "The random number is: "; newnumber

END

Did you get three random numbers each time you ran the program? Were the numbers different each time? Hopefully you answered yes to both questions. If not, please carefully review the code and try again.

Before moving on, do a little experiment. There is another function in this short program called RANDOMIZE TIMER. What does that do? Glad you asked. Try taking it out and re-run the program three or four times. Do you still get different numbers each time you run the program? Hopefully not, but you will have to wait for Basic 2 to understand why. Sorry!

Instead of just three random numbers, let's assume that we need to generate 10 different random numbers. We could simply add seven more LET statements to return the random numbers and seven more PRINT statements to print them out. That would work, but it seems like a lot of effort. Or, imagine that you had to modify this program to produce 1000 random numbers. That's a lot of coding!

Here's an important lesson that you need to learn as a computer programmer. When you find yourself writing code that seems to be repetitive (that is, the same steps repeated over and over again), it is usually time to ask:

"Isn't there a more efficient way to do the same thing?"

Programs that require repetitive tasks usually take advantage of the third programming logic structure: the looping structure. QBasic has three different methods of handling repetitive programming tasks. You will learn about the easiest one, the FOR-NEXT loop, in this lesson and the other two in Basic 2.

The FOR-NEXT loop is perfect for handling our need to generate many random numbers.


The FOR-NEXT Loop

The FOR-NEXT loop is used when you need to execute a repetitive task a specific number of times. Consequently, a FOR-NEXT loop is also sometimes called a counting loop because a counter is used to control the exact number of times a loop is repeated. The syntax of a typical FOR-NEXT loop is shown below. (Don't worry, it makes more sense with an example, which you will see shortly.)

FOR counter = start value TO terminal value STEP increment value

some block of code would go here

NEXT counter

The FOR-NEXT loop is pretty easy to understand. The loop continues as long as the value of the counter is less than or equal to the terminal value.

  • the counter is a variable that counts the number of times the loop repeats
  • the start value is the number the counter starts with
  • the terminal value is the number the counter ends with
  • the increment value is the number the counter increases (or decreases) by each time through a loop

Take a look at the following short example of a simple counting loop that prints a line of code. You know what to do next--type it in and watch it run!

FOR n = 1 TO 10 STEP 1
PRINT
"Computer Programming is Fun"
NEXT
n

You should begin developing the ability to look at a program segment like this and predict exactly what it will do.

  • the counter is the variable n
  • the start value equals 1
  • the terminal value equals 10
  • the increment value equals 1

Given just this little bit of information, you should be able to predict the output of this program.



What would be the output of the previous program?

Computer Programming is Fun will be printed 10 times.
Computer programming is fun will be printed 10 times.
Computer Programming is Fun will be printed once.
None of the above.


Something that every programmer eventually does is put their name in the PRINT statement shown above (for example, PRINT "QB"). Go ahead and satisfy your urge to do that before we move on...nobody will know!

As long as you know the start value, the terminal value, and the increment value, it is pretty easy to determine how many times a FOR-NEXT loop will count.

The increment value can control a FOR-NEXT loop in two important ways.

  1. The loop can count "forward" (for example, from 1 to 100) or "backwards" (for example, from 1293 to -1407) depending on whether the increment value is positive or negative.
  2. The loop can count by different amounts each time depending on the "size" of the increment value (for example, 1, 23, -6, .1, or -25.8).

Let's look at another quick example. Type in the program and see what happens.

FOR n = 1 TO 10 STEP 1
PRINT
"The counter is: ";n
NEXT
n

This little program is not very impressive, but this type of looping structure is one of the workhorses of computer programming in any language. Experiment a little bit because inquiring minds will want to do the following. Start by making the change shown inside the parentheses below. Notice that the value(s) in bold type are suggestions of what to change. After you try the suggested changes, make some of your own.

  • Change the terminal value from 10 to other positive numbers (FOR n=1 TO 250 STEP 1). What happens?
  • Change the start value from 1 to any other positive number (FOR n = 75 TO 250 STEP 1). What happens?
  • Delete the increment value and the word STEP. (FOR n = 75 TO 250). Does it still work? What does the loop count by?
  • Does the loop work if the start value is greater than the terminal value (FOR n=200 TO 100 STEP 1)?
  • Change the increment value from 1 to any other positive number FOR n=1 TO 250 STEP 5). What happens?
  • Can the increment value be a decimal number (FOR n=1 TO 20 STEP .1)? For that matter, can the start and terminal values be decimal numbers (FOR n= .5 TO 23.5 STEP .1)?
  • What would happen if the start value was negative and the terminal value was positive (FOR n=-200 TO 250 STEP 1)?

You probably have many other questions about FOR-NEXT loops, so be sure to take some time to continue exploring on your own. After you finish, we will see how to make the loop count backwards.

There are also some things that can go wrong with FOR-NEXT loops. Try changing the counter variable in the FOR statement to x, but leave it as n in the NEXT statement.
FOR x = 10 TO 1 STEP -1
PRINT"The counter is:";n
NEXT n

Also, try leaving out the entire FOR or the entire NEXT statement and see what happens. In an earlier example, you were able to leave out the STEP part of the FOR statement, and the loop still counted by 1s. What happens if you leave out the STEP part of the FOR statement when the loop is counting backwards?


Loops can count forward and loops can count backwards. The direction depends on the start value, the terminal value, and the increment value. If the following conditions are met, the loop will count backwards.

  • The increment value must be negative.
  • The start variable must be greater than the terminal value.

That seems too easy, but it's true. Let's try it out. Make the start value 10, the terminal value 1, and the increment value -1 as shown in the following example.

FOR n = 10 TO 1 STEP -1
PRINT
"The counter is: ";n
NEXT
n

That's pretty neat. Now, ask yourself some questions similar to those in the previous example of the FOR-NEXT loop and learn some more interesting things!


The FOR-NEXT Loop: Visualizing the Process

Flowcharts are an easy way to visualize a computer algorithm. Most of the major keywords in QBasic have a flowchart symbol, and FOR-NEXT is no exception. The flowchart symbol used to create FOR-NEXT loops is shown to the right and indicates three important values:

  1. the start value
  2. the terminal value
  3. the increment value

A generalized example of a FOR-NEXT loop is shown below. Every FOR-NEXT loop follows this pattern.
  1. Program flow enters a loop and sets the counter variable to an initial start value.
  2. The value of the counter variable and the terminal value are compared.
    • If the start value is less than or equal to the terminal value, a block of code within the FOR-NEXT loop structure is executed.
    • If the start value is greater than the terminal value, control exits outside the FOR-NEXT loop and another part of the program is executed.
  3. After the block of code within the loop is executed, the counter variable is changed by the increment value.

Steps 2 and 3 are repeated until the value of the counter variable is greater than the terminal value.

Make sure you can clearly visualize the operation of a FOR-NEXT loop before moving on to the following example.

The FOR-NEXT Loop: A "Random" Example

The FOR-NEXT loop performs a simple, but very important programming task. It allows repetition of a statement (or a block of statements) a specific number of times. Assign a "correct" start value, terminal value, and increment value and the loop will repeat flawlessly.

Take a look at the flowchart to the right. Does it look somewhat familiar? It should--it is a program to generate random numbers. Let's dissect how it works.

  1. The RANDOMIZE TIMER statement selects a new seed for the Random Number Function. (You learn what that actually means in Basic 2.)
  2. A FOR-NEXT loop is established using N as the counter variable.
    • the initial value is 1 (N=1).
    • the terminal value is 10 (N<=10).
    • the increment value is 1 (N+1).
  3. As long as the value of the counter variable (N) does not exceed the terminal value, the block of code within the FOR-NEXT loop is executed as follows.
    • a random number is assigned to the variable newnumber
    • the value of the variable newnumber is printed
  4. Once the value of the counter variable (N) exceeds the terminal value, the program continues outside the loop. In this case, the program simply ends, but in another program there could be more code to execute.
The algorithm illustrated in the flowchart can be coded into the following simple program.
REM Program: Ten Random Numbers
REM Programmer: Random Rudy
REM DATE: 12/24/01
'
REM Set up the loop with to generate random numbers
RANDOMIZE TIMER
FOR N = 1 TO 10 STEP 1
LET newnumber = RND
PRINT newnumber
NEXT N
END

Do you recognize this program? It basically does the same thing as the program in this lesson's first example. (Instead of printing three random numbers, it prints ten.) Are you clear about how the program works? You can always email your instructor if you have questions!

Can you modify the loop to produce 100 random numbers? How about 1000 random numbers?

Feeling pretty confident about FOR-NEXT loops? Try the following challenge.



YOUR ASSIGNMENT

Let's do some simple math with two random numbers and a FOR-NEXT loop. Save your program as loop.bas.


1. Write a program that repeats 20 times.
Use a FOR-NEXT loop that counts
from 1 to 20.

2. Inside the loop, assign random numbers to two variables with the RND function.
The example above shows one random number being chosen
(LET newnumber=RND). Since you
need two random numbers, you will need
two different variables.

3. Now perform simple math with the two random numbers. Add the two random numbers, subtract the two random numbers, multiply the two random numbers, and divide the two
random numbers. Store the answer for
each calculation in a separate variable (something like answer1, answer2, etc.).

4. Inside the loop, use a PRINT USING statement to print your answers in
six columns ( the two random numbers and the results
of the addition, the subtraction, the multiplication, and the division operations.)

Here is an image which includes headers of how a program might be displayed. To add the headers, you would need to add a PRINT statement before the LOOP starts. The PRINT USING statement for the numbers would be inside the LOOP just before NEXT N. (Each time you run the program, the numbers should change.)



Important Note: Remember that all random numbers are decimal numbers less than 1, so you will have to be careful with the format code in your PRINT USING statement. For example, if the computer chooses .934 and .123, when these are divided you will get a decimal number greater than 1 (7.593). That means if you use a format code.###, it will not print the answer correctly. When you run your program, you can immediately spot a format code problem because there will be a percent sign in front of the number (%7.593). All you have to do to fix this is add more # symbols in front of the decimal point in the format code (ex. ##.###).

When you have completed this assignment, submit it through the In Box for Assignment 04.10.


A Quick Review

Before you move on to the next assignment, please make sure that you can do the following.

  1. List the three fundamental logic structures used in computer programming.
  2. Define the following terms: counter, start value, increment value, terminal value.
  3. Describe the syntax of the FOR-NEXT loop.
  4. Identify the three elements of the FOR-NEXT loop flowchart symbol.
  5. Predict the output of simple FOR-NEXT loop programs.
  6. Explain two ways the increment value can control how a FOR-NEXT loop counts.

FOR-NEXT loops are extremely important in programming. They provide the key to writing much more complicated and sophisticated programs.



After you complete this assignment, please continue to Assignment 04.11.

Attention: Be sure to read the instructions carefully in the next page because 04.11B is a timed test. In addition, you will be taking the 04.11A Oral Review and should do it before you complete the 04.11B test.


previousnext