Computer Science: FORTRAN Language Programming

260 109 8MB

English Pages [190] Year 1970

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Computer Science: FORTRAN Language Programming

Citation preview

cor

ENCE: N Language Programming STENBERG

3 4067 00893462 1

QA76.5. C6127141970 DENT GEN - -

27/08/84

SCIENCE: FORTRAN LANGUAGE

UNIVERSITY OF QUEENSLAND LIBRARY This book should be returned not later than the last date stamped below. Points/fines may be imposed for late return.

ALEXANDRA I. FORSYTHE, M. A. Department of Mathematics, G u m High School, Palo Alto

ELLIOTT 1. ORGANICK, Ph. D. Professor and Chairman, Department of Computer Science University of Houston

John Wiley & Sons, Inc.

THOMAS A. KEENAN, Ph.D. Director, Educational Information Network, EDUCOM

WARREN STENBERG, Ph.D. Associate Professor of Mathematics, University of Minnesota

New York . London

Sydney Toronto

To WALTER HOFFMAN Our friend and collaborator 1922-1969

Copyright

0 1970. by .John

Wilcy & Sons, In..

All rights reserved. No p a n of ihis hook may be reproduced by any means, nor lransn-littod, nor translated inUi ii machine l¥ingii;i without the written permission of the publisher. 1 0 9 8 7 6 5 4 3 2 1

Library of Congres Caliiloguc Card Number: 74-96044 SBN 471

26679

5

' n i c e ! in the United States of America

In both Computer Science: A Primer and Computer Science: A First Course, the flow-chart language is carefully introduced and built up feature by feature. Essentially computer-independent, the flow-chart language is the only language (except for English) used to express the many algorithms developed in those two "central" books. There remains, however, the final specialization t o a real programming language such as FORTRAN, Basic, or PL/I. This language supplement has been written to bridge t h e narrow gap between the flow-chart language and FORTRAN IV, dovetailing section by section with the first eight chapt,ers of the above-mentioned books. The FORTRAN I V discussed in this book has been selected with an eye t o translating algorithms originating in the central books. This fact has two consequences. First, the subset of FORTRAN I V used here is available to most computer installations and, second, not every FORTRAN IV feature will be found. However, for the benefit of interested students who complete this course, an appendix lists several reference manuals and textbooks that treat the entire FORTRAN I V language. Testing of certain programs has been assisted by a grant from the National Science Foundation to Stanford University. Finally, we wish t o gratefully acknowledge t h e help of all those who contributed to the development of this series of textbooks, including especially the School Mathematics Study Group. A.I.F. T.A.K. E.I.O. W.S.

PART I

BASIC CONCEPTS,

1

Chapter I

Algorithms and Computers, 1-1 Introduction,

3

3

1-2 The General Appearance of a FORTRAN Program, 1-3 Testing a Program, 8 1-4 ASecondExample, 11

5

Chapter 2

The FORTRAN Language, 2-1 2-2 2-3 2-4 2-5

12

FORTRAN Language Elements, Input-Output,

12

20

Assignment Statements,

30

Rounding, Chopping, and Other- Matters,

38

Input and Output of Alphanumeric Data,

44

* T h e section numbers t h a t are used here correspond with those in Computer Sd~nrt': A First Course.

viii

CONTENTS

Chapter 3 Additional FORTRAN Concepts,

51

3-1 Conditional Statements for Problem Solving, 3.2

58 61 3-4 Compound Conditions and Multiple Branching,

51

Programming the Euclidean Algorithm,

3-3 The Euclidean Algorithm Continued,

3-5 Evaluation of Logical Expressions, 3-6 Subscripted Variables, 75 3-7 Double Subscripts,

64

75

83

Chapter 4 Looping,

87

87 4-2 Illustrative Examples. 91 4-3 Table-Look-Up, 100 106 4.4 Nested DO Loops, 4-5 Review, 115 4^1 The DO Statement,

Chapter 5 Approximations.

118

5-1 Review of the Real Number Representation, 5-2 Double Precision, 121 5-3 Implications of Finite Word Length,

118

122

5-4 A Note on the Order of Calculation, 122 5-7 Approximating the Square Root and Sine Functions,

123

CONTENTS

PART II

NUMERICAL APPLICATIONS,

128

Chapter 6 Subprograms,

131

6-1 Subprograms, 131 6-2 Functions, 135 6-3 Functions with More than One Argument, 6-4 Procedures, 139 6-5 Extensions of Subprograms, 6-6 Symbol Manipulation, 147

135

143

Chapter 7 Some Mathematical Applications, 7-1 7-2 7-3 7-4

Roots of Equations, 151 Locating Maxima and Minima, Computing Areas, 161 Midpoint and Simpson's Rules,

151

157 163

Chapter 8 More Mathematical Applications,

