Ada 147964
Ada 147964
Ada 147964
1111.=
L. It~I
I125
1II 1.~4 1111
E .6 1.
% ....
MAJOR DTNSRDC ORGANIZATIONAL COMPONENTS
DTNWRDC
COMMANDER 0
TECHNICAL DIRECTOR
01
OFFICER-IN-CHARGE OFFICER-IN-CHARGE
CARDEROCK 050 ANNAPOLIS O
SYSTEMS
DEVELOPMENT
DEPARTMENT
11
STRUCTURES COMPUTATION;
DEPARTMENT MATHEMATICS AND
LOGISTICS DEPARTMENT
17 s16
DTNSRDC-84/062
4. TITLE (and Subtitle) S. TYPE OF REPORT & PERIOD COVERED
Peter N. Roth
9. PERFORMING ORGANIZATION NAME AND ADDRESS 10. PROGRAM ELEMENT. PROJECT. TASK
AREA & WORK UNIT NUMBERS
David W. Taylor Naval Ship Research
and Development Center
Bethesda, Maryland 20084
I. CONTROLLING OFFICE NAME AND ADDRESS 12. REPORT DATE
October 1984
13. NUMBER OF PAGES
119
14. MONITORING AGENCY NAME & ADoRESS(If different from Controlling Office) IS. SECURITY CLASS. (of this report)
UNCLASSIFIED
IS& DECLASSIFICATION/DOWNGRADING
SCHEDULE
*". 17. DISTRIBUTION STATEMENT (of the abstract entered In Block 20, It different from Report)
19. KEIY WORDS (Continue on reverse side if necessary anld Identify by block number)
Programming, fundamentals, computer, ratfor, FORTRAN, Pascal, C, basic,
debugging
(
20. ABSTRACT (Continue on reverese lde I necessary and Identify by block number)
TABLE OF CONTENTS
INTRODUCTION
...................................... 1
7. DEBUGGING ................................. 43
7.1 Think........................... 43
7.2 If You Reach An mpasse ..................... 43
7.3 Where TheIsOelsug...... ............ 43
7.4 Fix The Error .............................. 43
"7.5 Bebuing .................................. 43
9. RA F .. o . oooo
.... ooo .oo .eooo....o .. ooo.
. ooooo.. eo
..
.v
11.9 Determinate Iteration...................... 72
1 1.*10 Altered Loops.. . .. *. ......
* .............
** ** ** 73
114.6 Multiple Choice.* ... ...... ... ... ... ........ 103
14.7 While .......... 0.0........................ 103
14.8 Repeat-Until..................... 103
*14.9 Determinate Iteration..................... 103
14.*10 Al tered Loops ............ _..... . ... ..... 1014
14.11 BASIC Summary ....... .. .. .. .. .. .. .. .. .. .. . .. 105
14.12 Program Header........................... 106
-V-
14.13 Running a BASIC Program .................... 106
141.114 Examples ................................... 107
17. GLOSSARY ..
- ....................................... 112
DTIC
ELECTE
SO2 6 984
B
*bi--
jklai an/o
By... .. .
Dist Spcta
-v
- Vi -
ABSTRACT
ADMINISTRATIVE INFORMATION
INTRODUCTION
- you should have some acquaintance with your computer's 'operating system'
(the program that lets other programs run);
- you must be able to wield a text editor (the program that lets you type
* programs and data into your computer);
- you have to be expert enough in your technical field to know that you need
to do some computing;
- you have to express the solution to your technical problem in some program-
ming language.
Operating systems and text editors have been addressed in other documents (see
[Roth831' and [Roth82l), and I can't begin to teach you your field, but perhaps
* I can help you with the programming process itself.
Programs can be written by applying a few simple principles. This text teaches
these simple principles in a language you already know, i.e., English. I will
further presume, however, that you are trying to become familiar with the syntax
d, % Pof one of the programming languages illustrated here.
Over 85% of the programs in the world are less than 200 lines long, so you will
probably spend most of your programming time writing programs of this size.
Development of larger programs is a different story because you need a well-
*References are indicated by the first four letters of the author's name
followed by the year of publication, in brackets. A complete listing of
references is given on page 111.
INTRODUCTION
I have a few other objectives for writing this text. First: algorithms are
often published in a language bearing great resemblance to Pascal and Algol. It
is desirable to be able to read these algorithms, and perhaps convert them into
other languages. By presenting the principles of programming here in several
languages, I hope to make it easier for you to read and understand these algo-
rithms.
Second: (a confession) I am comfortable using several kinds of large mainframe
oomputers because I am familiar with the way they behave. I know how to use
several text editors and many other software tools, having invented several of'
my own.
* I noticed that I was extremely reluctant to program the Texas Instruments TT59
'. ' programmable pocket calculator. I examined my motives for putting off1 working
with the machine, and arrived at the following list of technical and emotional
issues:
-The user manual is thick. ('You mean I have to read all this to write a
crummy program?')
-There aren't many experts around for me to talk to when I run into trouble,
or, they would be busy with their own work (which I would be disturbing); I
was on my own.
0 If you don't understand something on first reading, skip over it. Later
text should make it clear.
-2-
* INTRODUCTION
- I didn't know what response the machines would make to my commands; conse-
quent'y I didn't know what questions to ask when something 'went wrong.'
- Work with the machines is tedious. There are no software tools to help
program these devices.
- I don't have time to learn how to use the machine. And running speeds are
very slow.
You may have similar apprehensions about using mainframe computers. I believe
my excuses (the ones with emotional content) stem from the 'fear of the
unknown.' So, in addition to the reasons mentioned above, I wrote this to remove
as many unknowns as possible, and thereby reduce the fear level.
Finally: remember that if you can afford to write a couple of drafts of a report
or letter, you should allow yourself the 'luxury' of doing two drafts of a pro-
gram. Be prepared to throw the first draft away; you will anyway. Relax and
enjoy yourself.
-3-
WV
i!q%* . %' * .
07
Bef'ore you write any program, you should ask yourself' three questions:
You should be able to answer the first question in one sentence. If' you can do
what you want to do faster with a pencil and paper, you probably don't need a-
program.
If'the answer to the second or third question is 'yes,' you can often save your-
self' a lot of' work by using an existing program instead of' writing a new one
(you can also skip reading this text). Assuming that a program doesn't exist to
do what you want, or an existing one doesn't do it the way you want it done, and
there's no one around who can write it f'or you, you may decide to compose your
own. Now you need to know something about programming.*
But you don't need to know a lot! In f'act, you need only the following Four
Principles:
- Half' of' the constructs may be altered in at most two ways (Chapter 4).
When you apply these principles, you can compose your program in English (or the
reasoning language in which you do your other thinking) and then translate the
'English' program into the programming language of' choice. The closer the tar-
get language is to the way you think, the easier the translation will be.
Of'ten, the choice of' programming language is predetermined, because you are
* modif'ying a program which already exists, or you are writing the program f'or
someone else.
* . My own practice is to think with a pencil and paper,** making notes in a mixture
of' English, ratf'or, and Pascal, which I then translate completely into the tar-
get programming language. Although some panache is demonstrated by developing
programs on scraps of' paper, envelope rears, and irregular corners of' slates, it
is advisable to keep the notes you make when you develop your program. These
0 Notice that the initial ef'fort in writing a program is to avoid writing a
program!
00 Rather than erase errors, I f'ind it pref'erable to cross them out and rewrite
correctly. The crossed-out stutff provides a trace on the path of' my
thinking, which is sometimes helpf'ul to have when debugging time comes.
THE FOUR PROGRAMMING PRINCIPLES
* will help you when your boss insists that you docuent your work in a more
appropriate form, such as a report. It is easier, of course, to write the
users' manual for your program before you write the program itself.
Efficient' programs use little computer time and little computer memory. But:
*computer time and memory are in most cases just too cheap to worry about! Your
*time is infinitely more valuable than silicon time. Thus, efficiency is that
which makes your life 'easier.' Paraphrasing Boudreau [Boud7l], "A big, slow,
correct program is better than a slick wrong one." So get it right before you
make it 'fast.' As you gain experience using the four Principles, you will
notice that you are producing programs which are not only correct, but readable,
understandable, and quite fast, as well.
The action "translating completely into the target programming language" is
called "coding." Because translating incomplete thoughts into a programming
language is quite difficult, please regard the following maxim:
THE SOONER YOU START CODING,
THE LONGER IT WILL TAKE TO FINISH YOUR PROGRAM.
* When the translation from English to programming language is complete, the pro-
gram can be typed into a computer (see [Roth82l for help in this area), and com-
piled and executed using the procedures of rRoth831. Each of the language
chapters in this report also shows how to do it.
----- 7~WT, .0- N7.* -. 2.
2. DATA
Variables are things which may assume the values of different constants.
2.2 Types
We can assign values to, and examine the values of, variables according to the-
tyeof the data.
The data types useful for the majority of straightforward engineering programs
- are:
integer Numbers which have no fractional part. Most often used to count
things. For example, the number of keys on a piano is an integer con-
stant (88). A variable used to store this data type is called an
'integer variable.'
real Numbers which may have a fractional part. Useful for representation
of physical quantities like mass, density, thickness, location in
- . space, etc. The ratio of the circumference to the diameter of a cir-
cle is a real constant: 3.14159.... A variable used to store this
data type is called a 'real variable.'
Boolean (or logical). An item of Boolean data may have only one of two possi-
ble values: 'true' or 'false.' This type allows control of programs
through logic. It is 'true' that 2.0 is greater than 1.0. A variable
used to store a Boolean constant is called a %Boolean variable.'
character Used to read and write the character set available on the machine.
These are typically the lower case letters, the upper case letters,
the digits, the space, the tab, special symbols such as 1,@, etc.
A variable used to store this data type is called a 'character vari-
* able.'
2.3 Expressions
The data organizations most useful for straightforward engineering programs are
* the simple variable, the array, and the file.
-6-
DATA Data Organizations
2.41.1 The Simple Variable A simple variable is a thing to which you can assign
values according to its type, compare its value with variables or expressions of
the same type, and write the value of the var'iable (so you can see the results
* of assignments and comparisons).
All computing with variables is done in accordance with the variable's type.
For example, we can assign "position on the x-axis" to a variable we name X of
type real. Or we can assign the truth of the expression "X is greater than 6.1"
to a variable B of type Boolean.
2.41.2 The Array An array is an ordered, determinate number of variables. You
should think of an array as a single entity, even though it may have many parts.
For example, the direction cosines of a vector form a single array of three real
data items. We might name this array DIRCOS.
The generalization from simple variable to array suggests 'an array of arrays,'
Ian array of arrays of arrays,' etc. For example, we can consider the location
of a point in space to be given by the three real coordinates of the point: X,
Y, and Z (the names of three real simple variables). Or, we can consider the
location to be given by an array which contains three real variables. Suppose
we name this array %X.' Then X(1) could be the 'x' coordinate, X(2) the %y'
coordinate, and X(3) the 'z' coordinate.
Further, if we have 10 points in space, we can conceive of them as an array of
-: arrays. Suppose we name the array COORD. Then we need 10 'places' in the array
(one for each point). In each of the 'places' we need an array of three real
variables (one for each axis). So,
In the COORD array, therefore, the first 'subscript' gives the number of the
-. point and the second gives the axis of measurement. The important thing to note
is that the array concept allows us to deal with a lot of numbers with a single
name.
Note that although each item of an array can be of any type (the example above
used an array of type real), the subscripts are always of type integer. TRy
using integers in control structures, we can process arrays very quickly and
V with great economy of language.
'-7
NN
Data Organizations DATA
-This report originated as several files on a UNIX* system (at the time I
first wrote this sentence, the files were 2306 lines long, and had 9020
'words' made up of 51560 characters).
Files are used for input and output to computer programs. Although the 'memory'
of a computer is indeed finite, the files available to a program are conceptu-
* ally infinite. This allows us a handy place to temporarily save large numbers
* of simple variables and arrays which would exceed the capacity of the computer's
memory.
Because of' the possibility that files can be very long, programming languages
usually provide access to files through a "window;" that is, you
only get to see
* a little of it at a time. The shape of this window is greatly dependent on the
operating system and the language being used.
2.14.4 Other types and organizations Although the types and organizations men-
tioned above are satisfactory for the vast majority of the programs which you
will write, the list is incomplete. FORTRAN, for example, provides the addi-
tional types
*complex A variable which has a 'real' and 'imaginary' part; both of the parts
are represented internally as 'reals'.
Taking the Humpty Dumpty hint, we will wish to name variables in such a way that
their names give us a clue to their essence. Because English is our language,
we have no limitations on the length or style of a variable name. What is
interesting about English (or mathematical) variable names is that they are
assigned in a context which preserves their meaning. Thus, when we say some-
thing like, 'Let P be a point in space,' then the name 'P' somehow is seen to be
tied to the word 'point.' Of course, a second point would need another name to
make it distinct from P. Mathematicians will usually try to pick a name that is
somehow close to the first name, and yet obviously different; perhaps 'Q' (it is
near' P alphabetically). We note that P and Q are short names because we usu-
ally prefer not to write very much. At the same time, names (i.e., words) which
are longer than eight characters are usually at least three syllables, which
makes them hard to read and harder to type.
On the other hand: a textbook which defines 'P' on page 2, say, and never
reminds us that P is a point, is going to be a difficult text to refer to.
That's why mathematicians are always redefining things for their readers; con-
* text is usually limited to about a page or two. You should cultivate the same
* habit in your programs, because programs are not always read from beginning to
* end; one enters them at any place suitable to the need at hand. It is therefore
important that the program reader be able to get a fair understanding of what is
going on from the immediate context.
* Thus:
* Exercise: Obtain someone's program (preferably one of your own that is at least
6 months old), and take a look at the variable names. Can you tell what they
are? Why or why not?
-10-
3. THE THREE PARTS OF EVERY PROGRAM
- The Initialization.
- The Computation.
- The Clean-up.
3.1 The Initialization
- On some computers, the operating system itself provides much of the program ini-
tialization. The pieces most often under your control are the declaration of
variable type, and the initialization of variables to some value. The declara-
-tions are much like the statements preceding a mathematical proof ("Let f be a
smooth continuous function in the domain D with f' the first, and f" the
second, derivative of f with respect to distance in D").
* hsis comparable to the way in which a report or book is written: the last
parts to be written are the introduction and the abstract.
-11-
* *The Computation THE THREE PARTS OF EVERY PROGRAM
This is the program part which does your work. It is the part where you will
use The Constructs.
* In this part of the program, we save those things which we need to keep, throw
away the garbage, and exit from our computations gracefully (if possible).
-12-
4. THE CONSTRUCTS
In this fairly long chapter, I present The Constructs both in English and graph-
* ically.
* The facility for logic built into programming languages is a mechanical imple-
mentation of Boolean logic. Boolean expressions are those which allow us to
*test truth and falsity according to the rules of logic formalized by Boole. A
* Boolean expression may have only one of two values: TRUE or FALSE.
4I.2 Form of Boolean Expressions
In the following, X and Y are variables or expressions of the same type, and
each 'Boolean expression' will be either TRUE or FALSE.
X is greater than Y.
X is equal to Y.
X is not equal to Y.
X is less than Y.
One of the most important statement types is the assignment statement, which has
the form
X ao E
* We emphasize that the assignment statement is not the same as the 'Boolean
expression 'X equals E'; the assignment statement is an action, whereas the
Boolean expression is an assertion.
For example, let's assume that the integer variable X has the value 1. Then
X equals X + 1
is false, whereas
X becomes X +1
where the arrow into the box indicates that control is passing to the statement
'S.' When the statement 'S' has completed its action, control passes to the
'next' statement to be executed; this is represented by the arrow out of the
box.
_114-
* THE CONSTRUCTS The'Assignment Statement
In general, the notation "S'may be read as 'n statements in sequence' where "n"
is greater than or equal to 0. Thus,
Most contemporary computers are sequential machines, which means that statements
are executed in the order in which they are accessed. Thus, if we write the
statements Si, followed by S2, followed by 33, the statements will be executed
in the order S1, S2, S3 unless we somehow change this order. This 'changing' is
- done with The Constructs. Please note that each of The Constructs is also a
"statement,' and may be hooked together just as any of the 'other' statements of
a language are.
I°
I.
, 15
*The Conditional Construct THE CONSTRUCTS
If B,
then S.
For example:
If "it is raining"
then "carry an umbrella."
In this example, the Boolean expression B is: "it is raining." This expr'ession
may be TRUE or FALSE. The action to be performed, S, is "carry an umbrella."
FALSE
* where the 'if' part of the statement is represented by the B inside the diamond.
If 'B' is true, then the true path is taken, and 'S' is done. If 'B' is false,
then the false path is taken.
THE CONSTRUCTS The Alternative Construct
When there are alternative actions which may. be performed, we can use the Alter-
native construct. Given that B is a Boolean expression, then the Alternative
construct has the form
If B
then Si;
else,
S2.
For example:
If "it is raining"
then "carry an umbrella;"
else,
"lower convertible top."
Note that these actions are mutually exclusive. That is, "if it is raining"
then the only statement which is executed is "carry an umbrella." "If'it is not
raining," then the only statement which is executed is "lower convertible top."
IS
-17- S
211.
The Multiple Choice Construct THE CONSTRUCTS
Out of a number of possibilities, we may wisb to select the appropriate one and
do the statement(s) associated therewith. For example:
In case of
rain: "carry an umbrella"
snow: "wear parka and hat"
hail: "stay home"
tornado: "goto cellar"
sunshine: "play tennis"
where only one of the choices is elected. Thus, "goto cellar" and "play tennis"'
are mutually exclusive options.
where we have included the last 'else' to take care of the time when none of the
weather conditions we know about occurs.
" -18-
b*
!FALS
•B :
B2
.. . 3.
IS
•
,,
ia
-19
Iteration THE CONSTRUCTS
4.7 Iteration
Iteration is one of the great strengths of computers: the machines will do the
same actions over and over with no complaint.
- Test, then (perhaps) act. This iteration construct is called the While.
-- 20
2Y:
.20
while P,
S.
Note that the statement S may not be executed at ailt For example:
FASLSE
* The 'going back'-ness of this construct is what gives rise to the term 'loop' to
describe iteration. I will henceforth use the terms 'iteration construct' and
s%,'loop' interchangeably.
40
Iteration THE CONSTRUCTS
4.7.2 The Repeat-Until Construct This iteration places the test at the end of
the loop. Note the difference between the While and the Repeat-Until: the
statements controlled by the While may not be executed, whereas the statements
under control of the Repeat-Until are guaranteed to be executed at least once.
Given that B is a Boolean expression, then the Repeat-Until construct has the
Repeat
Si.
S2.
Until B.
In this construct, the statements S1 and S2 are guaranteed to be executed at
least once. For example:
Repeat
"brush uppers"
- . "brush lowers"
Until "teeth are clean'
The Repeat-Until can be diagramed
FALSE
_22-
THE CONSTRUCTS Iteration
* Let B be a Boolean expression which compares the values of the integer variables
* I and K (say, for example, B is the expression "I is less than K"). Then the
- determinate iteration construct has the form
I becomes J.
While B
S.
I becomes I + M.
I
-where the braces '[' and ' define the complete range of statements under con-
trol of the While. Note that there exists the possibility that statements "S"
* and "I becomes I + M" may not be executed at all (why?).
As an example of this construct, let's find and print the largest element MAX in
an array of integers ZOT which has N elements. Let's say N =3 and the contents
of ZOT are
ZOT(1= 27
-~ ZOT(2) = 31
* ZOT(3) =12
Let's assume we have an integer variable %IV which we can use to access each of
the elements of the array ZOT. We'll also assume that the contents of ZOT are
* calculated in some other part of our program, and that we don't know what the
values of ZOT are. We do know that there are N values we have to look at, and
-23-
Iteration THE CONSTRTJCT3
that we'd better look at them all. So, here is an English 'code fragment' which
will allow us to find MAX
Exercise: mark the three parts of this program fragment to show the initializa-
tion, computation, and clean-up phases.
Now let's step through the calculations by substituting numerical values for
each variable:
Exercises:
*3. How would you change this program to make it work for N 0? What value
would you assign to MAX?
-24-
' .
-°* S ~ -
-- 25-
4,V
Altered Loops THE CONSTRUCTS
The first unusual circumstance is 'stop iterating immediately (i.e., leave the
loop);' the next statement to be executed is the one which follows the termina-
* tor of the loop. This construction is typical in parts of programs which check
data for errors and reach an impasse.
While Bl1
Si.
If B2
then "break"
Else,
S2.
S3.
In this construct, the word "break" means that computation is to continue with
statement S3, which is entirely outside of the range of the While.
The Loop Exit can be used to alter any iteration construct; it is diagramed
modifying a While.
TRUE TRUE
61S
FAS
.MI
THE CONSTRUCTS
While B1 {
Si.
If B2
then "next"
Else,
S2.
S3.
In this construct, the word "next" means that computation is to proceed with the
next test B1. That is, "next" says "continue computation with the statement
'While B1." By the way, use of the "next" is extremely rare (I have used it
infrequently, and find few uses in the references).
The Loop Redo can be used to alter any iteration construct; it is diagramed
modifying a While.
i s1
.TRUE
'B
1 B2
FALSE FALSE
S2
-27-
Construct Summary THE CONSTRUCTS
Conditional: If B then
S.
Alternative: If B1 then
Si.
Else
32.
Repeat-Until: Repeat
t? S
Until R.
Determinate: I becomes J.
While H {
S.
I becomes I + M.
-28-
W6b *** -. . ~ * -
-How the iteration is supposed to stop will hint at the form of the con-
struct. By the way, make sure it will stop!
-You can always use a While (you might have noticed that the two other,
iteration constructs are really variations of the While).
-If you can count the data items to be processed, then the Determinate
* iteration is usually proper.
Examples THE CONSTRUCTS
4.11 Examples
These examples are a good opportunity for some exercise. For each case, write
an 'English' program, and compare it to the-sample solution shown at the end of
the chapter. Then translate your program into a programming language and com-
pare your translation with the example shown in the section devoted to that tar-
get language.
C 5*(F - 32)/9
where the symbol '*' means 'multiply,' and the symbol "I means 'divide.'
and write down the answer -40C in a second column. Since we haven't completed
our job yet (we haven't reached 1OOF), we add 5F to the current temperature
(-40F) to obtain -35F. With Fahrenheit temperature of -35F, we plug and chug,
producing -31C. We continue this process until the table is full.
-30-
- , -:.
', . ' ' ' " ."",""-"
"-"". - . "-A . ,
THE CONSTRUCTS Examples
4.11.2 Nearest Points Given 10 points in 3-D space, find the two points which
are nearest to each other.
The solution to this problem is intuitively obvious. We merely compute the dis-
tance from each point to its neighbors using the distance formula
where 'd' is the distance, "sqrt' represents the square root, '002' represents
squaring a number, 'x2" is the x-coordinate of "one" point (y2 and z2 are the y-
and z-coordinates of this same point), 'x1" is the x-coordinate or "another"
point (yl and z1 are the y- and z-coordinates of this same point).
Those two points which are at the minimum distance are the two closest neigh-
bors.
Additional exercises:
1. Modify your program to rind the points which are farthest apart.
2. Print all pairs of points which are at the same minimum (maximum) distance.
o.1°
4. -31-
Examples THE CONSTRUCTS
41.11.3 Count the 'A's Read <input> and count the number of 'A's in the file.
This is a simple problem mentally, but is quite tedious and prone to error.
* Let's assume that we can tell when we have reached the end of a file, much like
we can tell when we've reached the end of a book. Then we need merely read the
* file a character at a time, and check to see if the character we've just read is
*an 'A.' If it is, then we can increase our count of 'A's by one. (Hint: What
does the initial value of our count have to be, i.e., before we read any charac-
* ters? Does your program give the correct count when there are no 'A's? When
* there are no characters at all?)
* Additional exercise: modify your program to read real numbers from a file and
count the values greater than some threshold, say, 10.0. Assume that the last
line in the file will have the number -99999.0.
-. 32
.4%A
THE CONSTRUCTS Solutions to the Examples
Initialization - declarations:
F becomes -40.
Computation:
Cleanup:
(none!)
~*'*@ *Ap *- .9
*°."
-33-
Solutions to the Examples THE CONSTRUCTS
Initialization - declarations:
Computation:
I becomes 1.
While "I is less than or equal to 9" {
J becomes 1+1.
di; While "J is less than or equal to 10" {
J becomes J+1.
I (end of While "J is less...)
I becomes 1+1.
I (end of While "I is less...)
Cleanup:
-34-
THE CONSTRUCTS Solutions to the Examples
4.12.3 Count the 'A's
Initialization - declarations:
Count becomes 0.
Read Ch.
Computations:
Cleanup:
Print: Count.
L-35-
'-v
Assuming that you've written your program cor~rectly in 'English' and correctly
translated it into a programming language, how do you get it onto the machine
and running?
Presuming you are working with a CDC machine, the steps necessary are:
- typing the program into the computer using a text editor (with ED, for
example fRoth82]),
(code)
-s 1
.5 s
~~~LOADE R " •
(abs s
.--.. I've called the file of code that you write with ED %<code>.' It will be a file
" " of, say, FORTRAN, ratfor, or Pascal.
.-- A COMPILER is a program which translates a higher order language' (your code)
' into 'machine language,' which is very difficult to read and understand, and
which varies from one brand of machine to another. Compilers were invented to
'-- '. reduce your need to look at the machine language, and express yourself in a way
"' .which is portable from one machine to another.
- The machine language file is called <lgo> (from load and &0_). It is difficult
(impossible) to read <lgo> with ED; if you do enter ED with a <go> file, you
will destroy it if you do a SAVE!
-36-
GETTING YOUR PROGRAM TO RUN
'Loading' is a process which allows you to use things which other people have
written, including the transcendental functions, the input/output routines,
graphics routines, etc. Only files of machine language are LOADed, so the pro-
cess is largely invisible to a casual programmer. Naturally enough, LOADing is
performed by a program called a LOADER, which reads your <lgo> file and writes
its product, the "absolute' program, into a file called <abs>. <abs> is the
only kind of file which can execute on a CDC machine (<abs> is also imppssible
to read with ED).
Execution is the performance of work according to the program you wrote. This
is done by typing the command 'abs.'
The solid lines in the sketch show the path of intellect when everything goes-
right.' Unfortunately, everything going right on the first shot is a rare
occurrence. Still, you want to spend as little time as necessary in this 'loop'
trying to get your program to run. You can use the aids in the next two
chapters to make everything 'go right' as soon as possible.
The dotted arrows show the path of intellect when something 'goes wrong.' You
eliminate errors by repairing <code> and repeating the compile-load-go process
until no errors exist, since the tools used here are very reliable. That is,
* except in extremely rare cases, the errors are yours, not the computer systems'.
The easiest ways to effect this loop quickly are through the use of the pro-
cedures in Chapter 4 of [Roth83].
l
";, -37-
te
6. THE PROGRAM CHECKLIST
Although programs can be designed and coded from simple principles, the devil
*hides in the details. To prevent this ancient foe from getting a toehold on
their code, experienced programers can often be observed practicing seemingLy
weird and lengthy incantations before they run their programs. The list
presented in this chapter extends one found in (Myer7ql and initiates the novice
*into this cabala. Scan through this list and compare your program to each of
the questions asked here.
2. Are there any variables which are not referenced? Is this because you
misspelled a variable name?
3. Are all array references within the bounds of the array size?
4i. Are all array references selected with an integer subscript? Some
languages allow REAL type variables as array subscripts (it is best to
2 avoid this 'feature'). If you do this, is the subscript what you expect it
to be?
5. Is a variable being assigned a value which does not match its type?
6. Are there any 'off-by-one' errors in referencing array elements?
7. If an array is referenced in several procedures or subroutines, is it
defined identically in all sections?
*6.2 Data Declaration Errors
*1. Have all variables been explicitly declared? Undeclared arrays can be
misinterpreted by some compilers as functions.
*3. Are all variables and arrays initialized properly? I.e., do the values
assigned to each variable agree with the types of each variable?
4. Are there any variables with similar names (e.g., POINT and POINTS)? This
is not necessarily an error, but it is a sign that names may have been con-
fused or misspelled somewhere in the program.
-38-
THE PROGRAM CHECKLIST Computation Errors
7. Can a variable go outside its meaningf'ul range? For example, can a vari-
able measuring probability ever be greater than 1.0?
8. Is the assumption of' the order of' evaluation correct f'or expressions which
contain more than one operator?
9. Are there any invalid uses of' integer arithmetic? For instance, if'T Is an
integer variable, 2*1/2 is equal to I only if'I is even and only if'the
multiplication is done f'irst.
1. Are there any comparisons of' variables of' incompatible types? I.e., are
characters compared with reals?
3. Are the compariqon operators correct? Most of' the difficulty arises in the
combined use of' 'and', 'or', and 'not.'
4. Are the operators of' logical expressions of' type logical? For example, to
determine if' I is between the values ? and 10, the correct expression is
(2<1)&(I<10), not (2<I<10).
5. Are there any comparisons of' numbers with fractional parts in which trunca-
tion errors play a role?
**1. Is it possible that certain entry conditions will prevent execution of' your
program? For example, in the loop
% A -,- . * - . ._
Construct Errors THE PROGRAM CHECKLIST
2. Can the number of selections in a Multiple Choice construct ever exceed the
number of possibilities you've allowed for?
5. Are there any "off-by-one" errors (too many or too few iterations)?
S3. Do the attributes of each passed variable match the attributes of the
*received variable? For example, is a simple REAL variable passed to a
module which expects an array?
* . 4. Are the units of each passed variable correct? For example, is the passed
-j value expressed in degrees while the expected value is expressed in radi-
ans'?
5. Does the number of variables passed by a module equal the number of vari-
ables expected by the called module? Are they in the correct order?
6. Are the number, order, and type of variable correctly passed to 'built-in'
* .functions? For example, does the arctangent function require one or two
arguments? If two, which one is the divisor?
-140-
THE PROGRAM CHECKLIST Interface Errors
*7. Does a subroutine alter a value which is supposed to be only input? For
example, is an argument defining the length of an array used as the index
to a determinate loop? What is it's value on return from the module?
8. Are global variables referenced the same way in all modules? In FORTRAN,
for example, are the variables listed in COMMON blocks the same everywhere?
9. Are constants ever passed to subprograms? For example, the FORTRAN state-
ment
* CALL SuIB(A,3)
Many languages permit several ways to access files. If you are using these
f'eatures, check your program with this list:
* 1. Are file attributes correctly declared?
*3. Does the format specification agree with the READ statement?
*4. Are arrays declared to be large enough to contain all the information to be
read?
*8. Are there spelling or grammar errors in any messages written by the pro-
gram? Are the messages intelligible?
6.8 Miscellany
1. If the compiler you are using has a 'post mortem dm'switch, set it to
[ - 'on.'- This switch will allow the computer to print, at the time of your
program's death, the values of your variables according to their types
(rather than in their octal or hexadecimal representation). I.e., the
values of REAL variables are printed in engineering notation, INTEGERs are
printed as integers, LOGICALs are printed as TRUE or FALSE, etc. The clues
offered by this tool are extremely helpful. (Note that the procedures of
Chapter 4 of [Roth831 have this switch set 'on'.)
-41-
Miscellany THE PROGRAM CHECKLIST
2. Does the compiler cross reference map indicate variables which are unused
or referenced only once? This may not be an error, but might point to
misspellings.
*3. Are the attributes which the compiler assigns to each variable the ones you
expected?
* 14*Did the compiler produce any 'warning' messages (assuming of course that
you have a successful compile)? These messages point to potential prob-
lems.
- -5. Is the program or module sufficiently 'robust?' That is, does it check its.
- input for validity, or can it be killed with a 'reasonable' number?
6.Does the program NOT do something that you expected it would?
-42-
7. DEB~UGGING
Your program has finally 'compiled' and *go'ed, but produces erroneous output.
This is caused by 'bugs' which must be found and exterminated in order for the
program to be 'correct."*
This chapter provides an approach to bug eradication; don't forget the checklist
in the previous chapter. Many of the following suggestions are from [14yer791.
1 7.1 Think
The building size necessary to contain a computer with the power of your brain
would exceed that of the Empire State Building. You may not be able to calcu--
late quickly, but you can intuit. You should be able to debug most of your pro-
grams without going near a computer.
-sleep on it. Your subconscious mind has great potential for working things
out while you're doing something else. This is not an excuse to catch a
4 few z's on the job.
there are likely to be more. Examine the immediate vicinity of a bug for other
errors, since bugs usually result from a misunderstanding of what the program is
supposed to do. Note also that small pieces of code may be veritable 'roach
hotels;' there are such things as error-prone modules.
Don't just fix the symptom of the error. Make sure that all occurrences of' the
error are fixed, not just this 'Just-discovered' one.
7.5 Bebugging
* Recognize that fixing a program is likely to introduce new bugs, because the
* entire concept of the program may not be fresh in your mind.
7.6 Faulty Bug Repair
Your 'fix' may be wrong! The probability of a correct fix decreases with the
* size of the program, and varies with the size of the fix. Bug repair should
* place you mentally in the program design stage.
*if you would rather wave your hand and say, 'Yeah, I know it doesn't work
for such-and-such a case, but so whatl?' then the bug is known as a
'feature.'
3-.
_.4
K...Use Debugging Tools DEBUGGING
7.7 Use Debugging Tools
never.
-44-
8. THE LANGUAGES
The second most important requirement of computer programs is that they be legi-
ble to humans.* We use programming languages when we talk with computers because
English is imprecise (although we humans can understand it even when it is
misusedl). While we maintain precision in our programming, our computer talk
must also be understandable by humans, because we are the race which must 'main-
tain' the programs. This understandability is controlled first, by the language
itself, and second, by the way in which we use the language.
•.- 5-
FORTRAN77 The most recent revision of' FORTRAN. The major updates it provides to
FORTRAN66 are: the CHARACTER type, string processing, the block IF-
THEN-ELSE, and greater explicit control over Input/Output WIO). Syn-
tax is still somewhat inconsistent; and the meaning of' one of' the FOR-
TRAN66 constructs has been changed(t).
FORTHAN66 The 'standard' scientif'ic language since 1954. It is the lingua
f'ranca of' the engineering community. All of' the 'large' f'inite ele-
* . ment programs have been written in FORTRAN66, and almost all computer
vendors offer a FORTRAN66 compiler. Syntax of' this language is
unusual, and it f'orces you to write your program backwards f'rom the
- * way you would express it in English. But 'everyone' knows it, so its
anomalies are generally overlooked or unrecognized. It is to your.
advantage to write in some other language if'possible; 'ratf'or' is a
reasonable alternative.
Ada* This language is now under development. It is the new 'standard' DoD
language f'or embedded systems (systems which are part of' some other
machine, such as a tank, a ship, a torpedo, etc.). Ada is an
.'enhanced derivative' of' Pascal.
Algol This family of' languages preceded the development of' Pascal. It is
the native language of' Burroughs machines.
APL A very powerf'ul, very cryptic, language. The information content of'
.APL programs is extremely dense. Per (Kell81l, APL is "so compacted
that the source code can be freely disseminated without revealing the
programmer's intent or jeopardizing proprietary rights." It is impos-
sible to maintain programs written in APL; one throws them away and
redoes them.
Assembly Assembly language is a mnemonic method f'or addressing the computer's
'instruction set.' Usually, it is a very primitive language (note,
however, that the Burroughs machine instructions are Algol, a 'high
level' language). Programming in assembly language is undesirable
because it takes too much time to do it, and because it is nigh impos-
sible to move it to another vendor's machine. Certainly, some pieces
of' some programs should be written in assembly language (data acquisi-
tion programs and arcade games, for example), but because it can take
ten times more humnan time to write assembly than some other higher-
* order language, it is rare that one can recover an investment in
assembly language code development. The code produced by optimizing
* - compilers is as good as, and in many cases, better than, the code one
could produce 'by hand' using assembly language. Theref'ore, assembly
_46
THE LANGUAGES Languages Excluded
COBOL A language designed primarily for business purposes, and not very use-
ful for engineering purposes.
. FORTH A 'threaded' language in some use on microcomputers, which forces the
programmer to act as part of the compiler. This language immortalizes
reverse Polish notation (alias 'Okie code') in programs; FORTH pro-
grams are hard to read.
Lisp The de facto language of the artificial intelligence community. It is
not designed for, and hence has seen little use in, number crunching.
Modula-2 Niklaus Wirth's successor to Pascal. It removes many of the difficul-
ties associated with program development in Pascal, but distribution
of this language has not been wide-spread to date.
PL/I IBM's answer to the FORTRAN/COBOL dichotomy. An enormous and complex
language. Never really caught on in the engineering community.
_ 7
'
-.
1-47- - ... ..
'0
79. RATFOR
Blocks of statements in ratfor are grouped 4rith braces "{ and "}'. On CDC sys-
tems, these may be entered as either braces or brackets '[ 1'. Unfortunately,
the CDC character set is not common across all the printers, so brackets may
appear as either brackets or braces.
There are three ways to provide commentary in ratfor programs: with a 'C' or
in column 1, or with a '#' anywhere. You should start your program text in
column 2 or 3 so that a 'C' or a '' in column 1 is not interpreted as a comment
line. Blank lines are ignored by ratfor, so you may also use these to provide
* additional 'white space.
The type definitions may also be used to declare the dimensions of arrays, so
the DIMENSION statement is not needed in ratfor or FORTRAN programs.
ratfor uses the 'reserved word' concept; i.e., there are several words which are
special to ratfor. Thus, in ratfor programs, you may not use any of the follow-
ing words for variable names: break, do, else, if, next, repeat, until, and
while.
-t/ _
44..
4,
X >= Y or X => Y
X is equal to Y:
X == Y
X is not equal to Y:
X ^= Y (on CDC)
X != Y (on UNIX)
X is less than Y:
X<Y
X is less than or equal to Y:
X <= Y or X =< Y
X = expression
(Same as FORTRAN.)
9.4 Conditional
if (B)
S1
S2
} # end if
-49-
Au*- %, '
-76.7~.~ **
Alternative RATFOR
~ 9.5 Alternative
if (B){
Si
N S2
elsef
S3
# end if
* 9.6 Multiple Choice
The clearest way to select from multiple possibilities is with a series of If-
Then-Else 's.
if (B1)
Si
else if (B2)
S2
else if CB3)
S3
else
Sn
9.7 While
while (B)
Si
S2
# end while
-m I until (B)
where it is helpful to a reader to have the termination condition of the loop
presented in commentary on the Repeat line.
1;Iz -50-
An
do I = J,K,M f
Si
S2
) # end do
while (81) f
Si
if (B2)
break
S2
) # end while
while (BI) {
SI
if (B2)
next
S2
I # end while
SIn general, the only labels you need in a ratfor program are those on FORMAT
statements.
-51-
Generalized Iteration RATFOP
ratfor provides a generalized iteration scheme called the For. It has the form
initialize
while (B) [
S1
S2
reinitialize
1
The For may be easier to understand in some circumstances because it keeps all
terms which control the loop on a single "line.'
-4
-V
4-
.4
-- 52
, RATFOR ratfor Summary
Conditional: if (B)
S
Alternative: if (Bl)
Si
else
S2
Multiple Choice: if B1
S1
else if B2
S2
else if B3
-. S3
else if R4
-- $4
Determinate: do i = J,k,m
-. S
,53
-53
2..
°,
C.L * *3
Program Header RATFOR
The ratfor program header requires a comment line which identifies the program,
followed by the same information as that required in a FORTRAN program. On CDC
machines, this has the form
Assume you have composed your program with a text editor on a CDC computer and
the code is in <p>. Assume further that you have already executed the commands
ATTACH,ROTHICCLLIBID=CSPRo
LIBRARY,ROTH.
(you must execute these commands only once). Then the program in <p> may be run
*. with the command
rr'p.
(see [Roth83]).
'4,f
..
'€
€' .",? :';':'.".-"
."2 :'€ , :",";,'
""' .', ",. ',"," " " " " " ' . .i ,: .". ", J ". '" ' ' " .
" 5".
RATFOR Examples
9.15 Examples
-55-
* *. , *, . q***/. ~~
F- o .-
Examples RATFOR
9.15.2 Nearest Points Assume that the three coordinates of each point are
typed on a single line of <input>.
# near - find 2 of 10 points which are closest neighbors
program near( input, output)
real x(10,3) # array of points
real oldd,newd # distances between points
integer i,jk,mn # counters
do i = 1, 9 (
ipl = i + 1
do j = ipl, 10 {
newd = sqrt( (x(i,1)-x(j,1))**2
+ (x(i,2)-x(j,2))**2
+ (x(i,3)-x(j,3))**2)
if( newd <= oldd ) # found a new nearest neighbor
#
4.-.
nj
oldd newd
I# end do j
# end do i
print *,' closest points are at
print I, (x(m,i),i=1,3), (x(n,i),iz1,3)
end
.44.
.'..,,.
,..
*'' -56-
•,
RATFOR Examples
9.15.3 Count the 'A's Approachs assume that each line has at most 132 oharao-
ters, and read an entire line at a time* Also assume that character variables
can be represented as integers (this works on CDC machines)* If the line Is
shorter than 132 characters, FORTRAN will act as if the nonexistent characters
-~ were bl~anks. If the line is longer than 132 characters, the excess will be
(silently) truncated (perhaps not the best solution),
count = 0
* read(5,1) (line(i),i1,132)
1 format(132a1)
while( eof(5) = 0
do i =1, 132
* . if( line~i) =='A')
count = count + 1
red51 lnf)i112
print *,count
end
-57-
10. PASCAL
Blocks of statements in Pascal are grouped with the symbols *begin' and *end';
you might think of them as 'fat brackets.'
Pascal is a free-format language. That is, you may begin your code in any
column. It is a good idea to indent your code so that the logical structure of
the program is reflected by the lhyout of the text on a page.
The symbol '(*" or 'I' opens a comment, and the next occurrence of the symbol
)' or ')' closes a comment.* Comments may occur anywhere and may extend across
line boundaries. Blank lines are ignored by Pascal, so you may also use these
to provide additional 'white space.'
10.1 Variable Names
As in English, Pascal does not limit the number of characters in a variable
name. Most implementations of the language only guarantee that the first 8
characters are significant. That is,
a~ajl lngname
afairlylongnamewithstuffontheenj
probably refer to the same variable. Although it is possible to use any number
of characters, limit yourself to at most 12.
Note that Pascal forces you to declare the types of your variables before you
use them. So while you are declaring their types, you might just as well insert
some commentary which declares their purposes.
Pascal uses the reserved word' concept; i.e., many words are special to Pascal.
Thus, in Pascal programs, you may not name a variable %if,' 'while,' 'repeat,'
S-etc. A full list of the Pascal reserved words is given in tJens74].
-.- 58-
X is greater than Y:
.
4-.
x >=Y
X is equal to Y:
X is not equal to Y:
S.
U-X<>y
- X is less than Y:
X( <Y
X <= Y
" 10.3 Assignment Statement
X := expression
* 10.14 Conditional
if B then begin
Si;
S2
41 end;
. The semicolon is used in Pascal to join statements. 'begin' and "end' are
reserved words' which serve the same function as brackets in rator.
.4.
"4
-59-
Alternative PASCAL
_O. Alternative
if B then begin
S2
end
else begin
S3;
S14
end ('if*);
There are two ways of selecting from multiple alternatives: the case and the
if ... else if constructs.
case I of
Li: Si;
L2: 92;
L3: S3;
Ln: Sn
end (*case*);
The labels 'Li, 'L2', 'L3', ... , 'Ln' are the legitimate values which 'I' can
assume.
if B1 then
Si
else if B2 then
S2
else if B3 then
S3
* else if B4 then
S4(* end if #);
U-.-
. -60-
* PASCAL While
10.7 While
while B do begin
Si;
S2
end(Owhiles);
10.8 Repeat-Until
repeat (0 until B 0)
S1;
s2
until B;
This construct is made clearer to a reader by putting the termination condition
in commentary on the Repeat line,
for I := J to K do begin
Si;
S2
end(Otor*);
10.9.2 Decreasing Index
_" In these constructs, J is the initial value of I, and K is the terminal value.
Note that, if the initial condition satisfies the test for termination, the loop
will not be executed. In Pascal, the increment to a loop may be +1 or -1. No
other values are possible. For increments other than +1 or -1, use a While or
Repeat-Until construct.
6j
-61-
10.10.1 Loop Exit Although any loop (While* Repeat-Until, Determinate) may be
"exit'ed, we illustrate with a While.
label 13;
while Bl do begin
01 ;
if B2 then goto 13;
$2
end(*whilet );
Although this construct is possible, and indeed works, most Pascal-ers would not
recommend it. Clearer, and more in keeping with the style of the language would
be something like
because it presents all the loop terminators in a single statement (the While
statement) and it presents the logic in explicitly logical terms rather than in
terms of transportation ('goto label').
-62-
PASCAL Altered Loops
10.10.2 Loop Redo Although any loop (While, Repeat-Until, Determinace) may be
re-do'ed, we illustrate with a While,
label 13;
while B! do begin
SI;
if B2 then goto 13;
32
13: end(*whilef);
Although this construct is also possible, and indeed works, I do not recommend
it. Rather, the following is preferreds
while B1 do begin
Si;
if B2 then begin
(0 empty 'begin end': a do-nothingl ')
end
else begin
S2
end
end(Cwhile');
I"T.
* *,.,:".. ,. ..
Pascal Summary PASCAL
Conditional: if B then
S;
Alternative: if B1 then
s1
else
S2;
* Multiple Choice: case I of if BI then
BI:, SI; SI
B2: S2; (or) else if B2 then
B3: S3;
B 32
B4: S4 else if 83 then
end; S3
else if B4 then
While: while B
S;
Repeat-Until: repeat
S
until B;
-- 64-
.d - .%"": ,,.';,'; 3".", -
,
#'s,.J." *dJ '.. .'
•
'",'""..,* -" .
444". "", . """ . ,
•
" "." "-'"
"
PASCAL Program Header
begin
The program is closed with an %end' which matches the opening %begin', followed
by a period. That is, the last symbol in the program is 'end.'.
Assume you have composed your program with a text editor on a CDC cemputer and
the code is in <p>. Assume further that you have already executed the commands
ATTACH,ROTH,CCLLIB, ID=CSPR.
LIBRARY,ROTH.
(you must execute these commands only once). Then the program in <p> may be run
with the commands
pc , p.
lgo.
q * S' --
-65-
Examples PASCAL
10.111 ExMples
.- program ftoc(output);
begin
f := -40.0;
while f <= 100.0 do begin
a := 5.00(f - 32.0)/9.0;
writeln(f,c);
f := f + 5.0
end (*while')
end.
e .
. .-.
--
---
66
66-
var
x: array[l..10,1..31 of real; (0 points in space *)
oldd,newd: real; (* distances between points 0)
i,j,k,m,n: integer; (0 counters 0)
begin
for i := 1 to 10 do
for j := 1 to 3 do
read(x[i,j]);
for i :=1 to 9 do
for j := i+1 to 10 do begin
i newd :=sqrt( sqr(x[i,1j-x[J,1])
* + sqr(x[i,23-x[J,2])
+ sqr(xti,31-x[J,3i) );
if newd <= oldd then begin (' found a new nearest neighbor*)
m := i;
n := J;
oldd := newd
end ('if')
end (0 for J ');
write " closest points are at ");
for i : 1 to 3 write(x[m,il);
for i : 1 to 3 write(x[n,ii);
writeln
end.
-67-
begin
count := 0;
while not eof do begin
read(ch);
if ch = 'A' then
count := count + 1
end(* while 0);
writeln(count)
end.
* 1P
%o % 7
02 -68-
11. C
Blocks of statements in C are grouped with braces •{ and "}'. As of this writ-
ing, no C compiler exists for CDC computers; it is a language which lives on
many other brands, however. These include DEC's PDP-11/xx and VAX 11/7xx, IBM
machines of various sizes, and many microcomputers.
SC is a free-format language. That is, you may begin your code in any column.
It is a good idea to indent your code so that the logical structure of the pro-
gram is reflected by the layout of the text on a page. Blank lines are ignored
by C, so you may also use these to provide additional 'white space."
Comments may occur anywhere and may extend across line boundaries. The symbol
•'/" opens a comment, and the next occurrence of the symbol '/' closes a com-
ment.
C uses the 'reserved word' concept; i.e., there are a large number of words
which are special to C. Thus, in C programs, you may not name a variable 'if,'
'while,' 'break,' etc. A full list of the C reserved words is given in
*[Kern78].
. Only the first 8 characters in a name are significant. More may be used, how-
ever. A practical limit is 12 characters.
11.2 Boolean Expression
X is greater than Y:
, X>Y
X >= Y
X is equal to Y:
X == Y
X is not equal to Y:
;@ X 1= Y
X is less than Y:
x <Y
X is less than or equal to Y:
X <2 Y
-69-
Assignment Statement C
X = expression ;
-" Note that in C, statements are terminated with a semicolon, rather than joined
" as in Pascal (a subtle, but sometimes painful, difference).
11.41 Conditional
if (B) {
.;
*- s i;
- S2;
) /0 end if 0/
11.5 Alternative
if (B) {
Sl;
S2;
else f
S3;
S4;
. / end if V/
70
4.
4.
O.
4-
dl -70-
C Multiple Choice
There are two ways to select from multiple possibilities: if ... else if's, or
the Switch.
11.6.1 if ... else if
if ( B1 )
Si;
else if ( B2 )
S2;
else if ( B3 )
S3;
else
Sn;
Indenting successive "else-if's is deemed by some to make the program text
easier to read.
11.6.2 Switch
switch ( I ) f
case LI: 51;
case L2: 32;
case L3: S3;
Choosing between the 'switch' and multiple 'if ... else if's is mostly a matter
of style, although the switch can be faster in some circumstances.
0-,
6.°
|.-%i-
t-
While C
11.7 While
while (B) {
SI;
S2;
} I' end while 0/
11.8 Repeat-Until
do ( /* while B I/
S1;
S2;
} while (B);
C provides a generalized iteration scheme called the For. It has the form
initialize;
while (B) {
Si;
S2;
reinitialize;
I
Note that the initialization and reinitialization steps need not necessarily be
strictly related to counting of discrete program iterations. The For may be
easier to understand than a While in some circumstances because it keeps all
terms which control a loop on a single 'line.'
-72-
11.10.1 Loop2 Exit Although any loop (While, Repeat-Until, Determinate) may be
'exit'ed, we illustrate with a While.
while (81)
Si;
if (B2)
break;
while (81)
if (82)
continue
k
-V3-
C Summary C
11.11 C Summary
Conditional: if (B)
, S;
Alternative: if (B)
Si;
else
S2;
Repeat-Until: do
S
while (B);
Determinate: for(init; B; reinit)
5;
• °
I*~.
a * ** ~ * .a -
V : ',*.t*'%* %ia
-74-
C Program Header
C is not yet available on CDC machines. On a UNIX system, the C program header
is
main ()
Assume you have composed your program with a text editor on a UNIX system and
the code is in <p.p>. Then the program in <p.c> may be run with the commands
cc p.c
a.out
.5
-75-
11.14 Examples
main()
float f,c
-..
f = -40.0;
while ( f <= 100.0 ) {
c = 5.00(f - 32.0)/9.0;
printf("%4.Of %6.lf\n",f,e);
f f + 5.0;
iI -76-
11.14.2 Nearest Points In this example, please note that you must provide the
*function "gtarray' (to read the values into the x array), and that the "sqrt"
function must be made available to your program by accessing the appropriate
system library. C doesn't have an exponentiation operator, either, so you must
either multiply the terms yourself (as I've done here) or provide a function to
do it.
newd f.n;
ror(k 1; k <= 3,- + <1)
newd: newd + (x[ilrkl-xrllrkl)*(xril[kl-xfi 1rkl);
newl = sqrt(newd);
,.
-77-
Po
Examples C
.intc,na;
.:.'.na = 0;
~while( (c=getchar()) 1= EO )
.-. if( a == 'A'
• + na;
printf("%d\n",na)
where "getchar' is a function which gets the next character from <input> and
puts it into the variable %a.' If <input> is at end of file, then 'getchar'
assigns a non-character value to c (a system dependent constant of 0 or -1).
avoid this issue by using the symbolic EOP.
°
-1.
'.°
°-5
-78-
. .55. ./ .- . 5'.,
55, 5,,', .'-' ' , '.' ' V
-. *.,¢.. . -,• , .. , ,
%*1 del 5*
12. FORTRAN77
Blocks of statements in FORTRAN77 are grouped only in the "if ... then else'
statement, since blocks are a new concept in FORTRAN. It is advisable to
"create' blocks of statements by using the FORTRAN77 do-nothing CONTINUE state-
P- ment.
FORTRAN77 requires that the text of a program be contained in columns 7 through
72. That is, you may begin your code in any column after column 6. It is a
good idea to indent your code so that the logical structure of the program is
reflected by the layout of the text on a page.
Since all The Constructs are not available directly in FORTRAN77, you may find
it easier to use ratfor than this language.
12.1 Variable Names
-.
7
-yq
6'.
Boolean Expression FORTRAN77
X is greater than Y:
X .GT. Y
X is greater than or equal to Y:
X .GE. Y
X is equal to Y:
X .EQ. Y
X is not equal to Y:
X.NE. Y
X is less than Y:
X .LT. Y
X .LE. Y
.17
-80-
FORTRA7 ssignment Sttement
FORTRAN77 statements end at the end of a line. Long statements may be continued
for up to 19 additional lines by providing a non-blank, non-zero character in
column 6 of the continuation lines (columns 1 through 5 must be blank). Note
however, that long FORTRAN77 statements are like long sentences: they're hard to
read, hard to understand, and hard to correctl Strive for short statements,
even if it means inventing new variables to contain the results of intermediate
calculations.
12.4 Conditional
if( B ) then
SI
S2
endif
12.5 Alternative
if ( B ) then
S1
S2
else
S3
S4
endif
if ( B1 ) then
S1
else if B ) then
B2
S2
else if ( B3 ) then
S3
else
Sn
endif
-81-
While FORTRAN77
12.7 While
This construct must be simulated. Because a.reader may not immediately recog-
nize the construct, it should be annotated as a While. Note that FORTRAN77
forces you to express the Constructs in terms of transportation - "GOTO label"
is a rather indirect way to express a logical concept.
C while B
23000 if ( B ) then
Si
S2
goto 23000
endif
C end while
12.8 Repeat-Until
This construct must be simulated. Because a reader may not immediately recog-
nize the construct, it should be annotated as a Repeat-Until.
C repeat until B
23000 continue
Si
S2
if ( B goto 23000
12.9 Determinate Iteration
do 23000 I = JK,M
Si
32
23000 continue
-82-
FORTRAN77 Altered Loops
*12.10.1 LopExit
23000 if ( B1 ) then
S1
if ( 82 ) goto 23001
S2
goto 23000
endif
23001 continue
23000 if ( H1 ) then
SI
if ( 82 ) goto 23000
S2
goto 23000
endif
,,
-p8.
I
:.-4 . . .
-84-
-S. . V. ** *-
. FORTRAN77 Program Header
4Assume you have composed your program with a text editor on a CDC computer and
*" the code is in <p>. Assume further that you have already executed the commands
ATTACH,ROTH,CCLLIB,ID=CSPR.
LIBRARY,ROTH.
(you must execute these commands only once). Then the program in <p> may be run
with the command
vcqp.
abs.
(see [Roth83]).
4, -85
12.14 Examples
12.14.1 Temperature Conversion
-8'6
°..
'._ ":
**-o* -.
* -. * * * *
FORTRAN77
Examples
12.14.2 Nearest Points Assume that the three coordinates of each point, are
typed on a single line of <input>.
>'. IP1 = I + 1
[- DO I J = IP1, 10
DO2~M
NEWD I = 1SRT( (X(I,1)-X(J,1))**2
".$ + (X(l,2)-X(J,2))**2
$ + (X(1,3)-X(J,3)),12)
CN|EW MINIMUM FOUND?
IF( NEWTD .LE. OLDD )THEN
N. J
.- " OLDD = NEWD
.ENDIF
1 CONTINUE
•2 CONTINUE
I ,[:PRINT ,"CLOSEST POINTS ARE AT
.,'\"PRINT *, (X(M,I),I=1q3), (X(N,I),T= I,1)
\. END
.8
4".~
Examples FORTRAN77
12.14.3 Count the 'A's Approach: assume that each line has it most 132 charac-
ters, and read an entire line at a time. Also assume that character variables
can be represented as integers (this works on CDC machines). If the line is
shorter than 132 characters, FORTRAN will act as if the nonexistent characters
were blanks. If the line is longer than 132 characters, the excess will be
(silently) truncated (perhaps not the best solution).
PROGRAM COUNTA
C. COUNT THE NUMBER OF 'A'S IN <INPUT>.
C
INTEGER COUNTI
CHARACTER LINE '132
COUNT =0
OPEN(UNIT-5 ,FILE= 'INPUT')
C WHILE NOT END OF FILE
1 READ(5,2,END=3) LINE
" 2 FORMAT(A132)
DO 4 I = 1, 132
IF(LINE(I:I) .EQ. 'A') THEN
COUNT - COUNT + 1
ENDIF
4 CONTINUE
GOTO 1
C END WHILE
3 CONTINUE
PRINT *, COUNT
END
* -88-
13. FORTRAN66
If there is any way to avoid writing programs in this language, you should take
it. One way which comes readily to mind is the alternative 'ratfor,' which pro-
duces FORTRAN66 but allows you to express your program in terms more nearly like
English. Note that the straight-forward application of FORTRAN66 costs you time
and effort because you must convolute your natural thought processes when you
-. write the program, and then again when you go looking for errors.
The type definitions may also be used to declare the dimensions of arrays, so
the DIMENSION statement is not needed in FORTRAN programs (see, for example, the
program in section 13.14.2).
o .
q -,.-
. o. 4.• . * * * * ~ * * ~ * * * * 4 * * 4 '
EEEEEEEEEEIhEE
[EKE.IIIIIII
IIII'
,
-.L
Uii
1.
.
&61111
-
1.511111 L4 1122.
•L 6
M3O RT
N RD
111.0
Boolean Expression FORTRAN66
X is greater than Y:
X .GT. Y
X .GE. Y
X is equal to Y:
X .EQ. Y
X is not equal to Y:
X .NE. Y
X is less than Y:
X .LT. Y
X .LE. Y
,* X = expression
FORTRAN66 statements end at the end of a line. Long statements may be continued
for up to 19 additional lines by providing a non-blank, non-zero character in
column 6 of the continuation lines (columns 1 through 5 must be blank). Note
however, that long FORTRAN66 statements are like long sentences: they're hard to
. read, hard to understand, and hard to correct! Strive for short statements,
, even if it means inventing new variables to contain the results o intermediate
*calculations.
" -90-
4
* FORTRAN66 Conditional
if(.not.(B))goto 23000
Si
S2
23000 continue
13.5 Alternative
if(.not.(B))goto 23000
C B IS TRUE
Si
32
goto 23001
23000 continue
C B IS FALSE
S3
S41
23001 continue
Commentary in FORTRAN66 are lines with the symbol 'C' in column 1. Because the
control structures are more difficult to understand in this language, they
should be more thoroughly commented than in other languages.
13.6 Multiple Choice
This form of multiple choice makes you assign a statement label and a condition
number to any of the choices you wish to make.
goto ( 1,2,3,...,n ), I
1 51
goto m
2 S2
goto m
3 S3
goto m
n Sn
m continue
-91-
L 2I.
While FORTRAN66
13.7 While
This construct must be simulated. Because someone who reads your program may
not immediately recognize the construct, it should be annotated as a While.
C WHILE B DO
23000 if(.not.(B))goto 23001
$1
S2
goto 23000
23001 continue
13.8 Repeat-Until
This construct must be simulated. Because a reader may not immediately recog-
nize the construct, it should be annotated as a Repeat-Until.
C REPEAT UNTIL (B)
?3000 continue
S1
S2
, 23001 if( .not.(B) )goto 23000
:.-.
,,-92-
1o'- 2."
FORTRAN66 Determinate Iteration
do 23000 I = JK,M
S1
S2
23000 continue
-93-
-94
.S
'.
n Sn
m continue
-95-
- 4*b~t- M=.747477- : 7 b7-
Assume you have composed your program with a text editor on a CDC computer and
the code is in <p>. Assume further that you have already executed the commands
ATTACH,ROTH, CCLLIB,ID=CSPR.
LIBRARY,ROTH.
(you must execute these commands only once). Then the program in <p> may be run
with the command
-" fc,p.
abs.
(see rRoth83]).
=--
.6
~-96-
I~~ _m - - If
..- MTV-
FORTRAN66 Examples
13.14 Examples
PROGRAM FTOC(OUTPUT)
C
C. FTOC - FAHRENHEIT TO CELSIUS CONVERSION, -40F TO 1OOF
C
C F = FAHRENHEIT9 C CELSIUS
REAL F,C
. F =-40.0
C WHILE F <= 100
1 IF(F .GT. 100.0) GOTO 2
C = 5.01(F - 32.0)/9
PRINT 0,F,C
F F + 5.0
.* GOTO 1
C END WHILE
2 CONTINUE
6END
•
.9
r|
9.4
...
.:
i
-qT-
13.14.2 Nearest Points Assume that the three coordinates of each point are
typed on a single line of <input>.
5,.--98
.45
S'S
_. S*S
. *** ~ . . . . .
r-9
-'" . . . . . . . . ..
FORTRAN66 Examples
13.14.3 Count the 'A's Approach: assume that each line has at most 132 charac-
ters, and read an entire line at a time. A.so assume that character variables
can be represented as integers (this works on CDC machines). If the line is
shorter than 132 characters, FORTRAN will act as if the nonexistent characters
were blanks. If the line is longer than 132 characters, the excess will be
(silently) truncated (perhaps not the best solution).
' a,..
' ' '%
- S % W 4. ~~ ~
tt . *72. ~K
FORTRAN66
k 14. BASIC
There are many versions of BASIC. The following remarks therefore apply to
BASIC in a general sense; for specifics, you will need the BASIC manual for your
system.
Comiments are provided in a BASIC program by putting the string 'REM' (for
REMark) as the first entry following the line number. Because the control
structures are more difficult to understand in this language, they should be
more thoroughly commented than in other languages.'
Since few of the Constructs are available directly in BASIC, you may find it
easier to use any other language.
The names of BASIC variables may be one or two characters long. The first char-
acter must be a letter, and the second may be a letter or a numiber. Most BASICs
assumne all variables are of type REAL (i.e, they have fractional parts). Char-
acter type variables usually include the ' as the last character in the name
-100-
BASIC Boolean Expression
X is greater than Y:
'., x>Y
x >= Y
X is equal to Y:
X--Y
X is not equal to Y:
X <> Y
X is less than Y:
x <XY
X is less than or equal to Y:
X <= Y
-101-
* A n S eB
LET X = expression
14.4 Conditional
14.5 Alternative
10 if not B then 50
15 rem B IS TRUE
20 S1
30 S2
40 goto 80
50 rem B IS FALSE
60 S3
70 S4
80 rem continue
,'S
'S.'
.",
-102-
II
0"
The BASIC multiple choice forces you to assign a program line number (in the
proper numerical sequence) which corresponds to the condition number of the
choice you wish to make. This may be difficult to do when you are designing a
program because you can run out' of line numbers. Allow 'enough numbers.
10 on I goto ( 20,40,60,90 )
20 S1
30 goto 110
40 S2
50 goto 110
60 S3
70 goto 110
90 S4
100 goto 110
110 rem ...continue
14.7 While
5 rem WHILE B DO
10 if not B then 50
20 $1
30 S2
40 goto 10
50 rem continue
14.8 Repeat-Until
10 for I J to K step M
203S1
305S2
40 next I
J is the initial value of I, K is the terminal value of I, and M is the non-zero
increment of I. Note that if the initial condition satisfies the terminal con-
dition, the loop will not be executed.
-103-
!..--
Altered Loops BASIC
Although any loop (While, Repeat-Until, Determinate) may be 'exit'ed (you can
GOTO just about anywhere in a BASIC program), we illustrate with a While.
10 if not B1 then 60
20 S1
30 if B2 then 60
40 S2
50 goto 10
60 rem continue
10 if not B1 then 60
20 31
30 if B2 then 10
40 S2
90 goto 10
60 rem continue
_10-4
BASIC BASIC Summary
Repeat-Until: B0 t
20 if not B then 10
-105-
.. . ..
Program Header BASIC
Please refer to the manual for the system you have. BASIC programs are usually
entered from a keyboard or recalled from auxiliary storage (tape or floppy
disk). The sequence to run a program is usually something like
RUN programname
,-Q
° *'V*. '
° ~
-106-
BASIC Examples
1i4.14 Examples
t07
V.°
V.
A-107-
* Examples BASIC
..' 14.14.2 Nearest Points Assume that the three coordinates of each point are
contained in DATA statements (some points, are provided below). It is usually
easier to use the editing capabilities of the BASIC interpreter by supplying
DATA statements than it is to correctly type in 30 numbers 'interactively.'
-108-
.
BASIC Examples
14.14I.3 Count the 's The BASIC language recognizes the character data type.
However, the language does not have a standard way to read a file; data are usu-
ally embedded in the program itself. To access files on a system running BASIC,
one must somehow execute calls to the operating system through 'extensions, to
the language. Since these calls vary widely from vendor to vendor, I omit this
example.
.'~_109-
15. ACKNOWLEDGMENTS
My ideas about programming, pedagogy, and people have been honed by continual
arguments with Mel Haas, Jim McKee, Dave Somer, Kevin Laurent, Sharon Good, and
* Fredd Thrasher. I thank them for the good influence they have had on me and on
this work.
Stefan Zilliacus, Stan Wilner, Steve Walter, Joyce Toler, Claude Rizzo,
Bill Mynatt, and Fran Fortin pointed to portions of this text which were
irrelevant, obscure, inconsistent, or wrong, and helped me to make this document
clearer and smaller.
Many other people have had an impact on this document. Although I have not men-
tioned them by name (the list would be longer than this texti), I wish them to
please accept my thanks.
.o.*
, -110-
16. REFERENCES
Atki8O Atkinson, Laurence, Pascal Programming, John Wiley & Sons (1980).
Boud7l Boudreau, Ace, "Peeling the Yellow Tomato," Journal of the Oriental
Ecdysiast Society, Vol 17, No. 3 (1971).
Coop82 Cooper, Doug and Michael Clancy, Oh! Pascall, W W Norton & Co (1982).
Jens74 Jensen, K and Wirth, W, Pascal User Manual and Report, Springer-Verlag
(1978).
Roth82 Roth, Peter N, THE STRUCTURES DEPARTMENT INTERACTIVE CDC PRIMER, Enclo-
sure to Itr Ser 82-175-2 of 20 Jan 82.
" Roth83 Roth, Peter N, THE PROCEDURE BOOK: A Guide to Engineers Arl Scientists
Using CDC Computers, David Taylor Naval Ship Research and Development
Center Technical Memorandum 83-(1703).2-63, June (1983).
.9-%
,-111"
Mw
' .4
3'-.-1 -
17. GLOSSARY
library a special kind of file in which one may store programs, sub-
. routines, functions, and the like. Libraries make it easy
for you to use code developed by others.
-112-
GLOSSARY
-113-
GLOSSARY
shell a program which provides the interactive interface between
man and modern computers.
* software the hard part of computing (as opposed to hardware, which is
the easy part).
-- store as a verb: to put data into the computer's memory. as a
noun: the place where data are kept. See also 'memory.'-
symbol a representation of a single thing; a symbol may be composed
of more than one character. For example, the Pascal symbols
used to group statements are 'begin' and 'end.'
system the computer program that allows other computer programs to
run. Also called 'executive' and 'monitor.'-
word a grouping of information on a machine which is convenient to
the manufacturer. On CDC equipment, a word is ten 6-bit
* .'.characters; on some DEC equipment, a word is four 8-bit
bytes.
-1114-
*M - I- , -l ;..
"-I
18. INDEX
-115-
symbolic 78
symbols 6, 58
symptom 43
target 4, 5, 30, 48, 51
termination 50, 61, 72
terminator 26, 51
-~ tools 2, 3, 37
translate 1, 4, 30
tree 8
* understandability 45
i~ UNIX 8, 45, 49, 75, 76
vector 7
-116
INITIAL DISTRIBUTION
- Copies Copies
1 DNA 2 NUSC
* 1 SPSS 1 WR
1 WU
3 CNR
1 ONR-100 1 NUSC
I ONR-200
1 ONR-400 1 United States Naval Academy
4 NRL I NAVWARCOL
1 2800
1 4000 1 NOSC
1 5000
1 6000 1 NAVSHIPYD BREM/LIB
117
0-
Copies Copies
1 University of Notre Dame 1 NKF Engineering Assoc/Vienna
Prof. Michael Katona Dr. M. Pakstys
1 INFOtek 20 173
Charles Maiorana 25 174
118
i,
Copies Code Name
1 18
1 1843 R. Van Eseltine
1 1843 M. Marquardt
1 1890 G. Gray
1 1890 W. Mynatt
20 1892 J. Strickland
1 1892 S. Wilner
1 1892 S. Good
1 1892 D. Sommer
1 1892 L. Minor
1 19
" 1 1936 J. Allender
1 27
1 28
1 6080 B. Pierce
11
119