home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Shareware Overload
/
ShartewareOverload.cdr
/
progm
/
m2t-1.zip
/
CHAP04.TXT
< prev
next >
Wrap
Text File
|
1989-01-18
|
21KB
|
529 lines
Chapter 4
LOOPS AND CONTROL STRUCTURES
WHAT IS STRUCTURED PROGRAMMING?
______________________________________________________________
There is a lot of talk these days about structured
programming, so we should know what it is. Structured
programming is really another way of saying, "do it right."
Instead of using sloppy coding techniques, you should plan
carefully what you are doing, and instead of using the goto
statement profusely to produce "spaghetti code", you should
use only sequential (statements in succession), iterative
(looping), and decision (selective branching) statements. It
has been proven that any logic can be reduced to these three
constructs, and that the goto is not required. Modula-2
forces you to very carefully think out your logic prior to
beginning to code since it does not have a goto statement
available. Depending on your programming background, this may
come as a bit of a shock to you, but you will find that as you
learn to use Modula-2, you will not miss the goto statement.
Many books are available on structured programming and you
would be advised to purchase one so you can study proper
programming techniques before you embark on a major
programming project.
REPEATING AND DECIDING
______________________________________________________________
Loops are some of the most important and most used constructs
in computer programming and in all parts of your life. You
use loops all the time for many things. Walking is a
repetition of putting one foot in front of the other until you
get where you are going. Eating a sandwich involves a loop
of eating, chewing, swallowing, etc. In this chapter we will
first cover all of the possible loops you can define in
Modula-2, then go on to the control structures, the decision
makers.
Examine the program LOOPDEMO.MOD. This is ================
a rather large program compared to the LOOPDEMO.MOD
ones we have seen so far, but it is felt ================
that it would be better to cover all of
the loops in one file than have you compile and run 4
different files.
4-1
Chapter 4 - Loops and Control Structures
THE REPEAT ... UNTIL LOOP
______________________________________________________________
Ignoring the declaration part of the listing and going
straight to the program itself, we come first to the repeat
loop which does just what it says it will do. It will repeat
until it is told to stop. The reserved word REPEAT in line
16 and the reserved word UNTIL in line 19 go together, and
everything between them will be executed until the condition
following the UNTIL becomes true. The condition can be any
expression that will evaluate to a boolean answer, true or
false. It can even be a composite expression with AND's,
OR's, and NOT's like we studied in the last chapter. It can
be composed of any of the simple types discussed so far as
long as the terms are all compatible and it evaluates to a
boolean value. In this case we have a very simple expression,
"Index = 5". Since the variable named Index is initialized
to 0 and is incremented each time we go through the loop, it
will eventually reach a value of 5 and the loop will
terminate, after which time the expressions following it will
be executed.
We are not quite finished with the repeat loop yet, since we
will have more to say about it when we complete the while
loop.
THE WHILE LOOP
______________________________________________________________
The while loop is very much like the repeat loop except that
the condition is tested at the beginning of the loop and when
the condition becomes false, the loop is terminated. Once
again, the condition can be as complex as desired but in this
case it is the very simple "Index < 5" following the reserved
word WHILE, in line 24, which will control the loop
termination. When Index reaches 5, the loop is terminated and
the statements following the loop are executed.
The biggest difference between the repeat and the while loops
is concerned with when the test is made. In the while loop,
the test is made at the beginning, so it is possible that the
statements inside the loop will not be executed even once.
In the repeat loop, the test is made at the end of the loop,
so the statements in the loop will always be executed at least
once. It is also good to keep in mind that the repeat stops
when its condition goes true, and the while stops when its
condition goes false.
There is another loop that we can use in which we exit from
the center using any test we can devise. It will be covered
after we complete the FOR loop.
4-2
Chapter 4 - Loops and Control Structures
THE FOR LOOP
______________________________________________________________
The for loop exists in one form or another in nearly every
programming language and you will use it repeatedly because
it is so useful. It uses the reserved words FOR, TO, BY, DO,
and END. It uses any simple variable type except real, and
counts loops depending on what counts you put in for beginning
and ending points. The first example on line 31 says for the
computer to start Index at 1 and count to 5, going through the
loop once for each value of Index. The count advances by 1
each time because nothing else is specified and 1 is the
default. The end of the loop is specified by the reserved
word END in line 33 in this case, and as many statements as
desired can be within the body of the loop.
The next loop starts in line 37 and this time counts from 5
to 25 but incrementing by 4 each time because of the "BY 4"
part of the line. The loop will continue until the second
limit is either reached or is going to be exceeded, at which
time the loop will stop. The beginning and ending limits can
themselves be some kind of a calculated value or a constant,
the only provision being that they must be of the same type
as the loop indexing variable. In fact they can be negative
and the increment value can be negative. This is illustrated
in the next loop that starts in line 48 where we count by -7
until we go from 5 to -35. No further explanation should be
required for this loop.
The next loop, starting in line 54, uses calculated limits to
determine its starting and ending points and it uses the
constant named Where for its incrementing value. The value
of the constant Where is established in the definition part
of this program as a constant. It is simply used here and
will be explained in a future lesson when we get to it. Where
is a constant with a value of 11, and the incrementing value,
used in any for loop must always be a constant, but not
necessarily a predefined constant as is used here. It can be
an implicit constant as illustrated in line 48.
A CHARACTER TYPE LOOP CONTROL INDEX
______________________________________________________________
The next two for loops use a char type variable and simply
count from A to Z, or backwards in the case of the second one.
The observant student will note that we are incrementing or
decrementing a char type variable each time we go through the
loop. Even though this is not permitted in assignment
statements, it is permitted in this case.
Several things should be pointed out about the for loop for
you. The three values must agree in type, that is the index,
the starting point, and the ending point. The index must not
4-3
Chapter 4 - Loops and Control Structures
be changed by any logic within the loop or the results will
be unpredictable.
The value of the index must be assumed to be undefined after
the loop terminates. You may discover that it is predictable
on your compiler, but it may not be on some other compiler,
and you may want to transfer your program to another system
someday, so if you find that the value is predictable, you
should not make use of that knowledge.
SUMMARY OF FOR LOOP RULES
______________________________________________________________
Since the for loop is so important, a practical list of usage
rules are given as follows;
1. You cannot alter the value of the index variable within
the loop.
2. The bounds and increment expressions should not depend
on anything within the body of the loop.
3. The value of the index variable is undefined following
loop termination.
4. The loop index cannot be;
a. An imported variable
b. A member of a record, array, or set
c. A real variable
d. A procedure formal parameter
The compiler will detect most of these violations and report
an error, but all compilers will not detect all of these
errors. You will understand all parts of rule 4 after you
complete this entire tutorial.
THE INFINITE LOOP
______________________________________________________________
The fourth and final loop is an infinite loop as illustrated
in lines 77 through 87. It uses the reserved words LOOP and
END, and it never terminates by itself. It is up to you the
programmer to see to it that some means of terminating it is
available, the most usual is through use of the exit
statement. Anyplace in the loop you can set up some
conditions for exiting based on whatever you desire.
Executing the exit procedure will cause the program control
to leave the loop and begin executing the statements following
the loop.
Now you have been exposed to the four loops available in
Modula-2, the repeat, while, for, and loop. Spend some time
4-4
Chapter 4 - Loops and Control Structures
studying this program, then compile and run it to see if it
does what you expect it to do. Loops are very important. You
will do the vast majority of your logical control in loops and
if statements, so it would pay you to thoroughly understand
both the loop and the if statement.
WHAT IS AN IF STATEMENT?
______________________________________________________________
Examine the program IFDEMO.MOD for an ================
example of some IF statements in use. IFDEMO.MOD
Ignoring the header, we notice that the ================
program is composed of one big loop
starting in line 10 and continuing to line 32. This loop is
included in order to have a changing variable to illustrate
the use of the if statement. Within the loop are 3 if
statements. The if statement is the most widely used
conditional statement in Modula-2.
The first if statement is given in lines 11 through 15
starting with the reserved word IF. It simply says "if the
value of Index1 is less than 4, then" do everything from the
reserved word THEN to the reserved word END which is
associated with it. If the value of Index1 is not less than
4, then all of these statements are ignored and the next
statement to be executed will be line 17 since it is the one
following the reserved word END. In a nutshell, that is all
there is to the simple if statement. Once again, the
condition in line 11 can be any expression that will evaluate
to a boolean result, and it can be composed of any of the
simple types of data elements.
THE ELSE CLAUSE
______________________________________________________________
The second if statement, beginning in line 17 has an added
feature, the else clause. If the boolean expression does not
evaluate to true, then instead of the expressions following
the reserved word THEN being executed, the group following the
reserved word ELSE will be executed. Thus, if the condition
is true, everything from the THEN to the ELSE is executed, but
if it is false, everything from the ELSE to the END is
executed. The end statement is therefore the terminator for
the effect of the if statement.
WHAT CAN GO IN THE IF STATEMENTS?
______________________________________________________________
You may be wondering what is allowed to go into the group of
executable statements between the then and the else or between
the else and the end. The answer is, anything you want to put
4-5
Chapter 4 - Loops and Control Structures
there. You can put other if statements, loops, input or
output statements, calculations, just about anything. If you
indent the statements properly, you will even be able to read
and understand what you put in there and why you put it there.
Of course, if you put a loop in there, for example, you can
put other constructs within the loop including other if
statements, etc. Thus you can go as far as you desire in
building up a program.
THE ELSIF CLAUSE
______________________________________________________________
The third and last kind of if statement is given in the third
example starting on line 24 and continuing to line 30. In
this case, if the expression within the if statement is found
to be false, the statements following the then are skipped and
the next construct is found, the reserved word ELSIF. If
program control comes here, it has a further expression to
evaluate, which if true, will cause the statements immediately
following its then to be executed. If this expression is
found to be false, the statements following the else will be
executed. The net result is that, one and only one of the 3
groups of instructions will be executed each time through the
loop. It is permissible to add as many elsif cases as desired
to this construct, leading to a many way branch. In addition,
the else is entirely optional regardless of whether or not the
elsif's are used. After studying this program, compile and
execute it and examine the result.
LOOPs IN IFs IN LOOPs
______________________________________________________________
Load and display the next example program ================
LOOPIF.MOD for an example of some of the LOOPIF.MOD
latest topics being combined. This ================
program makes nonsense data but is
valuable because it is small enough to understand quickly to
see how loops and ifs can be nested together. The entire
program is a for loop containing an if statement. Each part
of the if statement has a loop nested within it. There is no
reason why this process could not be continued if there were
a need to. Study this program, then compile and execute it.
FINALLY, A MEANINGFUL PROGRAM
______________________________________________________________
Load and display the program named ================
TEMPCONV.MOD for your first look at a TEMPCONV.MOD
program that really does do something ================
useful. This is a program that generates
a list of temperatures in centigrade, converts the list to
4-6
Chapter 4 - Loops and Control Structures
fahrenheit, and displays the list along with a note in the
table at the freezing point and boiling point of water. You
should have no difficulty understanding this program, so the
fine points will be left up to you.
A few comments on good formatting is in order at this point.
Notice the temperature conversion program and how well it is
formatted. It is simple to follow the flow of control, and
the program itself needs no comments because of the judicious
choice of variable names. The block header at the top of the
page is a good example of how you should get used to defining
your programs. A simple block header of that variety goes a
long way toward making a program maintainable and useful
later. Take notice also of the way the variables are each
defined in a comment. A program as simple as this probably
doesn't need this much attention, but it would be good for you
to get into practice early. It would be good for you to think
of each of your programs as a work of art and strive to make
them look good.
After spending some time studying this ================
program, compile and execute it. Load and DUMBCONV.MOD
study the next program named DUMBCONV.MOD ================
to see if you can figure out what it does.
If you are really sharp, you will very quickly see that it is
the same program as the last one but without all of the extra
effort to put it into a neat, easy to follow format. Compile
and execute this program and you will see that they both do
the same thing. They are identical as far as the computer is
concerned. But there is a world of difference in the way they
can be understood by a human being.
THE CASE STATEMENT
______________________________________________________________
Examine the program named CASEDEMO.MOD for ================
an example of the last decision making CASEDEMO.MOD
construct in Modula-2, the case statement. ================
A case statement is a "many-way" branch
based on some simple variable. In this program we have a loop
which sets the variable named Dummy to the values from 1 to
25 successively. Each time it comes to the case statement
which begins with the reserved word CASE, one of the branches
is taken. The first branch is taken if the value is from 1
to 5, the second branch is taken if the value is from 6 to 9,
the third is taken if it is either a 10 or 11, etc. Finally,
if the value is not found in any of the branches, the ELSE
path is taken as would be the case of a 12, a 13, or a few
others. The important point is that one and only one of the
many paths are taken each time the case construct is entered.
The case variable can be any of the simple types except for
the real type. For each path, as many statements can be
executed as desired before the "|" is put in to end that path.
4-7
Chapter 4 - Loops and Control Structures
The case statement is a powerful statement when you need it
but you will not use it nearly as often as you will use the
if statement and the various loops.
As with all of the Modula-2 constructs, a few extra rules must
be given for completeness. The case variable can only be of
a simple type, but not of a real type. Of course the case
selectors must be of the same type as the case variable and
they cannot be a conditional expression, only a single value,
a range, or a grouping of values as illustrated in the example
program.
The example program named BIGCASE.MOD ===============
gives an additional example of a case BIGCASE.MOD
statement. The primary difference in this ===============
case demonstration program and the last is
the addition of several conditional and looping statements
within the branches of the case statement. Little or no
comment is needed, so when you understand what it will do,
compile and execute it.
ONE FINAL CONTROL STRUCTURE
______________________________________________________________
At any point in the main program, you can put the reserved
word RETURN, which will cause a return to the operating system
when executed, effectively terminating the program. This
would probably be used as the executable statement in an if
statement, but could be included in any control construct.
This usage of the return statement is not illustrated in an
example program in this tutorial.
ONE MISSING CONTROL CONSTRUCT
______________________________________________________________
As mentioned earlier, there is no goto statement available in
the Modula-2 programming language. After you gain experience
in using a structured language, you will not miss this
construct.
PROGRAMMING EXERCISES
______________________________________________________________
1. Write a program that will put your name on the monitor
10 times using a loop.
2. Write a program that lists the numbers from 1 to 12 on
the monitor and prints a special message beside the
number that represents the month of your birthday.
4-8
Chapter 4 - Loops and Control Structures
3. Write a program that calculates and lists the numbers
from 1 to 8 along with the factorial of each. This will
require use of a loop within a loop. A factorial is the
number obtained by multiplying each number less than and
up to the number in question. For example, factorial 4
= 1 * 2 * 3 * 4. Use a cardinal type variable for the
result, then change it to an integer to see the
difference in output due to the range of the two
different variable types. This is a good illustration
of the fact that careful choice of variable type is
sometimes very important.
4-9