166

8 - 1 Simultaneous Linear Equations, 166 8-2 Averages and Deviations. 169 8-3 Root-Mean-Square Deviation, 170 8-4 The Mathematics of Prediction, Appendix A WATFOR, Appendix B Index,

171

173

Other FORTRAN IV Literature,

177

176

ix

BASIC CONCEPTS

Chapter One

1-1 INTRODUCTION

FORTRAN-and other programming languages enable computers to read and to execute algorithmsthat are described by flow charts. Derived from the words FORmula TRANslator, FORTRAN uses English words and algebraic expressions, and was originally developed in 1956 by IBM. FORTRAN IV, the language described in this book, is a particular version, or dialect, of FORTRAN. Of course, FORTRAN IV will not remain popular forever. Eventually it will give way to a more recently developed language, possibly PL/l. Currently, however, FORTRAN IV is very widely used. Among the important characteristics of FORTRAN IV are the following. 1. The language can describe a great variety of algorithms. Although it is used principally for scientific and engineering computations, many other types of algorithms can be expressed satisfactorily in FORTRAN IV. 2. The rules (or grammar) of the language are precisely defined, unlike English, with the result that a FORTRAN IV algorithm means exactly the same thing to every person who reads it, if he knows the language. Thus FORTRAN IV can be used to communicate algorithms in correspondence and publications. 3. Many types of digital computers can be programmed t o accept algorithms written in FORTRAN IV because the language avoids any reference to special devices.

In this chapter we begin to describe FORTRAN IV as it is usually 3

4

ALGORITHMS AND COMPUTERS

implemented; hereafter, we simply call it FORTRAN, without the "IV.'' The steps of a FORTRAN program are called statements and correspond roughly to the boxes of a flow chart. Each statement is written so that, when typed or punched on a card, it can be transferred to the memory of a computer. There it can be scanned character by character and analyzed for its meaning. A program that analyzes these statementsis calleda compiler. - --. A typical FORTRAN compiler reads statements, analyzing them one a t a time, to form equivalent sequences of computer instructions. When executed, these instructions accomplish the intent of the corresponding FORTRAN statements. Target Programs and Source Programs

, :

, I

t

J

.,

/

'

1"

"

When a complete FORTRAN program has been read by the con~piler and processed as was described above, the result is a t a r g g p r q r a m . If there is room to store the target program in the computer as i t is developed, it can be executed immediately. When the target program is too large t o ' fit in memory along with the compiler, it can be stored temporarily on some auxiliary memory medium such as a magnetic drum, disc, tape, or even on punched cards. When it is stored on an auxiliary device, the target program can be recalled for execution a t a later time as suggested in Figure 1-1.Although we rarely want to read or study a target program, it is possible to have it printed for subsequent inspection. One might ask, "How does the compiler do its job?" Compiling is a flourchartable process and, while we will not pursue it here, this topic is studied in Computer Science: A First Course. Our purpose now is confined to learning t o express algorithms in FORTRAN.

SOURCE PROGRAM

hi

COMPUTER

w i t h compiler

i n memory)

On a u x i l i a r y medium

( t a p e , drum, or d i s c ) Printed for inspection

Figure 1-1 The compiling process.

1-2THE GENERAL APPEARANCE OF A FORTRAN PROGRAM

5

1-2 THE GENERAL APPEARANCE OF A FORTRAN PROGRAM The Fibonacci sequence, 0, 1, 1, 2, 3, 5, 8, 13, etc., is generated, starting with the numbers 0 and 1, by calculating each new member of the sequence as the sum of the two preceding members. In Figure 1-2 a flow chart to display the first term that exceeds 1000 is shown with the corresponding FORTRAN statements. First, notice the great similarity between the FORTRAN statements and what is written in the flowchart boxes. While there are differences in form, the ideas seem to be the same. We emphasize, however, that the FORTRAN statements on the right-hand side of Figure 1-2 do not make a complete or correct FORTRAN source program.

2

SUM'^-LATFST

t NEXT

1 3 SUM > 1000

NGXT+/AT£S SUM l.4TE.T-

31

\IF (SUM .GT. 1000)G@7@

f

I.

6

EXT= LA7EST LATEST= SUM

SUM

STOP

Flow chart

FORTRAN statements

1'igure 1-2 FORTRAN starements corresponding to How-chart boxes

6

ALGORITHMS AND COMPUTERS

FORTRAN statements are never connected by arrows as are the boxes of a flow chart. The ordering of FORTRAN statements one below the other implies that they are to be performed one after the other from top to bottom. A numeric label can be attached to any FORTRAN statement so that it can be identified from within the program. The purpose of the arrow from flow-chart box 4 leading back to box 2 is accomplished by the FORTRAN statement, G p T@ 2. Observe that there is no need for a FORTRANstatement to have a label unless it is referred to by another FORstatement. Thus, in Figure 1-2, only labels 2 and 6 are needed. "G@ T@"statements correspond to arrows in the flow chart. They change the normal sequence i f execution and are, therefore, equivalent to jumps or transfers in the instruction sequence. Figure 1-2 illustrates a number of characteristics of FORTRAN statements. In particular, in FORTRAN:

TRAN

1. Statements are separated by being written on separate lines. 2. Alphabetic characters are always in uppercase (capital) letters. 3. A statement may have a label. If so, the label precedes the statement, and is separated from it by a blank space. 4. A statement of the form "G@ TC) n" corresponds to a flow-chart arrow and changes the normal sequence of execution." 5. The assignment symbol is the equal sign ( = ) (alas, our preference would be a left-pointing arrow!), 6. The ability to use the symbol to mean is greater than seems to have been lost and replaced by .GT.. 7. Certain numbers, 6 and 11, in this instance, following the word WRITE have no apparent counterpart in the flow chart.

>

Figure 1-3 shows a FORTRAN program as it might appear on a coding sheet, before being punched on cards, one line of FORTRAN coding per card. Card Layout

A label or statement number, if used, is punched in card columns 1 through 5. The main part or body of the statement is placed in card columns 7 through 72. By common convention, card columns 73 through 80 are not considered a part of the program. In effect, the computer will ignore anything punched in the last eight columns of a program card. Comments can be added to identify a program and make it self-explanatory. A comment will be recognized by the compiler if we place the letter C in card column 1. Thus, the title, FIBPNACCI SEQUENCE will be treated as a comment rather than as a procedural statement because the letter C is punched in column 1 of this card. Extensive use of comments 'In-

FORTRAN letter "0" is slashed in this

text to distinguish it from zero,

1-2 THE GENERAL APPEARANCE OF A FORTRAN PROGRAM

7

Figure 1-3 A program on a FORTRAN coding sheet.

is a very inexpensive way t o help make a program understandable a t a later time. Column 6, although not used in Figure 1-3, has a significance that will be explained later. Language

The declaration END

is placed on the last line of the program to mark its end. This is characteristic of all FORTRAN programs. They are not complete without this terminal declaration, A line, labeled 11, in Figure 1-3, provides coded information defining the format, or layout, of the result t o be written by the WRITE statement. A -is required for each distinct arrangement of output on a printed or typed line.* A format is also required for each distinct arrangement of input data that is read from a punched card, sensed from key strokes at a typewriter console, or "read" by any other means. A detailed discussion of the codes that define formats is postponed to later sections. (If you are wondering about any special significance of the label, 11, of the FflRMAT line-don't bother. You will see later that the number is chosen arbitrarily and need only correspond with the second integer in the parentheses of the WRITE statement.) The first integer in the parentheses of the WRITE statement is a code *Somc versions of FORTRAN provide input and output statements that use a predefined format. The Appendix describes such statements as they occur in WATFOR, which is one of the popular versions of FORTRAN.

1-3 TESTING A PROGRAM

9

Unfortunately, for a program of any substantial complexity, it is rare t h a t we can be fully confident. it is entirely correct. Highly complex programs commonly undergo continued testing, revision, and correction even while they are in common use. This is the process called maintaining a program. Most of the programs you will write in this course can be thoroughly validated by a combination of processes. First, as you become adept a t flowcharting and using FORTRAN, you will begin t o discover sources of error by inspection. When you have finished writing a program, don't assume it (or its flow chart) is correct. Read it through again carefully, Have you considered the effect of unusual sets of data? As you proceed through this course, you will receive many warnings of what can go wrong. Be alert to these sources of trouble, and never assume that you have solved all of the difficulties the first time. As you learn FORTRAN-and even after you are experienced in its use-one recurring source of error will he forgetting or neglecting some detailed rule for a well-formed program. Fortunately, you need not be greatly concerned about this type of error. Most compilers have been designed to identify rule violations and to reject programs containing them, Compilers also identify the errors you make in the grammar of FORTRAN and issue warnings or "error messages." Although you have thoroughly inspected your program and the compiler has found no errors and issued no warnings, there still may be errors. Frequently they come to light when the program is run. For example, the program may produce no output, or it may compute indefinitely until stopped, or it may attempt to produce values beyond the range that can be represented in the computer. When any of these things happen-or if wrong answers are produced when everything else looks correct-we need techniques to help us locate the trouble. Two techniques are in common use. The first, called a memory (lump, is valuable to the professional programmer. This technique displays the memory contents (of the computer) at selected times during the execution of the program. The memory dump is helpful in finding the most obscure errors, but to profit from it requires a thorough knowledge of the computer being used and the time and effort that usually only a full-time professional is willing to give. Thesecond technique, and one you will find very helpful, is calledJ^Tf~zng Tracing is the process of"outputting values of certain variables a t critical points in the execution of the program. It is done by inserting WRITE statements a t selected points in a program being testid.These statements can be removed whenever they no longer serve a useful purpose, i.e., when the program is believed to be free of errors. An Example of a Program Trace

To illustrate tracing, we will consider the program of Figure 1-3, which calculates the first term of the Fibonacci sequence to exceed 1000. Here

10

ALGORITHMS AND COMPUTERS

Figure 1-5 Fibonacci sequence program with a tracing statement

one number is printed after repeated calculations. How can we best get information on the progress of the calculation before it finishes? In this program a critical point occurs at the end of the loop, just before the statement "G.0 T.0 2". SO,in Figure 1-5, we insert a WRITE statement at this point t o trace the repeated execution.

FORTRAN

STATEMENT

Figure 1-G Flow chart and FORTRAN statements for payroll

1-4 A SECOND EXAMPLE

11

1-4 A SECOND EXAMPLE

For another FORTRAN program, consider the task of preparing weekly wage statements for employees working on an hourly basis. Given the hourly rate of each employee and the number of hours worked in the week, a flow chart and the corresponding FORTRAN statements are shown in Figure 1-6. Several declarations need to be added to the FORTRAN statements that are shown before we have a complete program. Still, this example again demonstrates a close relationship between the language of the flow chart and FORTRAN. A complete FORTRAN program for this elementary payroll program is illustrated, without an explanation of the F ~ R M A Tdeclaration, in Figure 1-7. When you are reading the next chapter, you may find it interesting to look back a t this example.

Exercise 1-4

Write a FORTRAN program t o calculate and print the wages due workers based on hourly rates and time worked, the data being read from cards. Provide for payment at 1.5 limes the regular rate for hours worked that exceed 40 hours per week. Base y o u r program on Figure 1-7, and use the F0RMAT declarations shown there.

Chapter Two

2-1 FORTRAN LANGUAGE ELEMENTS

In this section we will consider in some detail the character set, or "alphabet," of FORTRAN and its use in constructing numerals (constants and labels), variables, --.- and names of .functions and operators. . The Character Set

The characters used in FORTRAN statements are limited to those shown in Table 2-1. Notice the absence of lowercase letters. Constructing Numerals (Numeric Constants) and Labels

Two fundamentally different schemes are used to represent numbers in the memory of a computer. The first represents integers, that is, the numbers reached from zero by

TABLE 2-1 The FORTRAN Character Set (a) Letters

(b) Digits (c) Special characters

A E C D q G J K L M N E f P S T U V W X 1 2 3 4 5 6 7

+ - * /

0 -

H Q Y 8

I R 2 9

2.1 FORTRAN LANGUAGE ELEMENTS

'J.

starting from an initial value of X = 0. In a FORTRAN statement. such numbers are called integers and are written without a decimal point, for -~ .......... example, as

!Â¥-,.

4, +14, -15,

,,

1..

13

,

1001

Within a computer, such numerals are represented in a special way so that arithmetic operations on integers result in integers. The second way to represent a number in the memory of a computer, called the floating-point -~.. . . . . . . . . representation, is routinely used t o approximate real numbers to a specific accuracy. In FORTRAN, a real number can be written as, for example, 4.0, +14., -.15, 10.01 Within a computer, such numbers are represented in a special way so that arithmetic operations on real numbers result in real numbers.' The way we write numerals as numerical constants in FORTRAN statements (i.e., with or without the decimal point) determines without, ambiguity which type of internal representation the number is to have during computation. We can represent a real number in FORTRAN in one more way. This is to use "E9'-notation. The code letter "E", as it is used in a numeral, is merely a convenient symbol whose meaning is "times ten to the power /; < . . .

A

-

8

is equivalent to 6

I F (LRGST .LT. A ) LRGST

=

A

These examples illustrate the fact that translation from the flow chart to FORTRAN may involve more than a transliteration of the flow-chart box. When writing conditional statements, be alert t o the possibility of using the complementary logical relation.* Notice the literal message enclosed in quotes in flow-chart box 9 of Figure 3-1. The quotes are used t o indicate that the enclosed message is to be printed literally. There is no way that the message itself may be changed in value as a result of carrying o u t the steps of the program. In FORTRAN an identifying message such as "is the largest"

does not appear directly as an item in the output list. (Constants, including literal messages, are not legal elements of an ordinary FORTRAN output list.) Instead, we insert the message in the FORMAT declaration. We have "Notice, for instance, the awkward coding that results when the relation in statement4 follows exactly the form used in the corresponding flowchart box. We would pet FUfi I M A N 'Â¥i

+

>

A

"

A

WIN +- WIN