SlideShare a Scribd company logo
Fortran for Scientists and Engineers 4th Edition
Stephen J. Chapman download
https://textbookfull.com/product/fortran-for-scientists-and-
engineers-4th-edition-stephen-j-chapman/
Download more ebook from https://textbookfull.com
We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!
Physics for Scientists and Engineers A Strategic
Approach 4th Edition Randall D. Knight
https://textbookfull.com/product/physics-for-scientists-and-
engineers-a-strategic-approach-4th-edition-randall-d-knight/
Physics for Scientists and Engineers with Modern
Physics 4th Edition Douglas C. Giancoli
https://textbookfull.com/product/physics-for-scientists-and-
engineers-with-modern-physics-4th-edition-douglas-c-giancoli/
Physics for scientists and engineers an interactive
approach 2nd Edition Peter J. Williams
https://textbookfull.com/product/physics-for-scientists-and-
engineers-an-interactive-approach-2nd-edition-peter-j-williams/
Statistics for Engineers and Scientists William Navidi
https://textbookfull.com/product/statistics-for-engineers-and-
scientists-william-navidi/
Essential MATLAB for Engineers and Scientists Hahn
https://textbookfull.com/product/essential-matlab-for-engineers-
and-scientists-hahn/
Essential MATLAB for engineers and scientists Hahn
https://textbookfull.com/product/essential-matlab-for-engineers-
and-scientists-hahn-2/
Essential MATLAB for engineers and scientists Hahn
https://textbookfull.com/product/essential-matlab-for-engineers-
and-scientists-hahn-3/
Probability statistics for engineers scientists Walpole
https://textbookfull.com/product/probability-statistics-for-
engineers-scientists-walpole/
Turbulence an introduction for scientists and engineers
Davidson
https://textbookfull.com/product/turbulence-an-introduction-for-
scientists-and-engineers-davidson/
Fortran for Scientists
and Engineers
Fourth Edition
Stephen J. Chapman
BAE Systems Australia
FORTRAN FOR SCIENTISTS AND ENGINEERS, FOURTH EDITION
MHID 0–07–338589–1
Library of Congress Cataloging-in-Publication Data
Chapman, Stephen J., author.
Fortran for scientists and engineers / Stephen J. Chapman, BAE Systems
Australia.
Fourth edition. | New York, NY : McGraw-Hill, a business unit of
The McGraw-Hill Companies, Inc., [2017] | Includes index.
LCCN 2016052439 | ISBN 9780073385891 (alk. paper) | ISBN
0073385891 (alk. paper)
LCSH: FORTRAN (Computer program language) | Science—Data
processing. | Engineering—Data processing.
LCC QA76.73.F25 C425 2017 | DDC 005.13/3—dc23 LC record available at
https://lccn.loc.gov/2016052439
Published by McGraw-Hill Education, 2 Penn Plaza, New York, NY 10121.
Copyright © 2018 by McGraw-Hill Education
Printed in the United States of America. Previous edition © 2008 and 2004
ISBN 978–0–07–338589–1
Preface xix
1 Introduction to Computers and The Fortran Language 1
1.1 The Computer 2
1.1.1. The CPU / 1.1.2. Memory / 1.1.3. Input and
Output Devices
1.2 Data Representation in a Computer 4
1.2.1. The Binary Number System / 1.2.2. Octal and
Hexadecimal Representations of Binary Numbers /
1.2.3. Types of Data Stored in Memory
1.3 Computer Languages 12
1.4 The History of the Fortran Language 13
1.5 The Evolution of Fortran 16
1.6 Summary 19
1.6.1. Exercises
2 Basic Elements of Fortran 22
2.1 Introduction 22
2.2 The Fortran Character Set 23
2.3 The Structure of a Fortran Statement 23
2.4 The Structure of a Fortran Program 24
2.4.1. The Declaration Section / 2.4.2. The Execution Section /
2.4.3. The Termination Section / 2.4.4. Program Style /
2.4.5. Compiling, Linking, and Executing the Fortran Program
2.5 Constants and Variables 28
2.5.1. Integer Constants and Variables / 2.5.2. Real Constants
and Variables / 2.5.3. Character Constants and Variables /
2.5.4. Default and Explicit Variable Typing / 2.5.5. Keeping
Constants Consistent in a Program
2.6 Assignment Statements and Arithmetic Calculations 36
2.6.1. Integer Arithmetic / 2.6.2. Real Arithmetic /
2.6.3. Hierarchy of Operations / 2.6.4. Mixed-Mode
Arithmetic / 2.6.5. Mixed-Mode Arithmetic and Exponentiation
C O N T E N T S
2.7 Intrinsic Functions 47
2.8 List-Directed Input and Output Statements 49
2.9 Initialization of Variables 55
2.10 The IMPLICIT NONE Statement 57
2.11 Program Examples 58
2.12 Debugging Fortran Programs 66
2.13 Summary 68
2.13.1. Summary of Good Programming Practice /
2.13.2. Summary of Fortran Statements / 2.13.3. Exercises
3 Program Design and Branching Structures 81
3.1 Introduction to Top-Down Design Techniques 82
3.2 Use of Pseudocode and Flowcharts 86
3.3 Logical Constants, Variables, and Operators 89
3.3.1. Logical Constants and Variables / 3.3.2. Assignment
Statements and Logical Calculations / 3.3.3. Relational
Operators / 3.3.4. Combinational Logic Operators /
3.3.5. Logical Values in Input and Output Statements /
3.3.6. The Significance of Logical Variables and Expressions
3.4 Control Constructs: Branches 94
3.4.1. The Block IF Construct / 3.4.2. The ELSE and ELSE IF
Clauses / 3.4.3. Examples Using Block IF Constructs /
3.4.4. Named Block IF Constructs / 3.4.5. Notes Concerning
the Use of Block IF Constructs / 3.4.6. The Logical IF
Statement / 3.4.7. The SELECT CASE Construct
3.5 More on Debugging Fortran Programs 118
3.6 Summary 119
3.6.1. Summary of Good Programming Practice /
3.6.2. Summary of Fortran Statements and Constructs /
3.6.3. Exercises
4 Loops and Character Manipulation 126
4.1 Control Constructs: Loops 126
4.1.1 The While Loop / 4.1.2 The DO WHILE Loop /
4.1.3 The Iterative or Counting Loop / 4.1.4 The CYCLE and
EXIT Statements / 4.1.5 Named Loops / 4.1.6 Nesting Loops
and Block IF Constructs
4.2 Character Assignments and Character Manipulations 154
4.2.1 Character Assignments / 4.2.2 Substring Specifications /
4.2.3 The Concatenation (//) Operator / 4.2.4 Relational
Operators with Character Data / 4.2.5 Character
Intrinsic Functions
4.3 Debugging Fortran Loops 168
4.4 Summary 169
4.4.1 Summary of Good Programming Practice /
4.4.2 Summary of Fortran Statements and Constructs /
4.4.3 Exercises
5 Basic I/O Concepts 180
5.1 Formats and Formatted WRITE Statements 180
5.2 Output Devices 182
5.2.1 Control Characters in Printer Output
5.3 Format Descriptors 184
5.3.1 Integer Output—The I Descriptor / 5.3.2 Real Output—
The F Descriptor / 5.3.3 Real Output—The E Descriptor /
5.3.4 True Scientific Notation—The ES Descriptor /
5.3.5 Logical Output—The L Descriptor / 5.3.6 Character
Output—The A Descriptor / 5.3.7 Horizontal Positioning—
The X and T Descriptor / 5.3.8 Repeating Groups of Format
Descriptors / 5.3.9 Changing Output Lines—The Slash (/)
Descriptor / 5.3.10 How Formats are Used During WRITEs
5.4 Formatted READ Statements 205
5.4.1 Integer Input—The I Descriptor / 5.4.2 Real Input—The F
Descriptor / 5.4.3 Logical Input—The L Descriptor /
5.4.4 Character Input—The A Descriptor / 5.4.5 Horizontal
Positioning—The X and T Descriptors / 5.4.6 Vertical
Positioning—The Slash (/) Descriptor / 5.4.7 How Formats
are Used During READs
5.5 An Introduction to Files and File Processing 211
5.5.1 The OPEN Statement / 5.5.2 The CLOSE Statement /
5.5.3 READs and WRITEs to Disk Files / 5.5.4 The IOSTAT= and
IOMSG= Clauses in the READ Statement / 5.5.5 File Positioning
5.6 Summary 232
5.6.1 Summary of Good Programming Practice / 5.6.2 Summary
of Fortran Statements and Structures / 5.6.3 Exercises
6 Introduction to Arrays 245
6.1 Declaring Arrays 246
6.2 Using Array Elements in Fortran Statements 247
6.2.1 Array Elements are Just Ordinary Variables /
6.2.2 Initialization of Array Elements / 6.2.3 Changing the
Subscript Range of an Array / 6.2.4 Out-of-Bounds Array
Subscripts / 6.2.5 The Use of Named Constants with
Array Declarations
6.3 Using Whole Arrays and Array Subsets in Fortran Statements 261
6.3.1 Whole Array Operations / 6.3.2 Array Subsets
6.4 Input and Output 265
6.4.1 Input and Output of Array Elements / 6.4.2 The Implied DO Loop /
6.4.3 Input and Output of Whole Arrays and Array Sections
6.5 Example Problems 271
6.6 When Should You Use an Array? 287
6.7 Summary 289
6.7.1 Summary of Good Programming Practice /
6.7.2 Summary of Fortran Statements and Constructs / 6.7.3 Exercises
7 Introduction to Procedures 297
7.1 Subroutines 299
7.1.1 Example Problem—Sorting / 7.1.2 The INTENT
Attribute / 7.1.3 Variable Passing in Fortran: The Pass-By-
Reference Scheme / 7.1.4 Passing Arrays to Subroutines /
7.1.5 Passing Character Variables to Subroutines /
7.1.6 Error Handling in Subroutines / 7.1.7 Examples
7.2 Sharing Data Using Modules 320
7.3 Module Procedures 328
7.3.1 Using Modules to Create Explicit Interfaces
7.4 Fortran Functions 331
7.4.1 Unintended Side Effects in Functions / 7.4.2 Using
Functions with Deliberate Side Effects
7.5 Passing Procedures as Arguments to Other Procedures 339
7.5.1 Passing User-Defined Functions as Arguments /
7.5.2 Passing Subroutines as Arguments
7.6 Summary 344
7.6.1 Summary of Good Programming Practice /
7.6.2 Summary of Fortran Statements and Structures / 7.6.3 Exercises
8 Additional Features of Arrays 360
8.1 2D or Rank 2 Arrays 360
8.1.1 Declaring Rank 2 Arrays / 8.1.2 Rank 2 Array
Storage / 8.1.3 Initializing Rank 2 Arrays / 8.1.4 Example
Problem / 8.1.5 Whole Array Operations and Array Subsets
8.2 Multidimensional or Rank n Arrays 372
8.3 Using Fortran Intrinsic Functions with Arrays 375
8.3.1 Elemental Intrinsic Functions / 8.3.2 Inquiry Intrinsic
Functions / 8.3.3 Transformational Intrinsic Functions
8.4 Masked Array Assignment: The WHERE Construct 378
8.4.1 The WHERE Construct / 8.4.2 The WHERE Statement
8.5 The FORALL Construct 381
8.5.1 The Form of the FORALL Construct / 8.5.2 The Significance
of the FORALL Construct / 8.5.3 The FORALL Statement
8.6 Allocatable Arrays 383
8.6.1 Fortran Allocatable Arrays / 8.6.2 Using Fortran
Allocatable Arrays in Assignment Statements
8.7 Summary 393
8.7.1 Summary of Good Programming Practice /
8.7.2 Summary of Fortran Statements and Constructs /
8.7.3 Exercises
9 Additional Features of Procedures 404
9.1 Passing Multidimensional Arrays to Subroutines and Functions 404
9.1.1 Explicit Shape Dummy Arrays / 9.1.2 Assumed-Shape
Dummy Arrays / 9.1.3 Assumed-Size Dummy Arrays
9.2 The SAVE Attribute and Statement 417
9.3 Allocatable Arrays in Procedures 421
9.4 Automatic Arrays in Procedures 422
9.4.1 Comparing Automatic Arrays and Allocatable
Arrays / 9.4.2 Example Program
9.5 Allocatable Arrays as Dummy Arguments in Procedures 430
9.5.1 Allocatable Dummy Arguments / 9.5.2 Allocatable
Functions
9.6 Pure and Elemental Procedures 434
9.6.1 Pure Procedures / 9.6.2 Elemental Procedures /
9.6.3 Impure Elemental Procedures
9.7 Internal Procedures 436
9.8 Submodules 438
9.9 Summary 446
9.9.1 Summary of Good Programming Practice /
9.9.2 Summary of Fortran Statements and Structures / 9.9.3 Exercises
10 More about Character Variables 457
 	10.1 Character Comparison Operations 458
10.1.1 The Relational Operators with Character Data /
10.1.2 The Lexical Functions LLT, LLE, LGT, and LGE
 	10.2 Intrinsic Character Functions 463
 	10.3 Passing Character Variables to Subroutines and Functions 465
 	10.4 Variable-Length Character Functions 471
 	10.5 Internal Files 473
 	10.6 Example Problems 474
 	10.7 Summary 479
10.7.1 Summary of Good Programming Practice /
10.7.2 Summary of Fortran Statements and Structures /
10.7.3 Exercises
11 Additional Intrinsic Data Types 485
 	11.1 Alternate Kinds of the REAL Data Type 485
11.1.1 Kinds of REAL Constants and Variables / 11.1.2 Determining
the KIND of a Variable / 11.1.3 Selecting Precision in a Processor-
Independent Manner / 11.1.4 Determining the KINDs of Data Types
on a Particular Processor / 11.1.5 Mixed-Mode Arithmetic /
11.1.6 Higher Precision Intrinsic Functions / 11.1.7 When to Use
High-Precision Real Values / 11.1.8 Solving Large Systems of
Simultaneous Linear Equations
 	11.2 Alternate Lengths of the INTEGER Data Type 509
 	11.3 Alternate Kinds of the CHARACTER Data Type 511
 	11.4 The COMPLEX Data Type 512
11.4.1 Complex Constants and Variables / 11.4.2 Initializing
Complex Variables / 11.4.3 Mixed-Mode Arithmetic /
11.4.4 Using Complex Numbers with Relational
Operators / 11.4.5 COMPLEX Intrinsic Functions
 	11.5 Summary 522
11.5.1 Summary of Good Programming Practice /
11.5.2 Summary of Fortran Statements and Structures /
11.5.3 Exercises
12 Derived Data Types 527
 	12.1 Introduction to Derived Data Types 527
 	12.2 Working with Derived Data Types 529
 	12.3 Input and Output of Derived Data Types 529
 	12.4 Declaring Derived Data Types in Modules 531
 	12.5 Returning Derived Types from Functions 540
 	12.6 Dynamic Allocation of Derived Data Types 544
 	12.7 Parameterized Derived Data Types 545
 	12.8 Type Extension 546
 	12.9 Type-Bound Procedures 548
12.10 The ASSOCIATE Construct 552
12.11 Summary 553
12.11.1 Summary of Good Programming Practice /
12.11.2 Summary of Fortran Statements and Structures /
12.11.3 Exercises
13 Advanced Features of Procedures and Modules 561
 	13.1 Scope and Scoping Units 562
 	13.2 Blocks 567
 	13.3 Recursive Procedures 568
 	13.4 Keyword Arguments and Optional Arguments 571
 	13.5 Procedure Interfaces and Interface Blocks 577
13.5.1 Creating Interface Blocks / 13.5.2 Notes on the
Use of Interface Blocks
 	13.6 Generic Procedures 581
13.6.1 User-Defined Generic Procedures / 13.6.2 Generic Interfaces
for Procedures in Modules / 13.6.3 Generic Bound Procedures
 	13.7 Extending Fortran with User-Defined Operators and Assignments 594
 	13.8 Bound Assignments and Operators 607
 	13.9 Restricting Access to the Contents of a Module 607
13.10 Advanced Options of the USE Statement 611
13.11 Intrinsic Modules 615
13.12 Access to Command Line Arguments and Environment Variables 615
13.12.1 Access to Command Line Arguments /
13.12.2 Retrieving Environment Variables
13.13 The VOLATILE Attribute and Statement 618
13.14 Summary 619
13.14.1 Summary of Good Programming Practice /
13.14.2 Summary of Fortran Statements and Structures /
13.14.3 Exercises
14 Advanced I/O Concepts 633
 	14.1 Additional Format Descriptors 633
14.1.1 Additional Forms of the E and ES Format Descriptors /
14.1.2 Engineering Notation—The EN Descriptor / 14.1.3 Double-
Precision Data—The D Descriptor / 14.1.4 The Generalized (G)
Format Descriptor / 14.1.5 The G0 Format Descriptor /
14.1.6 The Binary, Octal, and Hexadecimal (B, O, and Z) Descriptors /
14.1.7 The TAB Descriptors / 14.1.8 The Colon (:) Descriptor /
14.1.9 Scale Factors—The P Descriptor / 14.1.10 The SIGN
Descriptors / 14.1.11 Blank Interpretation: The BN and BZ
Descriptors / 14.1.12 Rounding Control: The RU, RD, RZ, RN, RC, and RP
Descriptors / 14.1.13 Decimal Specifier: The DC and DP Descriptors
 	14.2 Defaulting Values in List-Directed Input 642
 	14.3 Detailed Description of Fortran I/O Statements 644
14.3.1 The OPEN Statement / 14.3.2 The CLOSE Statement /
14.3.3 The INQUIRE Statement / 14.3.4 The READ Statement /
14.3.5 Alternate Form of the READ Statement / 14.3.6 The WRITE
Statement / 14.3.7 The PRINT Statement / 14.3.8 File Positioning
Statements / 14.3.9 The ENDFILE Statement / 14.3.10 The WAIT
Statement / 14.3.11 The FLUSH Statement
 	14.4 Namelist I/O 668
 	14.5 Unformatted Files 671
 	14.6 Direct Access Files 673
 	14.7 Stream Access Mode 678
 	14.8 Nondefault I/O for Derived Types 678
 	14.9 Asynchronous I/O 687
14.9.1. Performing Asynchronous I/O / 14.9.2. Problems with
Asynchronous I/O
14.10 Access to Processor-Specific I/O System Information 689
14.11 Summary 690
14.11.1 Summary of Good Programming Practice /
14.11.2 Summary of Fortran Statements and Structures /
14.11.3 Exercises
15 Pointers and Dynamic Data Structures 698
 	15.1 Pointers and Targets 699
15.1.1 Pointer Assignment Statements / 15.1.2 Pointer
Association Status
 	15.2 Using Pointers in Assignment Statements 705
 	15.3 Using Pointers with Arrays 707
 	15.4 Dynamic Memory Allocation with Pointers 709
 	15.5 Using Pointers as Components of Derived Data Types 712
 	15.6 Arrays of Pointers 725
 	15.7 Using Pointers in Procedures 727
15.7.1 Using the INTENT Attribute with Pointers /
15.7.2 Pointer-valued Functions
 	15.8 Procedure Pointers 733
 	15.9 Binary Tree Structures 736
15.9.1 The Significance of Binary Tree Structures /
15.9.2 Building a Binary Tree Structure
15.10 Summary 756
15.10.1 Summary of Good Programming Practice /
15.10.2 Summary of Fortran Statements and Structures /
15.10.3 Exercises
16 Object-Oriented Programming in Fortran 763
 	16.1 An Introduction to Object-Oriented Programming 764
16.1.1 Objects / 16.1.2 Messages / 16.1.3 Classes /
16.1.4 Class Hierarchy and Inheritance / 16.1.5 Object-
Oriented Programming
 	16.2 The Structure of a Fortran Class 769
 	16.3 The CLASS Keyword 770
 	16.4 Implementing Classes and Objects in Fortran 772
16.4.1 Declaring Fields (Instance Variables) / 16.4.2 Creating
Methods / 16.4.3 Creating (Instantiating) Objects from a Class
16.5 First Example: A timer Class 775
16.5.1 Implementing the timer Class / 16.5.2 Using
the timer Class / 16.5.3 Comments on the timer Class
 	16.6 Categories of Methods 780
 	16.7 Controlling Access to Class Members 789
 	16.8 Finalizers 790
 	16.9 Inheritance and Polymorphism 794
16.9.1 Superclasses and Subclasses / 16.9.2 Defining and Using
Subclasses / 16.9.3 The Relationship between Superclass
Objects and Subclass Objects / 16.9.4 Polymorphism /
16.9.5 The SELECT TYPE Construct
16.10 Preventing Methods from Being Overridden in Subclasses 809
16.11 Abstract Classes 809
16.12 Summary 831
16.12.1 Summary of Good Programming Practice /
16.12.2 Summary of Fortran Statements and Structures /
16.12.3 Exercises
17 Coarrays and Parallel Processing 837
 	17.1 Parallel Processing in Coarray Fortran 838
 	17.2 Creating a Simple Parallel Program 839
 	17.3 Coarrays 841
 	17.4 Synchronization between Images 843
 	17.5 Example: Sorting a Large Data Set 850
 	17.6 Allocatable Coarrays and Derived Data Types 856
 	17.7 Passing Coarrays to Procedures 857
 	17.8 Critical Sections 858
 	17.9 The Perils of parallel Programming 859
17.10 Summary 863
17.10.1 Summary of Good Programming Practice /
17.10.2 Summary of Fortran Statements and Structures /
17.10.3 Exercises
18 Redundant, Obsolescent, and Deleted Fortran Features 869
 	18.1 Pre-Fortran 90 Character Restrictions 870
 	18.2 Obsolescent Source Form 870
 	18.3 Redundant Data Type 871
 	18.4 Older, Obsolescent, and/or Undesirable Specification Statements 872
18.4.1 Pre-Fortran 90 Specification Statements / 18.4.2 The IMPLICIT
Statement / 18.4.3 The DIMENSION Statement / 18.4.4 The DATA
Statement / 18.4.5 The PARAMETER Statement
 	18.5 Sharing Memory Locations: COMMON and EQUIVALENCE 875
18.5.1 COMMON Blocks / 18.5.2 Initializing Data in
COMMON Blocks: The BLOCK DATA Subprogram /
18.5.3 The Unlabeled COMMON Statement /
18.5.4 The EQUIVALENCE Statement
 	18.6 Undesirable Subprogram Features 882
18.6.1 Alternate Subroutine Returns / 18.6.2 Alternate Entry
Points / 18.6.3 The Statement Function / 18.6.4 Passing
Intrinsic Functions as Arguments
 	18.7 Miscellaneous Execution Control Features 889
18.7.1 The PAUSE Statement / 18.7.2 Arguments Associated
with the STOP Statement / 18.7.3 The END Statement
 	18.8 Obsolete Branching and Looping Structures 892
18.8.1 The Arithmetic IF Statement / 18.8.2 The Unconditional
GO TO Statement / 18.8.3 The Computed GO TO Statement /
18.8.4 The Assigned GO TO Statement / 18.8.5 Older Forms
of DO Loops
 	18.9 Redundant Features of I/O Statements 896
18.10 Summary 897
18.10.1 Summary of Good Programming Practice /
18.10.2 Summary of Fortran Statements and Structures
Appendixes
A. The ASCII Character Set 903
B. Fortran/C Interoperability 904
B.1. Declaring Interoperable Data Types /
B.2. Declaring Interoperable Procedures / B.3. Sample Programs—
Fortran Calling C / B.4. Sample Programs—C Calling Fortran
C. Fortran Intrinsic Pro­
cedures 914
C.1. Classes of Intrinsic Procedures / C.2. Alphabetical List of Intrinsic
Procedures / C.3. Mathematical and Type Conversion Intrinsic
Procedures / C.4. Kind and Numeric Processor Intrinsic
Functions / C.5. System Environment Procedures / C.6. Bit Intrinsic
Procedures / C.7. Character Intrinsic Functions / C.8. Array and
Pointer Intrinsic Functions / C.9. Miscellaneous Inquiry Functions /
C.10. Miscellaneous Procedures / C.11. Coarray Functions
D. Order of Statements in a Fortran Program 961
E. Glossary 963
F. Answers to Quizzes 984
		 Index 1002
		 Summary of Selected Fortran Statements and Structures 1022
P R E F A C E
The first edition of this book was conceived as a result of my experience in writing
and maintaining large Fortran programs in both the defense and geophysical fields.
During my time in industry, it became obvious that the strategies and techniques
­
required to write large, maintainable Fortran programs were quite different from what
new ­
engineers were learning in their Fortran programming classes at school. The
­
incredible cost of maintaining and modifying large programs once they are placed into
service absolutely demands that they be written to be easily understood and modified
by ­
people other than their original programmers. My goal for this book is to teach
­
simultaneously both the fundamentals of the Fortran language and a programming
style that results in good, maintainable programs. In addition, it is intended to serve as
a reference for graduates working in industry.
It is quite difficult to teach undergraduates the importance of taking extra effort
during the early stages of the program design process in order to make their programs
more maintainable. Class programming assignments must by their very nature be sim-
ple enough for one person to complete in a short period of time, and they do not have
to be maintained for years. Because the projects are simple, a student can often “wing
it” and still produce working code. A student can take a course, perform all of the pro-
gramming assignments, pass all of the tests, and still not learn the habits that are really
needed when working on large projects in industry.
From the very beginning, this book teaches Fortran in a style suitable for use on
large projects. It emphasizes the importance of going through a detailed design pro-
cess before any code is written, using a top-down design technique to break the pro-
gram up into logical portions that can be implemented separately. It stresses the use of
procedures to implement those individual portions, and the importance of unit testing
before the procedures are combined into a finished product. Finally, it emphasizes the
importance of exhaustively testing the finished program with many different input data
sets before it is released for use.
In addition, this book teaches Fortran as it is actually encountered by engineers and
scientists working in industry and in laboratories. One fact of life is common in all pro-
gramming environments: Large amounts of old legacy code that have to be maintained.
The legacy code at a particular site may have been originally written in Fortran IV (or
an even earlier version!), and it may use programming constructs that are no longer
common today. For example, such code may use arithmetic IF statements, or computed
or assigned GO TO statements. Chapter 18 is devoted to those older features of the lan-
guage that are no longer commonly used, but that are encountered in legacy code.
xx Preface
The chapter emphasizes that these features should never be used in a new program, but
also prepares the student to handle them when he or she encounters them.
CHANGES IN THIS EDITION
This edition builds directly on the success of Fortran 95/2003 for Scientists and Engi-
neers, 3/e. It preserves the structure of the previous edition, while weaving the new Fortran
2008 material (and limited material from the proposed Fortran 2015 standard) throughout
the text. It is amazing, but Fortran started life around 1954, and it is still evolving.
Most of the additions in Fortran 2008 are logical extensions of existing capabili-
ties of Fortran 2003, and they are integrated into the text in the proper chapters. How-
ever, the use of parallel processing and Coarray Fortran is completely new, and Chapter
17 has been added to cover that material.
The vast majority of Fortran courses are limited to one-quarter or one semester,
and the student is expected to pick up both the basics of the Fortran language and the
concept of how to program. Such a course would cover Chapters 1 through 7 of this
text, plus selected topics in Chapters 8 and 9 if there is time. This provides a good
foundation for students to build on in their own time as they use the language in
­practical projects.
Advanced students and practicing scientists and engineers will need the material on
COMPLEX numbers, derived data types, and pointers found in Chapters 11 through 15.
Practicing scientists and engineers will almost certainly need the material on obsolete,
redundant, and deleted Fortran features found in Chapter 18. These materials are rarely
taught in the classroom, but they are included here to make the book a useful reference
text when the language is actually used to solve real-world problems.
FEATURES OF THIS BOOK
Many features of this book are designed to emphasize the proper way to write reliable
Fortran programs. These features should serve a student well as he or she is first learn-
ing Fortran, and should also be useful to the practitioner on the job. They include:
1. Emphasis on Modern Fortran.
		 The book consistently teaches the best current practice in all of its examples.
Many modern Fortran 2008 features duplicate and supersede older features of
the Fortran language. In those cases, the proper usage of the modern language
is presented. Examples of older usage are largely relegated to Chapter 18,
where their old/undesirable nature is emphasized. Examples of modern Fortran
features that supersede older features are the use of modules to share data
­instead of COMMON blocks, the use of DO . . . END DO loops instead of DO . . .
­
CONTINUE loops, the use of internal procedures instead of statement functions,
and the use of CASE constructs instead of computed GOTOs.
Preface xxi
2. Emphasis on Strong Typing.
		The IMPLICIT NONE statement is used consistently throughout the book to
force the explicit typing of every variable used in every program, and to catch
common typographical errors at compilation time. In conjunction with the ex-
plicit declaration of every variable in a program, the book emphasizes the im-
portance of creating a data dictionary that describes the purpose of each
variable in a program unit.
3. Emphasis on Top-Down Design Methodology.
		 The book introduces a top-down design methodology in Chapter 3, and then
uses it consistently throughout the rest of the book. This methodology encour-
ages a student to think about the proper design of a program before beginning
to code. It emphasizes the importance of clearly defining the problem to be
solved and the required inputs and outputs before any other work is begun.
Once the problem is properly defined, it teaches the student to employ stepwise
refinement to break the task down into successively smaller subtasks, and to
implement the subtasks as separate subroutines or functions. Finally, it teaches
the importance of testing at all stages of the process, both unit testing of the
component routines and exhaustive testing of the final product. Several exam-
ples are given of programs that work properly for some data sets, and then fail
for others.
		 The formal design process taught by the book may be summarized as
follows:
∙ Clearly state the problem that you are trying to solve.
∙ Define the inputs required by the program and the outputs to be produced by
the program.
∙ Describe the algorithm that you intend to implement in the program. This
step involves top-down design and stepwise decomposition, using pseudo-
code or flow charts.
∙ Turn the algorithm into Fortran statements.
∙ Test the Fortran program. This step includes unit testing of specific subpro-
grams, and also exhaustive testing of the final program with many different
data sets.
4. Emphasis on Procedures.
		 The book emphasizes the use of subroutines and functions to logically decom-
pose tasks into smaller subtasks. It teaches the advantages of procedures for data
hiding. It also emphasizes the importance of unit testing procedures before they
are combined into the final program. In addition, the book teaches about the
common mistakes made with procedures, and how to avoid them (argument type
mismatches, array length mismatches, etc.). It emphasizes the advantages asso-
ciated with explicit interfaces to procedures, which allow the Fortran compiler
to catch most common programming errors at compilation time.
5. Emphasis on Portability and Standard Fortran.
		 The book stresses the importance of writing portable Fortran code, so that a
program can easily be moved from one type of computer to another one.
It teaches students to use only standard Fortran statements in their programs, so
that they will be as portable as possible. In addition, it teaches the use of
­
features such as the SELECTED_REAL_KIND function to avoid precision and kind
differences when moving from computer to computer.
		 The book also teaches students to isolate machine-dependent code (such as
code that calls machine-dependent system libraries) into a few specific proce-
dures, so that only those procedures will have to be rewritten when a program
is ported between computers.
6. Good Programming Practice Boxes.
		 These boxes highlight good programming practices when they are introduced
for the convenience of the student. In addition, the good programming practices
introduced in a chapter are summarized at the end of the chapter. An example
Good Programming Practice Box is shown below:
Good Programming Practice
Always indent the body of an IF structure by two or more spaces to improve the
readability of the code.
7. Programming Pitfalls Boxes
		 These boxes highlight common errors so that they can be avoided. An exam-
ple Programming Pitfalls Box is shown below:
Programming Pitfalls
Beware of integer arithmetic. Integer division often gives unexpected results.
8. Emphasis on Pointers and Dynamic Data Structures.
		 Chapter 15 contains a detailed discussion of Fortran pointers, including pos-
sible problems resulting from the incorrect use of pointers such as memory
leaks and pointers to deallocated memory. Examples of dynamic data struc-
tures in the chapter include linked lists and binary trees.
		 Chapter 16 contains a discussion of Fortran objects and object-oriented pro-
gramming, including the use of dynamic pointers to achieve polymorphic behavior.
9. Use of Sidebars.
		 A number of sidebars are scattered throughout the book. These sidebars pro-
vide additional information of potential interest to the student. Some sidebars
are historical in nature. For example, one sidebar in Chapter 1 describes the
IBM Model 704, the first computer to ever run Fortran. Other sidebars
xxii Preface
­
reinforce lessons from the main text. For example, Chapter 9 contains a side-
bar reviewing and summarizing the many different types of arrays found in
modern Fortran.
10. Completeness.
		 Finally, the book endeavors to be a complete reference to the modern Fortran
language, so that a practitioner can locate any required information quickly.
Special attention has been paid to the index to make features easy to find. A
special effort has also been made to cover such obscure and little understood
features as passing procedure names by reference, and defaulting values in
list-directed input statements.
PEDAGOGICAL FEATURES
The book includes several features designed to aid student comprehension. Each
chapter begins with a list of the objectives that should be achieved in that chapter.
A total of 27 quizzes appear scattered throughout the chapters, with answers to all
questions included in Appendix F. These quizzes can serve as a useful self-test of
comprehension. In addition, there are approximately 360 end-of-chapter exercises.
Answers to selected exercises are available at the book’s Web site, and of course an-
swers to all exercises are included in the Instructor’s Manual. Good programming
practices are highlighted in all chapters with special Good Programming Practice
boxes, and common errors are highlighted in ­
Programming Pitfalls boxes. End-of-
chapter materials include Summaries of Good Programming Practice and Summaries
of Fortran Statements and Structures. Finally, a detailed description of every Fortran
intrinsic procedure is included in Appendix C, and an extensive Glossary is included
in Appendix E.
The book is accompanied by an Instructor’s Manual, containing the solutions to
all end-of-chapter exercises. Instructors can also download the solutions in the
­
Instructor’s Manual from the book’s Web site. The source code for all examples in
the book, plus other supplemental materials, can be downloaded by anyone from the
book’s ­
Web site.
A NOTE ABOUT FORTRAN COMPILERS
Two Fortran compilers were used during the preparation of this book: the Intel Visual
Fortran Compiler Version 16.0 and the GNU G95 Fortran compiler. Both compilers
provide essentially complete implementations of Fortran 2008, with only a very few
minor items not yet implemented. They are also both looking to the future, implement-
ing features from the proposed Fortran 2015 standard.
I highly recommend both compilers to potential users. The great advantage of
­
Intel Fortran is the very nice integrated debugging environment, and the great disad-
vantage is cost. The G95 compiler is free, but it is somewhat harder to debug.
Preface xxiii
A FINAL NOTE TO THE USER
No matter how hard I try to proofread a document like this book, it is inevitable that
some typographical errors will slip through and appear in print. If you should spot any
such errors, please drop me a note via the publisher, and I will do my best to get them
eliminated from subsequent printings and editions. Thank you very much for your help
in this matter.
I will maintain a complete list of errata and corrections at the book’s World Wide Web
site, which is www.mhhe.com/chapman4e. Please check that site for any updates and/or
corrections.
ACKNOWLEDGMENTS
I would like to thank Raghu Srinivasan and the team at McGraw-Hill Education for
making this revision possible. In addition, I would like to thank my wife Rosa and
daughter Devorah for their support during the revision process. (In previous editions, I
had thanked our other seven children as well, but they have all now flown the coop!)
Stephen J. Chapman
Melbourne, Victoria, Australia
August 7, 2016
xxiv Preface
1
1
Introduction to Computers
and the Fortran Language
OBJECTIVES
∙ Know the basic components of a computer.
∙ Understand binary, octal, and hexadecimal numbers.
∙ Learn about the history of the Fortran language.
The computer was probably the most important invention of the twentieth century.
It affects our lives profoundly in very many ways. When we go to the grocery store,
the scanners that check out our groceries are run by computers. Our bank balances
are maintained by computers, and the automatic teller machines and credit and debit
cards that allow us to make banking transactions at any time of the day or night are
run by more computers. Computers control our telephone and electric power sys-
tems, run our microwave ovens and other appliances, and control the engines in our
cars. Almost any business in the developed world would collapse overnight if it were
suddenly deprived of its computers. Considering their importance in our lives, it is
almost impossible to believe that the first electronic computers were invented just
about 75 years ago.
Just what is this device that has had such an impact on all of our lives? A ­computer
is a special type of machine that stores information, and can perform mathematical
calculations on that information at speeds much faster than human beings can think. A
program, which is stored in the computer’s memory, tells the computer what sequence
of calculations is required, and which information to perform the calculations on. Most
computers are very flexible. For example, the computer on which I write these words
can also balance my checkbook, if I just execute a different program on it.
Computers can store huge amounts of information, and with proper programming,
they can make that information instantly available when it is needed. For example, a
bank’s computer can hold the complete list of all the deposits and debits made by
­
every one of its customers. On a larger scale, credit companies use their computers to
hold the credit histories of every person in the United States—literally billions of
2 chapter 1:   Introduction to Computers and the Fortran Language
1
pieces of information. When requested, they can search through those billions of
pieces of information to recover the credit records of any single person, and present
those records to the user in a matter of seconds.
It is important to realize that computers do not think as humans understand
­thinking. They merely follow the steps contained in their programs. When a computer
appears to be doing something clever, it is because a clever person has written the pro-
gram that it is executing. That is where we humans come into the act. It is our collec-
tive creativity that allows the computer to perform its seeming miracles. This book
will help teach you how to write programs of your own, so that the computer will do
what you want it to do.
1.1
THE COMPUTER
A block diagram of a typical computer is shown in Figure 1-1. The major components
of the computer are the central processing unit (CPU), main memory, secondary
memory, and input and output devices. These components are described in the para-
graphs below.
FIGURE 1-1
A block diagram of a typical computer.
Main
memory
Secondary
memory
Internal
memory
(registers)
Control
unit
Memory
cache
Arithmetic
logic unit
Output
devices
Central processing unit
Introduction to Computers and the Fortran Language 3
1
1.1.1 The CPU
The central processing unit is the heart of any computer. It is divided into a control unit,
an arithmetic logic unit (ALU), and internal memory. The control unit within the CPU
controls all of the other parts of the computer, while the ALU performs the actual math-
ematical calculations. The internal memory within a CPU consists of a series of mem-
ory registers used for the temporary storage of intermediate results during calculations,
plus a memory cache to temporarily store data that will be needed in the near future.
The control unit of the CPU interprets the instructions of the computer program. It
also fetches data values from main memory (or the memory cache) and stores them in
the memory registers, and sends data values from memory registers to output devices
or main memory. For example, if a program says to multiply two numbers together and
save the result, the control unit will fetch the two numbers from main memory and
store them in registers. Then, it will present the numbers in the registers to the ALU
along with directions to multiply them and store the results in another register. Finally,
after the ALU multiplies the numbers, the control unit will take the result from the
destination register and store it back into the memory cache. (Other parts of the CPU
copy the data from the memory cache to main memory in slower time.)
Modern CPUs have become dramatically faster by incorporating multiple ALUs
running in parallel, allowing more operations to be performed in a given amount of
time. They also incorporate larger memory caches on the CPU chip, allowing data to
be fetched and saved very rapidly.
1.1.2 Memory
The memory of a computer is divided into three major types of memory: cache mem-
ory, main or primary memory, and secondary memory. Cache memory is memory
stored on the CPU chip itself. This memory can be accessed very rapidly, allowing
calculations to proceed at very high speed. The control unit looks ahead in the program
to see what data will be needed, and pre-fetches it from main memory into the memory
cache so that it can be used with minimal delay. The control unit also copies the results
of calculations from the cache back to main memory when they are no ­
longer needed.
Main memory usually consists of separate semiconductor chips connected to the
CPU by conductors called a memory bus. It is very fast, and relatively inexpensive com-
pared to the memory on the CPU itself. Data that is stored in main memory can be fetched
for use in a few nanoseconds or less (sometimes much less) on a modern computer. Be-
cause it is so fast and cheap, main memory is used to temporarily store the program
currently being executed by the computer, as well as the data that the program requires.
Main memory is not used for the permanent storage of programs or data. Most
main memory is volatile, meaning that it is erased whenever the computer’s power is
turned off. Besides, main memory is relatively expensive, so we only buy enough to
hold all of the programs actually being executed at any given time.
Secondary memory consists of devices that are slower and cheaper than main mem-
ory. They can store much more information for much less money than main ­
memory can.
In addition, most secondary memory devices are nonvolatile, meaning that they retain
4 chapter 1:   Introduction to Computers and the Fortran Language
1
the programs and data stored in them whenever the computer’s power is turned off. Typ-
ical secondary memory devices are hard disks, solid-state drives (SSD), USB memory
sticks, and DVDs. Secondary storage devices are normally used to store programs and
data that are not needed at the moment, but that may be needed some time in the future.
1.1.3 Input and Output Devices
Data is entered into a computer through an input device, and is output through an out-
put device. The most common input devices on a modern computer are the keyboard
and the mouse. We can type programs or data into a computer with a keyboard. Other
types of input devices found on some computers include touchscreens, scanners,
­
microphones, and cameras.
Output devices permit us to use the data stored in a computer. The most common
output devices on today’s computers are displays and printers. Other types of output
devices include plotters and speakers.
1.2
DATA REPRESENTATION IN A COMPUTER
Computer memories are composed of billions of individual switches, each of which can
be ON or OFF, but not at a state in between. Each switch represents one binary digit (also
called a bit); the ON state is interpreted as a binary 1, and the OFF state is interpreted as
a binary 0. Taken by itself, a single switch can only represent the numbers 0 and 1. Since
we obviously need to work with numbers other than 0 and 1, a number of bits are grouped
together to represent each number used in a computer. When several bits are grouped
­
together, they can be used to represent numbers in the binary (base 2) number system.
The smallest common grouping of bits is called a byte. A byte is a group of 8 bits
that are used together to represent a binary number. The byte is the fundamental unit
used to measure the capacity of a computer’s memory. For example, the personal com-
puter on which I am writing these words has a main memory of 24 gigabytes
(24,000,000,000 bytes) and a secondary memory (disk drive) with a storage of
2 ­
terabytes (2,000,000,000,000 bytes).
The next larger grouping of bits in a computer is called a word. A word consists
of 2, 4, or more consecutive bytes that are used to represent a single number in mem-
ory. The size of a word varies from computer to computer, so words are not a particu-
larly good way to judge the size of computer memories. Modern CPUs tend to use
words with lengths of either 32 or 64 bits.
1.2.1 The Binary Number System
In the familiar base 10 number system, the smallest (rightmost) digit of a number is the
ones place (100
). The next digit is in the tens place (101
), and the next one is in the
hundreds place (102
), etc. Thus, the number 12210
is really (1 × 102
) + (2 × 101
) +
(2 × 100
). Each digit is worth a power of 10 more than the digit to the right of it in the
base 10 system (see Figure 1-2a).
Introduction to Computers and the Fortran Language 5
1
Similarly, in the binary number system, the smallest (rightmost) digit is the ones
place (20
). The next digit is in the twos place (21
), and the next one is in the fours place
(22
), etc. Each digit is worth a power of 2 more than the digit to the right of it in the
base 2 system. For example, the binary number 1012
is really (1 × 22
) + (0 × 21
) +
(1 × 20
) = 5, and the binary number 1112
= 7 (see Figure 1-2b).
Note that three binary digits can be used to represent eight possible values: 0 (= 0002
)
to 7 (= 1112
). In general, if n bits are grouped together to form a binary number, then they
can represent 2n
possible values. Thus, a group of 8 bits (1 byte) can represent 256 possi-
ble values, a group of 16 bits (2 bytes) can be used to represent 65,536 possible values,
and a group of 32 bits (4 bytes) can be used to represent 4,294,967,296 possible values.
In a typical implementation, half of all possible values are reserved for represent-
ing negative numbers, and half of the values are reserved for representing zero plus the
positive numbers. Thus, a group of 8 bits (1 byte) is usually used to represent numbers
between −128 and +127, including 0, and a group of 16 bits (2 bytes) is usually used
to represent numbers between −32,768 and +32,767, including 0.1
FIGURE 1-2
(a) The base 10 number 122 is really (1 × 102
) + (2 × 101
) +
(2 × 100
). (b) Similarly, the base 2 number 1012
is really
(1 × 22
) + (0 × 21
) + (1 × 20
).
100’s place
10’s place
1’s place
(a)
1 2 2
4’s place
2’s place
1’s place
(b)
1 0 12 = 510
1
The most common scheme for representing negative numbers in a computer’s memory is the so-called
two’s complement representation, which is described in the sidebar.
TWO’S COMPLEMENT ARITHMETIC
The most common way to represent negative numbers in the binary number system is
the two’s complement representation. What is two’s complement, and what is so spe-
cial about it? Let’s find out.
The Two’s Complement Representation of Negative Numbers
In the two’s complement representation, the leftmost bit of a number is the sign bit.
If that bit is 0, then the number is positive; if it is 1, then the number is negative. To
change a positive number into the corresponding negative number in the two’s comple-
ment system, we perform two steps:
1. Complement the number (change all 1s to 0 and all 0s to 1).
2. Add 1 to the complemented number.
6 chapter 1:   Introduction to Computers and the Fortran Language
1 Let’s illustrate the process using simple 8-bit integers. As we already know, the
8-bit binary representation of the number 3 would be 00000011. The two’s comple-
ment representation of the number −3 would be found as follows:
1. Complement the positive number: 11111100
2. Add 1 to the complemented number: 11111100 + 1 = 11111101
Exactly the same process is used to convert negative numbers back to positive num-
bers. To convert the number −3 (11111101) back to a positive 3, we would:
1. Complement the negative number: 00000010
2. Add 1 to the complemented number: 00000010 + 1 = 00000011
Two’s Complement Arithmetic
Now we know how to represent numbers in two’s complement representation, and to
convert between positive and two’s complement negative numbers. The special
­
advantage of two’s complement arithmetic is that positive and negative numbers may
be added together according to the rules of ordinary addition without regard to the
sign, and the resulting answer will be correct, including the proper sign. ­
Because of
this fact, a computer may add any two integers together without checking to see what
the signs of the two integers are. This simplifies the design of computer circuits.
Let’s do a few examples to illustrate this point.
1. Add 3 + 4 in two’s complement arithmetic.
3 00000011
+4 00000100
7 00000111
2. Add (−3) + (−4) in two’s complement arithmetic.
3 11111101
+−4 11111100
−7 111111001
In a case like this, we ignore the extra ninth bit resulting from the sum, and the
answer is 11111001. The two’s complement of 11111001 is 00000111 or 7, so the
­
result of the addition was −7!
3. Add 3 + (−4) in two’s complement arithmetic.
−3 00000011
+−4 11111100
−1 11111111
The answer is 11111111. The two’s complement of 11111111 is 00000001 or 1, so the
result of the addition was −1.
With two’s complement numbers, binary addition comes up with the correct ­
answer
regardless of whether the numbers being added are both positive, both negative, or mixed.
Introduction to Computers and the Fortran Language 7
1
1.2.2 Octal and Hexadecimal Representations of Binary Numbers
Computers work in the binary number system, but people think in the decimal number
system. Fortunately, we can program the computer to accept inputs and give its outputs
in the decimal system, converting them internally to binary form for processing. Most
of the time, the fact that computers work with binary numbers is irrelevant to the
­programmer.
However, there are some cases in which a scientist or engineer has to work directly
with the binary representations coded into the computer. For example, individual bits
or groups of bits within a word might contain status information about the operation of
some machine. If so, the programmer will have to consider the individual bits of the
word, and work in the binary number system.
A scientist or engineer who has to work in the binary number system immediately
faces the problem that binary numbers are unwieldy. For example, a number like
110010
in the decimal system is 0100010011002
in the binary system. It is easy to get
lost working with such a number! To avoid this problem, we customarily break binary
numbers down into groups of 3 or 4 bits, and represent those bits by a single base
8 (octal) or base 16 (hexadecimal) number.
To understand this idea, note that a group of 3 bits can represent any number
­
between 0 (= 0002
) and 7 (= 1112
). These are the numbers found in an octal or base 8
arithmetic system. An octal number system has seven digits: 0 through 7. We can
break a binary number up into groups of 3 bits, and substitute the appropriate octal
digit for each group. Let’s use the number 0100010011002
as an example. Breaking
the number into groups of three digits yields 010∣001∣001∣1002
. If each group of 3 bits
is replaced by the appropriate octal number, the value can be written as 21148
. The
octal number represents exactly the same pattern of bits as the binary number, but it is
more compact.
Similarly, a group of 4 bits can represent any number between 0 (= 00002
) and
15 (= 11112
). These are the numbers found in a hexadecimal or base 16 arithmetic
system. A hexadecimal number system has 16 digits: 0 through 9 and A through F.
Since the hexadecimal system needs 16 digits, we use digits 0 through 9 for the first
10 of them, and then letters A through F for the remaining 6. Thus, 916
= 910
, A16
=
1010
, B16
= 1110
, and so forth. We can break a binary number up into groups of 4
bits, and substitute the appropriate hexadecimal digit for each group. Let’s use the
number 0100010011002
again as an example. Breaking the number into groups of
four digits yields 0100∣0100∣11002
. If each group of 4 bits is replaced by the appro-
priate hexadecimal number, the value can be written as 44C16
. The hexadecimal
number represents exactly the same pattern of bits as the binary number, but more
compactly.
Some computer vendors prefer to use octal numbers to represent bit patterns,
while other computer vendors prefer to use hexadecimal numbers to represent bit pat-
terns. Both representations are equivalent, in that they represent the pattern of bits in a
compact form. A Fortran language program can input or output numbers in any of the
four formats (decimal, binary, octal, or hexadecimal). Table 1-1 lists the decimal,
­
binary, octal, and hexadecimal forms of the numbers 0 to 15.
8 chapter 1:   Introduction to Computers and the Fortran Language
1
1.2.3 Types of Data Stored in Memory
Three common types of data are stored in a computer’s memory: character data,
­
integer data, and real data (numbers with a decimal point). Each type of data has
different characteristics, and takes up a different amount of memory in the
computer.
Character Data
The character data type consists of characters and symbols. A typical system for
representing character data in a non-Oriental language must include the following symbols:
1. The 26 uppercase letters A through Z
2. The 26 lowercase letters a through z
3. The 10 digits 0 through 9
4. Miscellaneous common symbols, such as ,(), {}, [], !, ~, @, #, $,
%, ^, , and *.
5. Any special letters or symbols required by the language, such as à, ç, ë, and £.
Since the total number of characters and symbols required to write Western
­
languages is less than 256, it is customary to use 1 byte of memory to store each
character. Therefore, 10,000 characters would occupy 10,000 bytes of the comput-
er’s memory.
The particular bit values corresponding to each letter or symbol may vary from
computer to computer, depending upon the coding system used for the characters. The
most important coding system is ASCII, which stands for the American Standard Code
TABLE 1-1
Table of decimal, binary, octal, and
hexadecimal numbers
Decimal Binary Octal Hexadecimal
0 0000 0 0
1 0001 1 1
2 0010 2 2
3 0011 3 3
4 0100 4 4
5 0101 5 5
6 0110 6 6
7 0111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
Introduction to Computers and the Fortran Language 9
1
for Information Interchange (ANSI X3.4 1986, or ISO/IEC 646:1991). The ASCII
coding system defines the values to associate with the first 128 of the 256 possible
values that can be stored in a 1-byte character. The 8-bit codes corresponding to each
letter and number in the ­
ASCII coding system are given in Appendix A.
The second 128 characters that can be stored in a 1-byte character are not defined
by the ASCII character set, and they used to be defined differently depending on the
language used in a particular country or region. These definitions are a part of the ISO
8859 standard series, and they are sometimes referred to as “code pages.” For exam-
ple, the ISO 8859-1 (Latin 1) character set is the version used in Western European
countries. There are similar code pages available for Eastern European languages,
­
Arabic, Greek, Hebrew, and so forth. Unfortunately, the use of different code pages
made the output of programs and the contents of files appear different in different
countries. As a result, these code pages are falling out of favor, and being replaced by
the Unicode system described below.
Some Oriental languages such as Chinese and Japanese contain more than 256
characters (in fact, about 4000 characters are needed to represent each of these
languages). To accommodate these languages and all of the other languages in the
world, a coding system called Unicode2
has been developed. In the Unicode cod-
ing system, each character is stored in 2 bytes of memory, so the Unicode system
supports 65,536 possible different characters. The first 128 Unicode characters are
identical to the ­
ASCII character set, and other blocks of characters are devoted to
various languages such as Chinese, Japanese, Hebrew, Arabic, and Hindi. When
the Unicode coding system is used, character data can be represented in any
­language.
Integer Data
The integer data type consists of the positive integers, the negative integers, and
zero. The amount of memory devoted to storing an integer will vary from computer to
computer, but will usually be 1, 2, 4, or 8 bytes. Four-byte integers are the most com-
mon type in modern computers.
Since a finite number of bits are used to store each value, only integers that fall
within a certain range can be represented on a computer. Usually, the smallest number
that can be stored in an n-bit integer is
Smallest integer value = −2n−1
(1-1)
and the largest number that can be stored in an n-bit integer is
Largest integer value = 2n−1
− 1 (1-2)
For a 4-byte integer, the smallest and largest possible values are −2,147,483,648 and
2,147,483,647, respectively. Attempts to use an integer larger than the largest possible
2
Also referred to by the corresponding standard number, ISO/IEC 10646:2014.
10 chapter 1:   Introduction to Computers and the Fortran Language
1
value or smaller than the smallest (most negative) possible value result in an error
called an overflow condition.3
Real Data
The integer data type has two fundamental limitations:
1. It is not possible to represent numbers with fractional parts (0.25, 1.5, 3.14159,
etc.) as integer data.
2. It is not possible to represent very large positive integers or very small negative
integers, because there are not enough bits available to represent the value. The
largest and smallest possible integers that can be stored in a given memory loca-
tion will be given by Equations (1-1) and (1-2).
To get around these limitations, computers include a real or floating-point data
type.
The real data type stores numbers in a type of scientific notation. We all know
that very large or very small numbers can be most conveniently written in scientific
notation. For example, the speed of light in a vacuum is about 299,800,000 m/s. This
number is easier to work with in scientific notation: 2.998 × 108
m/s. The two parts
of a number expressed in scientific notation are called the mantissa and the
­
exponent. The mantissa of the number above is 2.998, and the exponent (in the base
10 system) is 8.
The real numbers in a computer are similar to the scientific notation above, except
that a computer works in the base 2 system instead of the base 10 system. Real num-
bers usually occupy 32 bits (4 bytes) of computer memory, divided into two compo-
nents: a 24-bit mantissa and an 8-bit exponent (Figure 1-3).4
The mantissa contains a
number between −1.0 and 1.0, and the exponent contains the power of 2 required to
scale the number to its actual value.
Real numbers are characterized by two quantities: precision and range.
­
Precision is the number of significant digits that can be preserved in a number, and
range is the difference between the largest and smallest numbers that can be
­
represented. The precision of a real number depends on the number of bits in its
mantissa, while the range of the number depends on the number of bits in its expo-
nent. A 24-bit mantissa can represent approximately ±223
numbers, or about seven
significant decimal digits, so the precision of real numbers is about seven significant
digits. An 8-bit ­
exponent can represent multipliers between 2−128
and 2127
, so the
range of real numbers is from about 10−38
to 1038
. Note that the real data type can
represent numbers much larger or much smaller than integers can, but only with
seven significant digits of precision.
3
When an overflow condition occurs, some processors will abort the program causing the overflow condi-
tion. Other processors will “wrap around” from the most positive integer to the most negative integer with-
out giving the user a warning that anything has happened. This behavior varies for different types of
computers.
4
This discussion is based on the IEEE Standard 754 for floating-point numbers, which is representative of
most modern computers.
Introduction to Computers and the Fortran Language 11
1
When a value with more than seven digits of precision is stored in a real vari-
able, only the most significant 7 bits of the number will be preserved. The ­
remaining
information will be lost forever. For example, if the value 12,345,678.9 is stored in
a real variable on a PC, it will be rounded off to 12,345,680.0. This difference
­
between the original value and the number stored in the computer is known as
­
round-off error.
You will use the real data type in many places throughout this book and in your
programs after you finish this course. It is quite useful, but you must always remember
the limitations associated with round-off error, or your programs might give you an
unpleasant surprise. For example, if your program must be able to distinguish between
the numbers 1,000,000.0 and 1,000,000.1, then you cannot use the standard real data
type.5
It simply does not have enough precision to tell the difference between these two
numbers!
FIGURE 1-3
This floating-point number includes a 24-bit
mantissa and an 8-bit exponent.
Value = mantissa × 2exponent
10 20 30
Mantissa Exponent
mmmmmmmmmmmmmmmmmmmmmmmmeeeeeeee
5
We will learn how to use high-precision floating-point numbers in Chapter 11.
Programming Pitfalls
Always remember the precision and range of the data types that you are working
with. Failure to do so can result in subtle programming errors that are very hard
to find.
Quiz 1-1
This quiz provides a quick check to see if you have understood the concepts intro-
duced in Section 1.2. If you have trouble with the quiz, reread the section, ask
your instructor, or discuss the material with a fellow student. The answers to this
quiz are found in the back of the book.
1. Express the following decimal numbers as their binary equivalents:
(a) 2710
(b) 1110
(c) 3510
(d) 12710
(continued)
Random documents with unrelated
content Scribd suggests to you:
Greensleeves was my delight!
Greensleeves was my heart of gold!
And who but my Lady Greensleeves!
Greensleeves now farewell! adieu!
God I pray to prosper thee!
For I am still thy lover true:
Come once again and love me!
Greensleeves was all my joy!
Greensleeves was my delight!
Greensleeves was my heart of gold!
And who but my Lady Greensleeves!
MY TRUE LOVE
SIR PHILIP SIDNEY
My true love hath my heart, and I have his,
By just exchange one for another given:
I hold his dear, and mine he cannot miss;
There never was a better bargain driven:
My true love hath my heart, and I have his.
His heart in me keeps him and me in one,
My heart in him his thoughts and senses guides:
He loves my heart, for once it was his own,
I cherish his because in me it bides:
My true love hath my heart, and I have his.
DIRGE
JOHN WEBSTER
Call for the robin-redbreast and the wren,
Since o'er shady groves they hover,
And with leaves and flowers do cover
The friendless bodies of unburied men.
Call unto his funeral dole
The ant, the field-mouse, and the mole,
To rear him hillocks that shall keep him warm,
And (when gay tombs are robb'd) sustain no harm;
But keep the wolf far thence, that's foe to men,
For with his nails he'll dig them up again.
THE SHROUDING
Hark! now everything is still,
The screech-owl and the whistler shrill,
Call upon our dame aloud,
And bid her quickly don her shroud!
Much you had of land and rent;
Your length in clay's now competent:
A long war disturb'd your mind;
Here your perfect peace is sign'd.
Of what is 't fools make such vain keeping?
Sin their conception, their birth weeping,
Their life a general mist of error,
Their death a hideous storm of terror.
Strew your hair with powders sweet,
Don clean linen, bathe your feet,
And—the foul fiend more to check—
A crucifix let bless your neck;
'Tis now full tide 'tween night and day;
End your groan and come away.
CONTENT
THOMAS DEKKER
Art thou poor, yet hast thou golden slumbers?
O sweet content!
Art thou rich, yet is thy mind perplex'd?
O punishment!
Dost thou laugh to see how fools are vex'd
To add to golden numbers, golden numbers?
O sweet content! O sweet, O sweet content!
Work apace, apace, apace, apace;
Honest labour bears a lovely face;
Then hey nonny nonny, hey nonny nonny!
Canst drink the waters of the crispèd spring?
O sweet content!
Swimm'st thou in wealth, yet sink'st in thine own tears?
O punishment!
Then he that patiently want's burden bears
No burden bears, but is a king, a king!
O sweet content! O sweet, O sweet content!
Work apace, apace, apace, apace;
Honest labour bears a lovely face;
Then hey nonny nonny, hey nonny nonny!
TROLL THE BOWL
Cold's the wind, and wet's the rain,
Saint Hugh be our good speed!
Ill is the weather that bringeth no gain,
Nor helps good hearts in need.
Troll the bowl, the jolly nut-brown bowl,
And here, kind mate, to thee!
Let's sing a dirge for Saint Hugh's soul,
And down it merrily.
Down-a-down, hey, down-a-down,
Hey derry derry down-a-down.
Ho! well done, to let me come,
Ring compass, gentle joy!
Troll the bowl, the nut-brown bowl,
And here, kind mate, to thee!
Let's sing a dirge for Saint Hugh's soul,
And down it merrily.
Cold's the wind, and wet's the rain,
Saint Hugh be our good speed!
Ill is the weather that bringeth no gain,
Nor helps good hearts in need.
SIR PATRICK SPENS
ANONYMOUS
The king sits in Dunfermline toun,
Drinking the blude-red wine;
'Oh whare will I get a gude sailor,
To sail this ship o' mine?'
Then up and spake an eldern knight
Sat at the king's right knee;
'Sir Patrick Spens is the best sailor
That ever sail'd the sea.'
The king has written a braid letter,
And seal'd it wi' his hand,
And sent it to Sir Patrick Spens
Was walking on the strand.
'To Noroway, to Noroway,
To Noroway o'er the faem;
The king's daughter to Noroway,
'Tis thou maun tak' her hame.'
The first line that Sir Patrick read,
A loud laugh laughed he;
The neist line that Sir Patrick read,
The tear blinded his ee.
'O wha is this has done this deed,
And tauld the king o' me,
To send us out at this time o' the year,
To sail upon the sea?'
'Be 't wind or weet, be't hail or sleet,
Our ship maun sail the faem;
The king's daughter to Noroway,
'Tis we maun tak' her hame.'
They hoisted their sails on Monenday morn,
Wi' a' the speed they may;
And they hae landed in Noroway
Upon a Wodensday.
They hadna been a week, a week,
In Noroway but twae,
When that the lords o' Noroway
Began aloud to say—
'Ye Scotisman spend a' our king's gowd,
And a' our queenis fee.'
'Ye lee, ye lee, ye leears loud,
Sae loud's I hear ye lee!
'For I brought as much o' the white monie
As gane my men and me,
And a half-fou o' the gude red gowd,
Out owre the sea with me.
'Mak' ready, mak' ready, my merry men a',
Our gude ship sails the morn.'
'O say na sae, my master dear,
I fear a deadlie storm.
'I saw the new moon late yestreen,
Wi' the auld moon in her arm;
And if we gang to sea, master,
I fear we'll come to harm!'
They hadna sail'd a league, a league,
A league but barely three,
When the lift grew dark, and the wind blew loud
And gurly grew the sea.
The ankers brak, and the tap-masts lap,
It was sic a deadlie storm;
And the waves cam' owre the broken ship,
Till a' her sides were torn.
'O whare will I get a gude sailor
Will tak' the helm in hand,
Till I get up to the tall tap-mast,
To see if I can spy land.'
'O here am I, a sailor gude,
To tak' the helm in hand,
Till ye get up to the tall tap-mast,
But I fear ye'll ne'er spy land.'
He hadna gane a step, a step,
A step but barely ane,
When a bout flew out o' the gude ship's side,
And the saut sea it cam' in.
'Gae, fetch a web o' the silken claith,
Anither o' the twine,
And wap them into our gude ship's side,
And letna the sea come in.'
They fetch'd a wab o' the silken claith,
Anither o' the twine,
And they wapp'd them into the gude ship's side,
But aye the sea cam' in.
O laith, laith were our Scots lords' sons
To weet their coal-black shoon,
But lang ere a' the play was play'd,
They wat their hats abune.
And mony was the feather-bed
That fluttered on the faem,
And mony was the gude lord's son
That never mair cam' hame.
O lang, lang may the ladies sit,
Wi' their fans into their hand,
Before they see Sir Patrick Spens
Come sailing to the strand.
And lang, lang may the maidens sit,
Wi' the gowd kaims in their hair,
A' waiting for their ain dear loves,
For them they'll see nae mair.
Half owre, half owre to Aberdour
'Tis fifty fathom deep,
And there lies gude Sir Patrick Spens
Wi' the Scots lords at his feet.
THE BEGGAR'S DAUGHTER OF
BEDNALL-GREEN
PART I
It was a blind beggar, had long lost his sight,
He had a fair daughter of beauty most bright;
And many a gallant brave suitor had she,
For none was so comely as pretty Bessee.
And though she was of favour most faire,
Yet seeing she was but a poor beggar's heyre,
Of ancyent housekeepers despised was she,
Whose sons came as suitors to pretty Bessee.
Wherefore in great sorrow fair Bessy did say,
Good father, and mother, let me go away
To seek out my fortune, whatever it be,
This suite then they granted to pretty Bessee.
Then Bessy, that was of beauty so bright,
All cladd in grey russet, and late in the night
From father and mother alone parted she,
Who sighed and sobbed for pretty Bessee.
She went till she came to Stratford-le-Bow;
Then knew she not whither, nor which way to go:
With tears she lamented her hard destinìe,
So sad and so heavy was pretty Bessee.
She kept on her journey until it was day,
And went unto Rumford along the high way;
Where at the Queen's arms entertained was she:
So fair and well-favoured was pretty Bessee.
She had not been there a month to an end,
But master and mistress and all was her friend:
And every brave gallant, that once did her see,
Was straightway enamour'd of pretty Bessee.
Great gifts they did send her of silver and gold,
And in their songs daily her love was extolled;
Her beauty was blazed in every degree;
So fair and so comely was pretty Bessee.
The young men of Rumford in her had their joy
She showed herself courteous, and modestly coy;
And at her commandment still would they be;
So fair and so comely was pretty Bessee.
Four suitors at once unto her did go;
They craved her favour, but still she said no;
I would not wish gentles to marry with me;
Yet ever they honoured pretty Bessee.
The first of them was a gallant young knight,
And he came unto her disguised in the night:
The second a gentleman of good degree,
Who wooed and sued for pretty Bessee.
A merchant of London, whose wealth was not small,
He was the third suitor, and proper withal:
Her master's own son the fourth man must be,
Who swore he would die for pretty Bessee.
And, if thou wilt marry with me, quoth the knight,
I'll make thee a lady with joy and delight;
My heart's so enthralled by thy beautie,
That soon I shall die for pretty Bessee.
The gentleman said, Come, marry with me,
As fine as a lady my Bessy shall be:
My life is distressed: O hear me, quoth he;
And grant me thy love, my pretty Bessee.
Let me be thy husband, the merchant did say,
Thou shalt live in London both gallant and gay;
My ships shall bring home rich jewels for thee,
And I will for ever love pretty Bessee.
Then Bessy she sighed, and thus she did say,
My father and mother I mean to obey;
First get their good will, and be faithful to me,
And then you shall marry your pretty Bessee.
To every one this answer she made,
Wherefore unto her they joyfully said,
This thing to fulfil we all do agree;
But where dwells thy father, my pretty Bessee?
My father, she said, is soon to be seen:
The silly blind beggar of Bednall-green,
That daily sits begging for charitìe,
He is the good father of pretty Bessee.
His marks and his tokens are known very well;
He always is led with a dog and a bell:
A silly old man, God knoweth, is he,
Yet he is the father of pretty Bessee.
Nay then, quoth the merchant, thou art not for me.
Nor, quoth the innholder, my wife thou shalt be:
I loth, said the gentle, a beggar's degree,
And therefore adieu, my pretty Bessee.
Why then, quoth the knight, hap better or worse,
I weigh not true love by the weight of the purse,
And beauty is beauty in every degree;
Then welcome unto me, my pretty Bessee.
With thee to thy father forthwith I will go.
Nay soft, quoth his kinsmen, it must not be so;
A poor beggar's daughter no lady shall be,
Then take thy adieu of pretty Bessee.
But soon after this, by break of the day
The knight had from Rumford stole Bessy away.
The young men of Rumford, as thick as might be,
Rode after to fetch again pretty Bessee.
As swift as the wind to ryde they were seen,
Until they came near unto Bednall-green;
And as the knight lighted most courteouslìe,
They all fought against him for pretty Bessee.
But rescue came speedily over the plain,
Or else the young knight for his love had been slain.
This fray being ended, then straightway he see
His kinsmen come railing at pretty Bessee.
Then spake the blind beggar, Although I be poor,
Yet rail not against my child at my own door:
Though she be not decked in velvet and pearl,
Yet will I drop angels with you for my girl.
And then, if my gold may better her birth,
And equal the gold that you lay on the earth,
Then neither rail nor grudge you to see
The blind beggar's daughter a lady to be.
But first you shall promise, and have it well known,
The gold that you drop shall all be your own.
With that they replied, Contented be we.
Then here's, quoth the beggar, for pretty Bessee.
With that an angel he cast on the ground,
And dropped in angels full three thousand pound;
And oftentimes it was proved most plain,
For the gentlemen's one the beggar dropt twain:
So that the place, wherein they did sit,
With gold it was covered every whit.
The gentlemen then having dropt all their store,
Said, Now, beggar, hold, for we have no more,
Thou hast fulfilled thy promise aright.
Then marry, quoth he, my girl to this knight;
And here, added he, I will now throw you down
A hundred pounds more to buy her a gown.
The gentlemen all, that this treasure had seen,
Admired the beggar of Bednall-green:
And all those, that were her suitors before,
Their flesh for very anger they tore.
Thus was fair Bessy matched to the knight,
And then made a lady in others' despite:
A fairer lady there never was seen,
Than the blind beggar's daughter of Bednall-green.
But of their sumptuous marriage and feast,
What brave lords and knights thither were prest,
The second fitt shall set forth to your sight
With marvellous pleasure and wished delight.
PART II
Of a blind beggar's daughter most bright,
That late was betrothed unto a young knight;
All the discourse thereof you did see:
But now comes the wedding of pretty Bessee.
Within a gorgeous palace most brave,
Adorned with all the cost they could have,
This wedding was kept most sumptuouslìe,
And all for the credit of pretty Bessee.
All kind of dainties and delicates sweet
Were bought for the banquet, as it was most meet;
Partridge, and plover, and venison most free,
Against the brave wedding of pretty Bessee.
This marriage through England was spread by report,
So that a great number thereto did resort
Of nobles and gentles in every degree;
And all for the fame of pretty Bessee.
To church then went this gallant young knight;
His bride followed after, an angel most bright,
With troops of ladies, the like ne'er was seen,
As went with sweet Bessy of Bednall-green.
This marriage being solemnized then,
With musick performed by the skilfullest men,
The nobles and gentles sat down at that tide,
Each one admiring the beautiful bride.
Now, after the sumptuous dinner was done,
To talk, and to reason a number begun:
They talked of the blind beggar's daughter most bright,
And what with his daughter he gave to the knight.
Then spake the nobles, 'Much marvel have we,
This jolly blind beggar we cannot here see.'
My lords, quoth the bride, my father's so base,
He is loth with his presence these states to disgrace.
'The praise of a woman in question to bring
Before her own face, were a flattering thing,
But we think thy father's baseness,' quoth they,
'Might by thy beauty be clean put away.'
They had no sooner these pleasant words spoke,
But in comes the beggar clad in a silk cloak;
A fair velvet cap, and a feather had he,
And now a musician forsooth he would be.
He had a dainty lute under his arm,
He touched the strings, which made such a charm,
Says, Please you to hear any musick of me,
I'll sing you a song of pretty Bessee.
With that his lute he twanged straightway,
And thereon began most sweetly to play;
And after that lessons were played two or three,
He strain'd out this song most delicatelìe.
'A poor beggar's daughter did dwell on a green,
Who for her fairness might well be a queen:
A blithe bonny lass, and a dainty was she,
And many one called her pretty Bessee.
'Her father he had no goods, nor no land,
But begged for a penny all day with his hand;
And yet to her marriage he gave thousands three,
And still he hath somewhat for pretty Bessee.
'And if any one here her birth do disdain,
Her father is ready, with might and with main,
To prove she is come of noble degree:
Therefore never flout at pretty Bessee.'
With that the lords and the company round
With hearty laughter were ready to swound;
At last said the lords, Full well we may see,
The bride and the beggar's beholden to thee.
On this the bride all blushing did rise,
The pearly drops standing within her fair eyes,
O pardon my father, grave nobles, quoth she,
That through blind affection thus doteth on me.
If this be thy father, the nobles did say,
Well may he be proud of this happy day;
Yet by his countenance well may we see,
His birth and his fortune did never agree:
'And therefore, blind man, we pray thee bewray
(And look that the truth thou to us do say)
Thy birth and thy parentage, what it may be;
For the love that thou bearest to pretty Bessee.'
'Then give me leave, nobles and gentles, each one,
One song more to sing, and then I have done;
And if that it may not win good report,
Then do not give me a groat for my sport.
'Sir Simon de Montfort my subject shall be;
Once chief of all the great barons was he,
Yet fortune so cruel this lord did abase,
Now lost and forgotten are he and his race.
'When the barons in arms did king Henry oppose,
Sir Simon de Montfort their leader they chose;
A leader of courage undaunted was he,
And oft-times he made their enemies flee.
'At length in the battle on Evesham plain,
The barons were routed, and Montfort was slain;
Most fatal that battle did prove unto thee,
Though thou wast not born then, my pretty Bessee!
'Along with the nobles, that fell at that tide,
His eldest son Henry, who fought by his side,
Was felled by a blow he received in the fight;
A blow that deprived him for ever of sight.
'Among the dead bodies all lifeless he lay,
Till evening drew on of the following day,
When by a young lady discovered was he;
And this was thy mother, my pretty Bessee!
'A baron's fair daughter stept forth in the night
To search for her father, who fell in the fight,
And seeing young Montfort, where gasping he lay,
Was moved with pity, and brought him away.
'In secret she nurst him, and swaged his pain,
While he through the realm was believed to be slain:
At length his fair bride she consented to be,
And made him glad father of pretty Bessee.
'And now, lest our foes our lives should betray,
We clothed ourselves in beggars' array;
Her jewels she sold, and hither came we:
All our comfort and care was our pretty Bessee.
'And here have we lived in fortune's despite,
Though poor, yet contented with humble delight:
Full forty winters thus have I been
A silly blind beggar of Bednall-green.
'And here, noble lords, is ended the song
Of one, that once to your own rank did belong:
And thus have you learned a secret from me,
That ne'er had been known, but for pretty Bessee.'
Now when the fair company every one,
Had heard the strange tale in the song he had shown,
They all were amazed, as well they might be,
Both at the blind beggar, and pretty Bessee.
With that the fair bride they all did embrace,
Saying, Sure thou art come of an honourable race
Thy father likewise is of noble degree,
And thou art well worthy a lady to be.
Thus was the feast ended with joy and delight,
A bridegroom most happy then was the young knight,
In joy and felicitie long lived he,
All with his fair lady, the pretty Bessee.
THE BABES IN THE WOOD
Now ponder well, you parents dear,
These words, which I shall write;
A doleful story you shall hear,
In time brought forth to light.
A gentleman of good account
In Norfolk dwelt of late,
Who did in honour far surmount
Most men of his estate.
Sore sick he was, and like to die,
No help his life could save;
His wife by him as sick did lie,
And both possest one grave.
No love between these two was lost,
Each was to other kind,
In love they liv'd, in love they died,
And left two babes behind:
The one a fine and pretty boy,
Not passing three yeares old;
The other a girl more young than he,
And fram'd in beauty's mould.
The father left his little son,
As plainly doth appeare,
When he to perfect age should come,
Three hundred pounds a yeare.
And to his little daughter Jane
Five hundred pounds in gold,
To be paid down on marriage-day,
Which might not be controll'd:
But if the children came to die,
Ere they to age should come,
Their uncle should possesse their wealth;
For so the will did run.
Now, brother, said the dying man,
Look to my children dear;
Be good unto my boy and girl,
No friends else have they here:
To God and you I recommend
My children dear this daye;
But little while be sure we have
Within this world to stay.
You must be father and mother both,
And uncle all in one;
God knows what will become of them,
When I am dead and gone.
With that bespake their mother dear,
O brother kind, quoth she,
You are the man must bring our babes
To wealth or miserie:
And if you keep them carefully,
Then God will you reward;
But if you otherwise should deal,
God will your deeds regard.
With lips as cold as any stone,
They kist their children small:
God bless you both, my children dear;
With that the tears did fall.
These speeches then their brother spake
To this sick couple there,
The keeping of your little ones,
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
textbookfull.com

More Related Content

PDF
Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
(eBook PDF) Java How to Program, Late Objects Global Edition 11th Edition
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
Clean Code. An Agile Guide to Software Craft Kameron H.
PDF
Core Java Volume I Fundamentals 12th Horstmann Cay
PDF
epdf.pub_real-time-systems-design-and-analysis.pdf
PDF
Core Java Vol Iiadvanced Features 12th Edition Cay S Horstmann
Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman
Clean Code. An Agile Guide to Software Craft Kameron H.
(eBook PDF) Java How to Program, Late Objects Global Edition 11th Edition
Clean Code. An Agile Guide to Software Craft Kameron H.
Clean Code. An Agile Guide to Software Craft Kameron H.
Core Java Volume I Fundamentals 12th Horstmann Cay
epdf.pub_real-time-systems-design-and-analysis.pdf
Core Java Vol Iiadvanced Features 12th Edition Cay S Horstmann

Similar to Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman (20)

PDF
Test bank for Big Java: Early Objects 6th Edition by Horstmann
PDF
Test bank for Big Java: Early Objects 6th Edition by Horstmann
PDF
Embedded systems are specialized computing systems designed to perform specif...
PDF
Introdução Ao Teste De Software 2nd Edition Marcio Delamaro Mario Jino
PDF
Functional Programming in C#: How to write better C# code 1st Edition Enrico ...
PDF
A Practical Introduction To Data Structures And Algorithms Analysis, Java Edi...
PDF
Mechanising_Programs_in_IsabelleHOL
PDF
Open source programming
PDF
Practice Standard for Scheduling Third Edition Project Management Institute
DOC
Java Programming by P.Rizwan Ahmed,MUCollege, Ambur
PPT
Network
PDF
Table ofcontents
PDF
[FREE PDF sample] Object Oriented Programming and Java Second Edition Danny P...
PDF
java TM rmi The Remote Method Invocation Guide 1st Edition Esmond Pitt
PDF
Coding guideline
DOCX
Abstract An overview of the whole report and what it is about..docx
PDF
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
PDF
java TM rmi The Remote Method Invocation Guide 1st Edition Esmond Pitt
PPT
Bd siit i pv4-ipv6
PDF
Programming the Network with Perl 1st Edition Paul Barry
Test bank for Big Java: Early Objects 6th Edition by Horstmann
Test bank for Big Java: Early Objects 6th Edition by Horstmann
Embedded systems are specialized computing systems designed to perform specif...
Introdução Ao Teste De Software 2nd Edition Marcio Delamaro Mario Jino
Functional Programming in C#: How to write better C# code 1st Edition Enrico ...
A Practical Introduction To Data Structures And Algorithms Analysis, Java Edi...
Mechanising_Programs_in_IsabelleHOL
Open source programming
Practice Standard for Scheduling Third Edition Project Management Institute
Java Programming by P.Rizwan Ahmed,MUCollege, Ambur
Network
Table ofcontents
[FREE PDF sample] Object Oriented Programming and Java Second Edition Danny P...
java TM rmi The Remote Method Invocation Guide 1st Edition Esmond Pitt
Coding guideline
Abstract An overview of the whole report and what it is about..docx
[Ebooks PDF] download C How to Program 1ST Edition Harvey M. Deitel full chap...
java TM rmi The Remote Method Invocation Guide 1st Edition Esmond Pitt
Bd siit i pv4-ipv6
Programming the Network with Perl 1st Edition Paul Barry
Ad

Recently uploaded (20)

PPTX
Presentation on HIE in infants and its manifestations
PPTX
Lesson notes of climatology university.
PPTX
Institutional Correction lecture only . . .
PPTX
Pharma ospi slides which help in ospi learning
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
RMMM.pdf make it easy to upload and study
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
Presentation on HIE in infants and its manifestations
Lesson notes of climatology university.
Institutional Correction lecture only . . .
Pharma ospi slides which help in ospi learning
STATICS OF THE RIGID BODIES Hibbelers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Final Presentation General Medicine 03-08-2024.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
RMMM.pdf make it easy to upload and study
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Supply Chain Operations Speaking Notes -ICLT Program
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
2.FourierTransform-ShortQuestionswithAnswers.pdf
Ad

Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman

  • 1. Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman download https://textbookfull.com/product/fortran-for-scientists-and- engineers-4th-edition-stephen-j-chapman/ Download more ebook from https://textbookfull.com
  • 2. We believe these products will be a great fit for you. Click the link to download now, or visit textbookfull.com to discover even more! Physics for Scientists and Engineers A Strategic Approach 4th Edition Randall D. Knight https://textbookfull.com/product/physics-for-scientists-and- engineers-a-strategic-approach-4th-edition-randall-d-knight/ Physics for Scientists and Engineers with Modern Physics 4th Edition Douglas C. Giancoli https://textbookfull.com/product/physics-for-scientists-and- engineers-with-modern-physics-4th-edition-douglas-c-giancoli/ Physics for scientists and engineers an interactive approach 2nd Edition Peter J. Williams https://textbookfull.com/product/physics-for-scientists-and- engineers-an-interactive-approach-2nd-edition-peter-j-williams/ Statistics for Engineers and Scientists William Navidi https://textbookfull.com/product/statistics-for-engineers-and- scientists-william-navidi/
  • 3. Essential MATLAB for Engineers and Scientists Hahn https://textbookfull.com/product/essential-matlab-for-engineers- and-scientists-hahn/ Essential MATLAB for engineers and scientists Hahn https://textbookfull.com/product/essential-matlab-for-engineers- and-scientists-hahn-2/ Essential MATLAB for engineers and scientists Hahn https://textbookfull.com/product/essential-matlab-for-engineers- and-scientists-hahn-3/ Probability statistics for engineers scientists Walpole https://textbookfull.com/product/probability-statistics-for- engineers-scientists-walpole/ Turbulence an introduction for scientists and engineers Davidson https://textbookfull.com/product/turbulence-an-introduction-for- scientists-and-engineers-davidson/
  • 4. Fortran for Scientists and Engineers Fourth Edition Stephen J. Chapman BAE Systems Australia
  • 5. FORTRAN FOR SCIENTISTS AND ENGINEERS, FOURTH EDITION MHID 0–07–338589–1 Library of Congress Cataloging-in-Publication Data Chapman, Stephen J., author. Fortran for scientists and engineers / Stephen J. Chapman, BAE Systems Australia. Fourth edition. | New York, NY : McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., [2017] | Includes index. LCCN 2016052439 | ISBN 9780073385891 (alk. paper) | ISBN 0073385891 (alk. paper) LCSH: FORTRAN (Computer program language) | Science—Data processing. | Engineering—Data processing. LCC QA76.73.F25 C425 2017 | DDC 005.13/3—dc23 LC record available at https://lccn.loc.gov/2016052439 Published by McGraw-Hill Education, 2 Penn Plaza, New York, NY 10121. Copyright © 2018 by McGraw-Hill Education Printed in the United States of America. Previous edition © 2008 and 2004 ISBN 978–0–07–338589–1
  • 6. Preface xix 1 Introduction to Computers and The Fortran Language 1 1.1 The Computer 2 1.1.1. The CPU / 1.1.2. Memory / 1.1.3. Input and Output Devices 1.2 Data Representation in a Computer 4 1.2.1. The Binary Number System / 1.2.2. Octal and Hexadecimal Representations of Binary Numbers / 1.2.3. Types of Data Stored in Memory 1.3 Computer Languages 12 1.4 The History of the Fortran Language 13 1.5 The Evolution of Fortran 16 1.6 Summary 19 1.6.1. Exercises 2 Basic Elements of Fortran 22 2.1 Introduction 22 2.2 The Fortran Character Set 23 2.3 The Structure of a Fortran Statement 23 2.4 The Structure of a Fortran Program 24 2.4.1. The Declaration Section / 2.4.2. The Execution Section / 2.4.3. The Termination Section / 2.4.4. Program Style / 2.4.5. Compiling, Linking, and Executing the Fortran Program 2.5 Constants and Variables 28 2.5.1. Integer Constants and Variables / 2.5.2. Real Constants and Variables / 2.5.3. Character Constants and Variables / 2.5.4. Default and Explicit Variable Typing / 2.5.5. Keeping Constants Consistent in a Program 2.6 Assignment Statements and Arithmetic Calculations 36 2.6.1. Integer Arithmetic / 2.6.2. Real Arithmetic / 2.6.3. Hierarchy of Operations / 2.6.4. Mixed-Mode Arithmetic / 2.6.5. Mixed-Mode Arithmetic and Exponentiation C O N T E N T S
  • 7. 2.7 Intrinsic Functions 47 2.8 List-Directed Input and Output Statements 49 2.9 Initialization of Variables 55 2.10 The IMPLICIT NONE Statement 57 2.11 Program Examples 58 2.12 Debugging Fortran Programs 66 2.13 Summary 68 2.13.1. Summary of Good Programming Practice / 2.13.2. Summary of Fortran Statements / 2.13.3. Exercises 3 Program Design and Branching Structures 81 3.1 Introduction to Top-Down Design Techniques 82 3.2 Use of Pseudocode and Flowcharts 86 3.3 Logical Constants, Variables, and Operators 89 3.3.1. Logical Constants and Variables / 3.3.2. Assignment Statements and Logical Calculations / 3.3.3. Relational Operators / 3.3.4. Combinational Logic Operators / 3.3.5. Logical Values in Input and Output Statements / 3.3.6. The Significance of Logical Variables and Expressions 3.4 Control Constructs: Branches 94 3.4.1. The Block IF Construct / 3.4.2. The ELSE and ELSE IF Clauses / 3.4.3. Examples Using Block IF Constructs / 3.4.4. Named Block IF Constructs / 3.4.5. Notes Concerning the Use of Block IF Constructs / 3.4.6. The Logical IF Statement / 3.4.7. The SELECT CASE Construct 3.5 More on Debugging Fortran Programs 118 3.6 Summary 119 3.6.1. Summary of Good Programming Practice / 3.6.2. Summary of Fortran Statements and Constructs / 3.6.3. Exercises 4 Loops and Character Manipulation 126 4.1 Control Constructs: Loops 126 4.1.1 The While Loop / 4.1.2 The DO WHILE Loop / 4.1.3 The Iterative or Counting Loop / 4.1.4 The CYCLE and EXIT Statements / 4.1.5 Named Loops / 4.1.6 Nesting Loops and Block IF Constructs 4.2 Character Assignments and Character Manipulations 154 4.2.1 Character Assignments / 4.2.2 Substring Specifications / 4.2.3 The Concatenation (//) Operator / 4.2.4 Relational Operators with Character Data / 4.2.5 Character Intrinsic Functions 4.3 Debugging Fortran Loops 168
  • 8. 4.4 Summary 169 4.4.1 Summary of Good Programming Practice / 4.4.2 Summary of Fortran Statements and Constructs / 4.4.3 Exercises 5 Basic I/O Concepts 180 5.1 Formats and Formatted WRITE Statements 180 5.2 Output Devices 182 5.2.1 Control Characters in Printer Output 5.3 Format Descriptors 184 5.3.1 Integer Output—The I Descriptor / 5.3.2 Real Output— The F Descriptor / 5.3.3 Real Output—The E Descriptor / 5.3.4 True Scientific Notation—The ES Descriptor / 5.3.5 Logical Output—The L Descriptor / 5.3.6 Character Output—The A Descriptor / 5.3.7 Horizontal Positioning— The X and T Descriptor / 5.3.8 Repeating Groups of Format Descriptors / 5.3.9 Changing Output Lines—The Slash (/) Descriptor / 5.3.10 How Formats are Used During WRITEs 5.4 Formatted READ Statements 205 5.4.1 Integer Input—The I Descriptor / 5.4.2 Real Input—The F Descriptor / 5.4.3 Logical Input—The L Descriptor / 5.4.4 Character Input—The A Descriptor / 5.4.5 Horizontal Positioning—The X and T Descriptors / 5.4.6 Vertical Positioning—The Slash (/) Descriptor / 5.4.7 How Formats are Used During READs 5.5 An Introduction to Files and File Processing 211 5.5.1 The OPEN Statement / 5.5.2 The CLOSE Statement / 5.5.3 READs and WRITEs to Disk Files / 5.5.4 The IOSTAT= and IOMSG= Clauses in the READ Statement / 5.5.5 File Positioning 5.6 Summary 232 5.6.1 Summary of Good Programming Practice / 5.6.2 Summary of Fortran Statements and Structures / 5.6.3 Exercises 6 Introduction to Arrays 245 6.1 Declaring Arrays 246 6.2 Using Array Elements in Fortran Statements 247 6.2.1 Array Elements are Just Ordinary Variables / 6.2.2 Initialization of Array Elements / 6.2.3 Changing the Subscript Range of an Array / 6.2.4 Out-of-Bounds Array Subscripts / 6.2.5 The Use of Named Constants with Array Declarations 6.3 Using Whole Arrays and Array Subsets in Fortran Statements 261 6.3.1 Whole Array Operations / 6.3.2 Array Subsets
  • 9. 6.4 Input and Output 265 6.4.1 Input and Output of Array Elements / 6.4.2 The Implied DO Loop / 6.4.3 Input and Output of Whole Arrays and Array Sections 6.5 Example Problems 271 6.6 When Should You Use an Array? 287 6.7 Summary 289 6.7.1 Summary of Good Programming Practice / 6.7.2 Summary of Fortran Statements and Constructs / 6.7.3 Exercises 7 Introduction to Procedures 297 7.1 Subroutines 299 7.1.1 Example Problem—Sorting / 7.1.2 The INTENT Attribute / 7.1.3 Variable Passing in Fortran: The Pass-By- Reference Scheme / 7.1.4 Passing Arrays to Subroutines / 7.1.5 Passing Character Variables to Subroutines / 7.1.6 Error Handling in Subroutines / 7.1.7 Examples 7.2 Sharing Data Using Modules 320 7.3 Module Procedures 328 7.3.1 Using Modules to Create Explicit Interfaces 7.4 Fortran Functions 331 7.4.1 Unintended Side Effects in Functions / 7.4.2 Using Functions with Deliberate Side Effects 7.5 Passing Procedures as Arguments to Other Procedures 339 7.5.1 Passing User-Defined Functions as Arguments / 7.5.2 Passing Subroutines as Arguments 7.6 Summary 344 7.6.1 Summary of Good Programming Practice / 7.6.2 Summary of Fortran Statements and Structures / 7.6.3 Exercises 8 Additional Features of Arrays 360 8.1 2D or Rank 2 Arrays 360 8.1.1 Declaring Rank 2 Arrays / 8.1.2 Rank 2 Array Storage / 8.1.3 Initializing Rank 2 Arrays / 8.1.4 Example Problem / 8.1.5 Whole Array Operations and Array Subsets 8.2 Multidimensional or Rank n Arrays 372 8.3 Using Fortran Intrinsic Functions with Arrays 375 8.3.1 Elemental Intrinsic Functions / 8.3.2 Inquiry Intrinsic Functions / 8.3.3 Transformational Intrinsic Functions 8.4 Masked Array Assignment: The WHERE Construct 378 8.4.1 The WHERE Construct / 8.4.2 The WHERE Statement 8.5 The FORALL Construct 381 8.5.1 The Form of the FORALL Construct / 8.5.2 The Significance of the FORALL Construct / 8.5.3 The FORALL Statement
  • 10. 8.6 Allocatable Arrays 383 8.6.1 Fortran Allocatable Arrays / 8.6.2 Using Fortran Allocatable Arrays in Assignment Statements 8.7 Summary 393 8.7.1 Summary of Good Programming Practice / 8.7.2 Summary of Fortran Statements and Constructs / 8.7.3 Exercises 9 Additional Features of Procedures 404 9.1 Passing Multidimensional Arrays to Subroutines and Functions 404 9.1.1 Explicit Shape Dummy Arrays / 9.1.2 Assumed-Shape Dummy Arrays / 9.1.3 Assumed-Size Dummy Arrays 9.2 The SAVE Attribute and Statement 417 9.3 Allocatable Arrays in Procedures 421 9.4 Automatic Arrays in Procedures 422 9.4.1 Comparing Automatic Arrays and Allocatable Arrays / 9.4.2 Example Program 9.5 Allocatable Arrays as Dummy Arguments in Procedures 430 9.5.1 Allocatable Dummy Arguments / 9.5.2 Allocatable Functions 9.6 Pure and Elemental Procedures 434 9.6.1 Pure Procedures / 9.6.2 Elemental Procedures / 9.6.3 Impure Elemental Procedures 9.7 Internal Procedures 436 9.8 Submodules 438 9.9 Summary 446 9.9.1 Summary of Good Programming Practice / 9.9.2 Summary of Fortran Statements and Structures / 9.9.3 Exercises 10 More about Character Variables 457   10.1 Character Comparison Operations 458 10.1.1 The Relational Operators with Character Data / 10.1.2 The Lexical Functions LLT, LLE, LGT, and LGE   10.2 Intrinsic Character Functions 463   10.3 Passing Character Variables to Subroutines and Functions 465   10.4 Variable-Length Character Functions 471   10.5 Internal Files 473   10.6 Example Problems 474   10.7 Summary 479 10.7.1 Summary of Good Programming Practice / 10.7.2 Summary of Fortran Statements and Structures / 10.7.3 Exercises
  • 11. 11 Additional Intrinsic Data Types 485   11.1 Alternate Kinds of the REAL Data Type 485 11.1.1 Kinds of REAL Constants and Variables / 11.1.2 Determining the KIND of a Variable / 11.1.3 Selecting Precision in a Processor- Independent Manner / 11.1.4 Determining the KINDs of Data Types on a Particular Processor / 11.1.5 Mixed-Mode Arithmetic / 11.1.6 Higher Precision Intrinsic Functions / 11.1.7 When to Use High-Precision Real Values / 11.1.8 Solving Large Systems of Simultaneous Linear Equations   11.2 Alternate Lengths of the INTEGER Data Type 509   11.3 Alternate Kinds of the CHARACTER Data Type 511   11.4 The COMPLEX Data Type 512 11.4.1 Complex Constants and Variables / 11.4.2 Initializing Complex Variables / 11.4.3 Mixed-Mode Arithmetic / 11.4.4 Using Complex Numbers with Relational Operators / 11.4.5 COMPLEX Intrinsic Functions   11.5 Summary 522 11.5.1 Summary of Good Programming Practice / 11.5.2 Summary of Fortran Statements and Structures / 11.5.3 Exercises 12 Derived Data Types 527   12.1 Introduction to Derived Data Types 527   12.2 Working with Derived Data Types 529   12.3 Input and Output of Derived Data Types 529   12.4 Declaring Derived Data Types in Modules 531   12.5 Returning Derived Types from Functions 540   12.6 Dynamic Allocation of Derived Data Types 544   12.7 Parameterized Derived Data Types 545   12.8 Type Extension 546   12.9 Type-Bound Procedures 548 12.10 The ASSOCIATE Construct 552 12.11 Summary 553 12.11.1 Summary of Good Programming Practice / 12.11.2 Summary of Fortran Statements and Structures / 12.11.3 Exercises 13 Advanced Features of Procedures and Modules 561   13.1 Scope and Scoping Units 562   13.2 Blocks 567   13.3 Recursive Procedures 568   13.4 Keyword Arguments and Optional Arguments 571
  • 12.   13.5 Procedure Interfaces and Interface Blocks 577 13.5.1 Creating Interface Blocks / 13.5.2 Notes on the Use of Interface Blocks   13.6 Generic Procedures 581 13.6.1 User-Defined Generic Procedures / 13.6.2 Generic Interfaces for Procedures in Modules / 13.6.3 Generic Bound Procedures   13.7 Extending Fortran with User-Defined Operators and Assignments 594   13.8 Bound Assignments and Operators 607   13.9 Restricting Access to the Contents of a Module 607 13.10 Advanced Options of the USE Statement 611 13.11 Intrinsic Modules 615 13.12 Access to Command Line Arguments and Environment Variables 615 13.12.1 Access to Command Line Arguments / 13.12.2 Retrieving Environment Variables 13.13 The VOLATILE Attribute and Statement 618 13.14 Summary 619 13.14.1 Summary of Good Programming Practice / 13.14.2 Summary of Fortran Statements and Structures / 13.14.3 Exercises 14 Advanced I/O Concepts 633   14.1 Additional Format Descriptors 633 14.1.1 Additional Forms of the E and ES Format Descriptors / 14.1.2 Engineering Notation—The EN Descriptor / 14.1.3 Double- Precision Data—The D Descriptor / 14.1.4 The Generalized (G) Format Descriptor / 14.1.5 The G0 Format Descriptor / 14.1.6 The Binary, Octal, and Hexadecimal (B, O, and Z) Descriptors / 14.1.7 The TAB Descriptors / 14.1.8 The Colon (:) Descriptor / 14.1.9 Scale Factors—The P Descriptor / 14.1.10 The SIGN Descriptors / 14.1.11 Blank Interpretation: The BN and BZ Descriptors / 14.1.12 Rounding Control: The RU, RD, RZ, RN, RC, and RP Descriptors / 14.1.13 Decimal Specifier: The DC and DP Descriptors   14.2 Defaulting Values in List-Directed Input 642   14.3 Detailed Description of Fortran I/O Statements 644 14.3.1 The OPEN Statement / 14.3.2 The CLOSE Statement / 14.3.3 The INQUIRE Statement / 14.3.4 The READ Statement / 14.3.5 Alternate Form of the READ Statement / 14.3.6 The WRITE Statement / 14.3.7 The PRINT Statement / 14.3.8 File Positioning Statements / 14.3.9 The ENDFILE Statement / 14.3.10 The WAIT Statement / 14.3.11 The FLUSH Statement   14.4 Namelist I/O 668   14.5 Unformatted Files 671   14.6 Direct Access Files 673
  • 13.   14.7 Stream Access Mode 678   14.8 Nondefault I/O for Derived Types 678   14.9 Asynchronous I/O 687 14.9.1. Performing Asynchronous I/O / 14.9.2. Problems with Asynchronous I/O 14.10 Access to Processor-Specific I/O System Information 689 14.11 Summary 690 14.11.1 Summary of Good Programming Practice / 14.11.2 Summary of Fortran Statements and Structures / 14.11.3 Exercises 15 Pointers and Dynamic Data Structures 698   15.1 Pointers and Targets 699 15.1.1 Pointer Assignment Statements / 15.1.2 Pointer Association Status   15.2 Using Pointers in Assignment Statements 705   15.3 Using Pointers with Arrays 707   15.4 Dynamic Memory Allocation with Pointers 709   15.5 Using Pointers as Components of Derived Data Types 712   15.6 Arrays of Pointers 725   15.7 Using Pointers in Procedures 727 15.7.1 Using the INTENT Attribute with Pointers / 15.7.2 Pointer-valued Functions   15.8 Procedure Pointers 733   15.9 Binary Tree Structures 736 15.9.1 The Significance of Binary Tree Structures / 15.9.2 Building a Binary Tree Structure 15.10 Summary 756 15.10.1 Summary of Good Programming Practice / 15.10.2 Summary of Fortran Statements and Structures / 15.10.3 Exercises 16 Object-Oriented Programming in Fortran 763   16.1 An Introduction to Object-Oriented Programming 764 16.1.1 Objects / 16.1.2 Messages / 16.1.3 Classes / 16.1.4 Class Hierarchy and Inheritance / 16.1.5 Object- Oriented Programming   16.2 The Structure of a Fortran Class 769   16.3 The CLASS Keyword 770   16.4 Implementing Classes and Objects in Fortran 772 16.4.1 Declaring Fields (Instance Variables) / 16.4.2 Creating Methods / 16.4.3 Creating (Instantiating) Objects from a Class
  • 14. 16.5 First Example: A timer Class 775 16.5.1 Implementing the timer Class / 16.5.2 Using the timer Class / 16.5.3 Comments on the timer Class   16.6 Categories of Methods 780   16.7 Controlling Access to Class Members 789   16.8 Finalizers 790   16.9 Inheritance and Polymorphism 794 16.9.1 Superclasses and Subclasses / 16.9.2 Defining and Using Subclasses / 16.9.3 The Relationship between Superclass Objects and Subclass Objects / 16.9.4 Polymorphism / 16.9.5 The SELECT TYPE Construct 16.10 Preventing Methods from Being Overridden in Subclasses 809 16.11 Abstract Classes 809 16.12 Summary 831 16.12.1 Summary of Good Programming Practice / 16.12.2 Summary of Fortran Statements and Structures / 16.12.3 Exercises 17 Coarrays and Parallel Processing 837   17.1 Parallel Processing in Coarray Fortran 838   17.2 Creating a Simple Parallel Program 839   17.3 Coarrays 841   17.4 Synchronization between Images 843   17.5 Example: Sorting a Large Data Set 850   17.6 Allocatable Coarrays and Derived Data Types 856   17.7 Passing Coarrays to Procedures 857   17.8 Critical Sections 858   17.9 The Perils of parallel Programming 859 17.10 Summary 863 17.10.1 Summary of Good Programming Practice / 17.10.2 Summary of Fortran Statements and Structures / 17.10.3 Exercises 18 Redundant, Obsolescent, and Deleted Fortran Features 869   18.1 Pre-Fortran 90 Character Restrictions 870   18.2 Obsolescent Source Form 870   18.3 Redundant Data Type 871   18.4 Older, Obsolescent, and/or Undesirable Specification Statements 872 18.4.1 Pre-Fortran 90 Specification Statements / 18.4.2 The IMPLICIT Statement / 18.4.3 The DIMENSION Statement / 18.4.4 The DATA Statement / 18.4.5 The PARAMETER Statement
  • 15.   18.5 Sharing Memory Locations: COMMON and EQUIVALENCE 875 18.5.1 COMMON Blocks / 18.5.2 Initializing Data in COMMON Blocks: The BLOCK DATA Subprogram / 18.5.3 The Unlabeled COMMON Statement / 18.5.4 The EQUIVALENCE Statement   18.6 Undesirable Subprogram Features 882 18.6.1 Alternate Subroutine Returns / 18.6.2 Alternate Entry Points / 18.6.3 The Statement Function / 18.6.4 Passing Intrinsic Functions as Arguments   18.7 Miscellaneous Execution Control Features 889 18.7.1 The PAUSE Statement / 18.7.2 Arguments Associated with the STOP Statement / 18.7.3 The END Statement   18.8 Obsolete Branching and Looping Structures 892 18.8.1 The Arithmetic IF Statement / 18.8.2 The Unconditional GO TO Statement / 18.8.3 The Computed GO TO Statement / 18.8.4 The Assigned GO TO Statement / 18.8.5 Older Forms of DO Loops   18.9 Redundant Features of I/O Statements 896 18.10 Summary 897 18.10.1 Summary of Good Programming Practice / 18.10.2 Summary of Fortran Statements and Structures Appendixes A. The ASCII Character Set 903 B. Fortran/C Interoperability 904 B.1. Declaring Interoperable Data Types / B.2. Declaring Interoperable Procedures / B.3. Sample Programs— Fortran Calling C / B.4. Sample Programs—C Calling Fortran C. Fortran Intrinsic Pro­ cedures 914 C.1. Classes of Intrinsic Procedures / C.2. Alphabetical List of Intrinsic Procedures / C.3. Mathematical and Type Conversion Intrinsic Procedures / C.4. Kind and Numeric Processor Intrinsic Functions / C.5. System Environment Procedures / C.6. Bit Intrinsic Procedures / C.7. Character Intrinsic Functions / C.8. Array and Pointer Intrinsic Functions / C.9. Miscellaneous Inquiry Functions / C.10. Miscellaneous Procedures / C.11. Coarray Functions D. Order of Statements in a Fortran Program 961 E. Glossary 963 F. Answers to Quizzes 984 Index 1002 Summary of Selected Fortran Statements and Structures 1022
  • 16. P R E F A C E The first edition of this book was conceived as a result of my experience in writing and maintaining large Fortran programs in both the defense and geophysical fields. During my time in industry, it became obvious that the strategies and techniques ­ required to write large, maintainable Fortran programs were quite different from what new ­ engineers were learning in their Fortran programming classes at school. The ­ incredible cost of maintaining and modifying large programs once they are placed into service absolutely demands that they be written to be easily understood and modified by ­ people other than their original programmers. My goal for this book is to teach ­ simultaneously both the fundamentals of the Fortran language and a programming style that results in good, maintainable programs. In addition, it is intended to serve as a reference for graduates working in industry. It is quite difficult to teach undergraduates the importance of taking extra effort during the early stages of the program design process in order to make their programs more maintainable. Class programming assignments must by their very nature be sim- ple enough for one person to complete in a short period of time, and they do not have to be maintained for years. Because the projects are simple, a student can often “wing it” and still produce working code. A student can take a course, perform all of the pro- gramming assignments, pass all of the tests, and still not learn the habits that are really needed when working on large projects in industry. From the very beginning, this book teaches Fortran in a style suitable for use on large projects. It emphasizes the importance of going through a detailed design pro- cess before any code is written, using a top-down design technique to break the pro- gram up into logical portions that can be implemented separately. It stresses the use of procedures to implement those individual portions, and the importance of unit testing before the procedures are combined into a finished product. Finally, it emphasizes the importance of exhaustively testing the finished program with many different input data sets before it is released for use. In addition, this book teaches Fortran as it is actually encountered by engineers and scientists working in industry and in laboratories. One fact of life is common in all pro- gramming environments: Large amounts of old legacy code that have to be maintained. The legacy code at a particular site may have been originally written in Fortran IV (or an even earlier version!), and it may use programming constructs that are no longer common today. For example, such code may use arithmetic IF statements, or computed or assigned GO TO statements. Chapter 18 is devoted to those older features of the lan- guage that are no longer commonly used, but that are encountered in legacy code.
  • 17. xx Preface The chapter emphasizes that these features should never be used in a new program, but also prepares the student to handle them when he or she encounters them. CHANGES IN THIS EDITION This edition builds directly on the success of Fortran 95/2003 for Scientists and Engi- neers, 3/e. It preserves the structure of the previous edition, while weaving the new Fortran 2008 material (and limited material from the proposed Fortran 2015 standard) throughout the text. It is amazing, but Fortran started life around 1954, and it is still evolving. Most of the additions in Fortran 2008 are logical extensions of existing capabili- ties of Fortran 2003, and they are integrated into the text in the proper chapters. How- ever, the use of parallel processing and Coarray Fortran is completely new, and Chapter 17 has been added to cover that material. The vast majority of Fortran courses are limited to one-quarter or one semester, and the student is expected to pick up both the basics of the Fortran language and the concept of how to program. Such a course would cover Chapters 1 through 7 of this text, plus selected topics in Chapters 8 and 9 if there is time. This provides a good foundation for students to build on in their own time as they use the language in ­practical projects. Advanced students and practicing scientists and engineers will need the material on COMPLEX numbers, derived data types, and pointers found in Chapters 11 through 15. Practicing scientists and engineers will almost certainly need the material on obsolete, redundant, and deleted Fortran features found in Chapter 18. These materials are rarely taught in the classroom, but they are included here to make the book a useful reference text when the language is actually used to solve real-world problems. FEATURES OF THIS BOOK Many features of this book are designed to emphasize the proper way to write reliable Fortran programs. These features should serve a student well as he or she is first learn- ing Fortran, and should also be useful to the practitioner on the job. They include: 1. Emphasis on Modern Fortran. The book consistently teaches the best current practice in all of its examples. Many modern Fortran 2008 features duplicate and supersede older features of the Fortran language. In those cases, the proper usage of the modern language is presented. Examples of older usage are largely relegated to Chapter 18, where their old/undesirable nature is emphasized. Examples of modern Fortran features that supersede older features are the use of modules to share data ­instead of COMMON blocks, the use of DO . . . END DO loops instead of DO . . . ­ CONTINUE loops, the use of internal procedures instead of statement functions, and the use of CASE constructs instead of computed GOTOs.
  • 18. Preface xxi 2. Emphasis on Strong Typing. The IMPLICIT NONE statement is used consistently throughout the book to force the explicit typing of every variable used in every program, and to catch common typographical errors at compilation time. In conjunction with the ex- plicit declaration of every variable in a program, the book emphasizes the im- portance of creating a data dictionary that describes the purpose of each variable in a program unit. 3. Emphasis on Top-Down Design Methodology. The book introduces a top-down design methodology in Chapter 3, and then uses it consistently throughout the rest of the book. This methodology encour- ages a student to think about the proper design of a program before beginning to code. It emphasizes the importance of clearly defining the problem to be solved and the required inputs and outputs before any other work is begun. Once the problem is properly defined, it teaches the student to employ stepwise refinement to break the task down into successively smaller subtasks, and to implement the subtasks as separate subroutines or functions. Finally, it teaches the importance of testing at all stages of the process, both unit testing of the component routines and exhaustive testing of the final product. Several exam- ples are given of programs that work properly for some data sets, and then fail for others. The formal design process taught by the book may be summarized as follows: ∙ Clearly state the problem that you are trying to solve. ∙ Define the inputs required by the program and the outputs to be produced by the program. ∙ Describe the algorithm that you intend to implement in the program. This step involves top-down design and stepwise decomposition, using pseudo- code or flow charts. ∙ Turn the algorithm into Fortran statements. ∙ Test the Fortran program. This step includes unit testing of specific subpro- grams, and also exhaustive testing of the final program with many different data sets. 4. Emphasis on Procedures. The book emphasizes the use of subroutines and functions to logically decom- pose tasks into smaller subtasks. It teaches the advantages of procedures for data hiding. It also emphasizes the importance of unit testing procedures before they are combined into the final program. In addition, the book teaches about the common mistakes made with procedures, and how to avoid them (argument type mismatches, array length mismatches, etc.). It emphasizes the advantages asso- ciated with explicit interfaces to procedures, which allow the Fortran compiler to catch most common programming errors at compilation time. 5. Emphasis on Portability and Standard Fortran. The book stresses the importance of writing portable Fortran code, so that a program can easily be moved from one type of computer to another one.
  • 19. It teaches students to use only standard Fortran statements in their programs, so that they will be as portable as possible. In addition, it teaches the use of ­ features such as the SELECTED_REAL_KIND function to avoid precision and kind differences when moving from computer to computer. The book also teaches students to isolate machine-dependent code (such as code that calls machine-dependent system libraries) into a few specific proce- dures, so that only those procedures will have to be rewritten when a program is ported between computers. 6. Good Programming Practice Boxes. These boxes highlight good programming practices when they are introduced for the convenience of the student. In addition, the good programming practices introduced in a chapter are summarized at the end of the chapter. An example Good Programming Practice Box is shown below: Good Programming Practice Always indent the body of an IF structure by two or more spaces to improve the readability of the code. 7. Programming Pitfalls Boxes These boxes highlight common errors so that they can be avoided. An exam- ple Programming Pitfalls Box is shown below: Programming Pitfalls Beware of integer arithmetic. Integer division often gives unexpected results. 8. Emphasis on Pointers and Dynamic Data Structures. Chapter 15 contains a detailed discussion of Fortran pointers, including pos- sible problems resulting from the incorrect use of pointers such as memory leaks and pointers to deallocated memory. Examples of dynamic data struc- tures in the chapter include linked lists and binary trees. Chapter 16 contains a discussion of Fortran objects and object-oriented pro- gramming, including the use of dynamic pointers to achieve polymorphic behavior. 9. Use of Sidebars. A number of sidebars are scattered throughout the book. These sidebars pro- vide additional information of potential interest to the student. Some sidebars are historical in nature. For example, one sidebar in Chapter 1 describes the IBM Model 704, the first computer to ever run Fortran. Other sidebars xxii Preface
  • 20. ­ reinforce lessons from the main text. For example, Chapter 9 contains a side- bar reviewing and summarizing the many different types of arrays found in modern Fortran. 10. Completeness. Finally, the book endeavors to be a complete reference to the modern Fortran language, so that a practitioner can locate any required information quickly. Special attention has been paid to the index to make features easy to find. A special effort has also been made to cover such obscure and little understood features as passing procedure names by reference, and defaulting values in list-directed input statements. PEDAGOGICAL FEATURES The book includes several features designed to aid student comprehension. Each chapter begins with a list of the objectives that should be achieved in that chapter. A total of 27 quizzes appear scattered throughout the chapters, with answers to all questions included in Appendix F. These quizzes can serve as a useful self-test of comprehension. In addition, there are approximately 360 end-of-chapter exercises. Answers to selected exercises are available at the book’s Web site, and of course an- swers to all exercises are included in the Instructor’s Manual. Good programming practices are highlighted in all chapters with special Good Programming Practice boxes, and common errors are highlighted in ­ Programming Pitfalls boxes. End-of- chapter materials include Summaries of Good Programming Practice and Summaries of Fortran Statements and Structures. Finally, a detailed description of every Fortran intrinsic procedure is included in Appendix C, and an extensive Glossary is included in Appendix E. The book is accompanied by an Instructor’s Manual, containing the solutions to all end-of-chapter exercises. Instructors can also download the solutions in the ­ Instructor’s Manual from the book’s Web site. The source code for all examples in the book, plus other supplemental materials, can be downloaded by anyone from the book’s ­ Web site. A NOTE ABOUT FORTRAN COMPILERS Two Fortran compilers were used during the preparation of this book: the Intel Visual Fortran Compiler Version 16.0 and the GNU G95 Fortran compiler. Both compilers provide essentially complete implementations of Fortran 2008, with only a very few minor items not yet implemented. They are also both looking to the future, implement- ing features from the proposed Fortran 2015 standard. I highly recommend both compilers to potential users. The great advantage of ­ Intel Fortran is the very nice integrated debugging environment, and the great disad- vantage is cost. The G95 compiler is free, but it is somewhat harder to debug. Preface xxiii
  • 21. A FINAL NOTE TO THE USER No matter how hard I try to proofread a document like this book, it is inevitable that some typographical errors will slip through and appear in print. If you should spot any such errors, please drop me a note via the publisher, and I will do my best to get them eliminated from subsequent printings and editions. Thank you very much for your help in this matter. I will maintain a complete list of errata and corrections at the book’s World Wide Web site, which is www.mhhe.com/chapman4e. Please check that site for any updates and/or corrections. ACKNOWLEDGMENTS I would like to thank Raghu Srinivasan and the team at McGraw-Hill Education for making this revision possible. In addition, I would like to thank my wife Rosa and daughter Devorah for their support during the revision process. (In previous editions, I had thanked our other seven children as well, but they have all now flown the coop!) Stephen J. Chapman Melbourne, Victoria, Australia August 7, 2016 xxiv Preface
  • 22. 1 1 Introduction to Computers and the Fortran Language OBJECTIVES ∙ Know the basic components of a computer. ∙ Understand binary, octal, and hexadecimal numbers. ∙ Learn about the history of the Fortran language. The computer was probably the most important invention of the twentieth century. It affects our lives profoundly in very many ways. When we go to the grocery store, the scanners that check out our groceries are run by computers. Our bank balances are maintained by computers, and the automatic teller machines and credit and debit cards that allow us to make banking transactions at any time of the day or night are run by more computers. Computers control our telephone and electric power sys- tems, run our microwave ovens and other appliances, and control the engines in our cars. Almost any business in the developed world would collapse overnight if it were suddenly deprived of its computers. Considering their importance in our lives, it is almost impossible to believe that the first electronic computers were invented just about 75 years ago. Just what is this device that has had such an impact on all of our lives? A ­computer is a special type of machine that stores information, and can perform mathematical calculations on that information at speeds much faster than human beings can think. A program, which is stored in the computer’s memory, tells the computer what sequence of calculations is required, and which information to perform the calculations on. Most computers are very flexible. For example, the computer on which I write these words can also balance my checkbook, if I just execute a different program on it. Computers can store huge amounts of information, and with proper programming, they can make that information instantly available when it is needed. For example, a bank’s computer can hold the complete list of all the deposits and debits made by ­ every one of its customers. On a larger scale, credit companies use their computers to hold the credit histories of every person in the United States—literally billions of
  • 23. 2 chapter 1:   Introduction to Computers and the Fortran Language 1 pieces of information. When requested, they can search through those billions of pieces of information to recover the credit records of any single person, and present those records to the user in a matter of seconds. It is important to realize that computers do not think as humans understand ­thinking. They merely follow the steps contained in their programs. When a computer appears to be doing something clever, it is because a clever person has written the pro- gram that it is executing. That is where we humans come into the act. It is our collec- tive creativity that allows the computer to perform its seeming miracles. This book will help teach you how to write programs of your own, so that the computer will do what you want it to do. 1.1 THE COMPUTER A block diagram of a typical computer is shown in Figure 1-1. The major components of the computer are the central processing unit (CPU), main memory, secondary memory, and input and output devices. These components are described in the para- graphs below. FIGURE 1-1 A block diagram of a typical computer. Main memory Secondary memory Internal memory (registers) Control unit Memory cache Arithmetic logic unit Output devices Central processing unit
  • 24. Introduction to Computers and the Fortran Language 3 1 1.1.1 The CPU The central processing unit is the heart of any computer. It is divided into a control unit, an arithmetic logic unit (ALU), and internal memory. The control unit within the CPU controls all of the other parts of the computer, while the ALU performs the actual math- ematical calculations. The internal memory within a CPU consists of a series of mem- ory registers used for the temporary storage of intermediate results during calculations, plus a memory cache to temporarily store data that will be needed in the near future. The control unit of the CPU interprets the instructions of the computer program. It also fetches data values from main memory (or the memory cache) and stores them in the memory registers, and sends data values from memory registers to output devices or main memory. For example, if a program says to multiply two numbers together and save the result, the control unit will fetch the two numbers from main memory and store them in registers. Then, it will present the numbers in the registers to the ALU along with directions to multiply them and store the results in another register. Finally, after the ALU multiplies the numbers, the control unit will take the result from the destination register and store it back into the memory cache. (Other parts of the CPU copy the data from the memory cache to main memory in slower time.) Modern CPUs have become dramatically faster by incorporating multiple ALUs running in parallel, allowing more operations to be performed in a given amount of time. They also incorporate larger memory caches on the CPU chip, allowing data to be fetched and saved very rapidly. 1.1.2 Memory The memory of a computer is divided into three major types of memory: cache mem- ory, main or primary memory, and secondary memory. Cache memory is memory stored on the CPU chip itself. This memory can be accessed very rapidly, allowing calculations to proceed at very high speed. The control unit looks ahead in the program to see what data will be needed, and pre-fetches it from main memory into the memory cache so that it can be used with minimal delay. The control unit also copies the results of calculations from the cache back to main memory when they are no ­ longer needed. Main memory usually consists of separate semiconductor chips connected to the CPU by conductors called a memory bus. It is very fast, and relatively inexpensive com- pared to the memory on the CPU itself. Data that is stored in main memory can be fetched for use in a few nanoseconds or less (sometimes much less) on a modern computer. Be- cause it is so fast and cheap, main memory is used to temporarily store the program currently being executed by the computer, as well as the data that the program requires. Main memory is not used for the permanent storage of programs or data. Most main memory is volatile, meaning that it is erased whenever the computer’s power is turned off. Besides, main memory is relatively expensive, so we only buy enough to hold all of the programs actually being executed at any given time. Secondary memory consists of devices that are slower and cheaper than main mem- ory. They can store much more information for much less money than main ­ memory can. In addition, most secondary memory devices are nonvolatile, meaning that they retain
  • 25. 4 chapter 1:   Introduction to Computers and the Fortran Language 1 the programs and data stored in them whenever the computer’s power is turned off. Typ- ical secondary memory devices are hard disks, solid-state drives (SSD), USB memory sticks, and DVDs. Secondary storage devices are normally used to store programs and data that are not needed at the moment, but that may be needed some time in the future. 1.1.3 Input and Output Devices Data is entered into a computer through an input device, and is output through an out- put device. The most common input devices on a modern computer are the keyboard and the mouse. We can type programs or data into a computer with a keyboard. Other types of input devices found on some computers include touchscreens, scanners, ­ microphones, and cameras. Output devices permit us to use the data stored in a computer. The most common output devices on today’s computers are displays and printers. Other types of output devices include plotters and speakers. 1.2 DATA REPRESENTATION IN A COMPUTER Computer memories are composed of billions of individual switches, each of which can be ON or OFF, but not at a state in between. Each switch represents one binary digit (also called a bit); the ON state is interpreted as a binary 1, and the OFF state is interpreted as a binary 0. Taken by itself, a single switch can only represent the numbers 0 and 1. Since we obviously need to work with numbers other than 0 and 1, a number of bits are grouped together to represent each number used in a computer. When several bits are grouped ­ together, they can be used to represent numbers in the binary (base 2) number system. The smallest common grouping of bits is called a byte. A byte is a group of 8 bits that are used together to represent a binary number. The byte is the fundamental unit used to measure the capacity of a computer’s memory. For example, the personal com- puter on which I am writing these words has a main memory of 24 gigabytes (24,000,000,000 bytes) and a secondary memory (disk drive) with a storage of 2 ­ terabytes (2,000,000,000,000 bytes). The next larger grouping of bits in a computer is called a word. A word consists of 2, 4, or more consecutive bytes that are used to represent a single number in mem- ory. The size of a word varies from computer to computer, so words are not a particu- larly good way to judge the size of computer memories. Modern CPUs tend to use words with lengths of either 32 or 64 bits. 1.2.1 The Binary Number System In the familiar base 10 number system, the smallest (rightmost) digit of a number is the ones place (100 ). The next digit is in the tens place (101 ), and the next one is in the hundreds place (102 ), etc. Thus, the number 12210 is really (1 × 102 ) + (2 × 101 ) + (2 × 100 ). Each digit is worth a power of 10 more than the digit to the right of it in the base 10 system (see Figure 1-2a).
  • 26. Introduction to Computers and the Fortran Language 5 1 Similarly, in the binary number system, the smallest (rightmost) digit is the ones place (20 ). The next digit is in the twos place (21 ), and the next one is in the fours place (22 ), etc. Each digit is worth a power of 2 more than the digit to the right of it in the base 2 system. For example, the binary number 1012 is really (1 × 22 ) + (0 × 21 ) + (1 × 20 ) = 5, and the binary number 1112 = 7 (see Figure 1-2b). Note that three binary digits can be used to represent eight possible values: 0 (= 0002 ) to 7 (= 1112 ). In general, if n bits are grouped together to form a binary number, then they can represent 2n possible values. Thus, a group of 8 bits (1 byte) can represent 256 possi- ble values, a group of 16 bits (2 bytes) can be used to represent 65,536 possible values, and a group of 32 bits (4 bytes) can be used to represent 4,294,967,296 possible values. In a typical implementation, half of all possible values are reserved for represent- ing negative numbers, and half of the values are reserved for representing zero plus the positive numbers. Thus, a group of 8 bits (1 byte) is usually used to represent numbers between −128 and +127, including 0, and a group of 16 bits (2 bytes) is usually used to represent numbers between −32,768 and +32,767, including 0.1 FIGURE 1-2 (a) The base 10 number 122 is really (1 × 102 ) + (2 × 101 ) + (2 × 100 ). (b) Similarly, the base 2 number 1012 is really (1 × 22 ) + (0 × 21 ) + (1 × 20 ). 100’s place 10’s place 1’s place (a) 1 2 2 4’s place 2’s place 1’s place (b) 1 0 12 = 510 1 The most common scheme for representing negative numbers in a computer’s memory is the so-called two’s complement representation, which is described in the sidebar. TWO’S COMPLEMENT ARITHMETIC The most common way to represent negative numbers in the binary number system is the two’s complement representation. What is two’s complement, and what is so spe- cial about it? Let’s find out. The Two’s Complement Representation of Negative Numbers In the two’s complement representation, the leftmost bit of a number is the sign bit. If that bit is 0, then the number is positive; if it is 1, then the number is negative. To change a positive number into the corresponding negative number in the two’s comple- ment system, we perform two steps: 1. Complement the number (change all 1s to 0 and all 0s to 1). 2. Add 1 to the complemented number.
  • 27. 6 chapter 1:   Introduction to Computers and the Fortran Language 1 Let’s illustrate the process using simple 8-bit integers. As we already know, the 8-bit binary representation of the number 3 would be 00000011. The two’s comple- ment representation of the number −3 would be found as follows: 1. Complement the positive number: 11111100 2. Add 1 to the complemented number: 11111100 + 1 = 11111101 Exactly the same process is used to convert negative numbers back to positive num- bers. To convert the number −3 (11111101) back to a positive 3, we would: 1. Complement the negative number: 00000010 2. Add 1 to the complemented number: 00000010 + 1 = 00000011 Two’s Complement Arithmetic Now we know how to represent numbers in two’s complement representation, and to convert between positive and two’s complement negative numbers. The special ­ advantage of two’s complement arithmetic is that positive and negative numbers may be added together according to the rules of ordinary addition without regard to the sign, and the resulting answer will be correct, including the proper sign. ­ Because of this fact, a computer may add any two integers together without checking to see what the signs of the two integers are. This simplifies the design of computer circuits. Let’s do a few examples to illustrate this point. 1. Add 3 + 4 in two’s complement arithmetic. 3 00000011 +4 00000100 7 00000111 2. Add (−3) + (−4) in two’s complement arithmetic. 3 11111101 +−4 11111100 −7 111111001 In a case like this, we ignore the extra ninth bit resulting from the sum, and the answer is 11111001. The two’s complement of 11111001 is 00000111 or 7, so the ­ result of the addition was −7! 3. Add 3 + (−4) in two’s complement arithmetic. −3 00000011 +−4 11111100 −1 11111111 The answer is 11111111. The two’s complement of 11111111 is 00000001 or 1, so the result of the addition was −1. With two’s complement numbers, binary addition comes up with the correct ­ answer regardless of whether the numbers being added are both positive, both negative, or mixed.
  • 28. Introduction to Computers and the Fortran Language 7 1 1.2.2 Octal and Hexadecimal Representations of Binary Numbers Computers work in the binary number system, but people think in the decimal number system. Fortunately, we can program the computer to accept inputs and give its outputs in the decimal system, converting them internally to binary form for processing. Most of the time, the fact that computers work with binary numbers is irrelevant to the ­programmer. However, there are some cases in which a scientist or engineer has to work directly with the binary representations coded into the computer. For example, individual bits or groups of bits within a word might contain status information about the operation of some machine. If so, the programmer will have to consider the individual bits of the word, and work in the binary number system. A scientist or engineer who has to work in the binary number system immediately faces the problem that binary numbers are unwieldy. For example, a number like 110010 in the decimal system is 0100010011002 in the binary system. It is easy to get lost working with such a number! To avoid this problem, we customarily break binary numbers down into groups of 3 or 4 bits, and represent those bits by a single base 8 (octal) or base 16 (hexadecimal) number. To understand this idea, note that a group of 3 bits can represent any number ­ between 0 (= 0002 ) and 7 (= 1112 ). These are the numbers found in an octal or base 8 arithmetic system. An octal number system has seven digits: 0 through 7. We can break a binary number up into groups of 3 bits, and substitute the appropriate octal digit for each group. Let’s use the number 0100010011002 as an example. Breaking the number into groups of three digits yields 010∣001∣001∣1002 . If each group of 3 bits is replaced by the appropriate octal number, the value can be written as 21148 . The octal number represents exactly the same pattern of bits as the binary number, but it is more compact. Similarly, a group of 4 bits can represent any number between 0 (= 00002 ) and 15 (= 11112 ). These are the numbers found in a hexadecimal or base 16 arithmetic system. A hexadecimal number system has 16 digits: 0 through 9 and A through F. Since the hexadecimal system needs 16 digits, we use digits 0 through 9 for the first 10 of them, and then letters A through F for the remaining 6. Thus, 916 = 910 , A16 = 1010 , B16 = 1110 , and so forth. We can break a binary number up into groups of 4 bits, and substitute the appropriate hexadecimal digit for each group. Let’s use the number 0100010011002 again as an example. Breaking the number into groups of four digits yields 0100∣0100∣11002 . If each group of 4 bits is replaced by the appro- priate hexadecimal number, the value can be written as 44C16 . The hexadecimal number represents exactly the same pattern of bits as the binary number, but more compactly. Some computer vendors prefer to use octal numbers to represent bit patterns, while other computer vendors prefer to use hexadecimal numbers to represent bit pat- terns. Both representations are equivalent, in that they represent the pattern of bits in a compact form. A Fortran language program can input or output numbers in any of the four formats (decimal, binary, octal, or hexadecimal). Table 1-1 lists the decimal, ­ binary, octal, and hexadecimal forms of the numbers 0 to 15.
  • 29. 8 chapter 1:   Introduction to Computers and the Fortran Language 1 1.2.3 Types of Data Stored in Memory Three common types of data are stored in a computer’s memory: character data, ­ integer data, and real data (numbers with a decimal point). Each type of data has different characteristics, and takes up a different amount of memory in the computer. Character Data The character data type consists of characters and symbols. A typical system for representing character data in a non-Oriental language must include the following symbols: 1. The 26 uppercase letters A through Z 2. The 26 lowercase letters a through z 3. The 10 digits 0 through 9 4. Miscellaneous common symbols, such as ,(), {}, [], !, ~, @, #, $, %, ^, , and *. 5. Any special letters or symbols required by the language, such as à, ç, ë, and £. Since the total number of characters and symbols required to write Western ­ languages is less than 256, it is customary to use 1 byte of memory to store each character. Therefore, 10,000 characters would occupy 10,000 bytes of the comput- er’s memory. The particular bit values corresponding to each letter or symbol may vary from computer to computer, depending upon the coding system used for the characters. The most important coding system is ASCII, which stands for the American Standard Code TABLE 1-1 Table of decimal, binary, octal, and hexadecimal numbers Decimal Binary Octal Hexadecimal 0 0000 0 0 1 0001 1 1 2 0010 2 2 3 0011 3 3 4 0100 4 4 5 0101 5 5 6 0110 6 6 7 0111 7 7 8 1000 10 8 9 1001 11 9 10 1010 12 A 11 1011 13 B 12 1100 14 C 13 1101 15 D 14 1110 16 E 15 1111 17 F
  • 30. Introduction to Computers and the Fortran Language 9 1 for Information Interchange (ANSI X3.4 1986, or ISO/IEC 646:1991). The ASCII coding system defines the values to associate with the first 128 of the 256 possible values that can be stored in a 1-byte character. The 8-bit codes corresponding to each letter and number in the ­ ASCII coding system are given in Appendix A. The second 128 characters that can be stored in a 1-byte character are not defined by the ASCII character set, and they used to be defined differently depending on the language used in a particular country or region. These definitions are a part of the ISO 8859 standard series, and they are sometimes referred to as “code pages.” For exam- ple, the ISO 8859-1 (Latin 1) character set is the version used in Western European countries. There are similar code pages available for Eastern European languages, ­ Arabic, Greek, Hebrew, and so forth. Unfortunately, the use of different code pages made the output of programs and the contents of files appear different in different countries. As a result, these code pages are falling out of favor, and being replaced by the Unicode system described below. Some Oriental languages such as Chinese and Japanese contain more than 256 characters (in fact, about 4000 characters are needed to represent each of these languages). To accommodate these languages and all of the other languages in the world, a coding system called Unicode2 has been developed. In the Unicode cod- ing system, each character is stored in 2 bytes of memory, so the Unicode system supports 65,536 possible different characters. The first 128 Unicode characters are identical to the ­ ASCII character set, and other blocks of characters are devoted to various languages such as Chinese, Japanese, Hebrew, Arabic, and Hindi. When the Unicode coding system is used, character data can be represented in any ­language. Integer Data The integer data type consists of the positive integers, the negative integers, and zero. The amount of memory devoted to storing an integer will vary from computer to computer, but will usually be 1, 2, 4, or 8 bytes. Four-byte integers are the most com- mon type in modern computers. Since a finite number of bits are used to store each value, only integers that fall within a certain range can be represented on a computer. Usually, the smallest number that can be stored in an n-bit integer is Smallest integer value = −2n−1 (1-1) and the largest number that can be stored in an n-bit integer is Largest integer value = 2n−1 − 1 (1-2) For a 4-byte integer, the smallest and largest possible values are −2,147,483,648 and 2,147,483,647, respectively. Attempts to use an integer larger than the largest possible 2 Also referred to by the corresponding standard number, ISO/IEC 10646:2014.
  • 31. 10 chapter 1:   Introduction to Computers and the Fortran Language 1 value or smaller than the smallest (most negative) possible value result in an error called an overflow condition.3 Real Data The integer data type has two fundamental limitations: 1. It is not possible to represent numbers with fractional parts (0.25, 1.5, 3.14159, etc.) as integer data. 2. It is not possible to represent very large positive integers or very small negative integers, because there are not enough bits available to represent the value. The largest and smallest possible integers that can be stored in a given memory loca- tion will be given by Equations (1-1) and (1-2). To get around these limitations, computers include a real or floating-point data type. The real data type stores numbers in a type of scientific notation. We all know that very large or very small numbers can be most conveniently written in scientific notation. For example, the speed of light in a vacuum is about 299,800,000 m/s. This number is easier to work with in scientific notation: 2.998 × 108 m/s. The two parts of a number expressed in scientific notation are called the mantissa and the ­ exponent. The mantissa of the number above is 2.998, and the exponent (in the base 10 system) is 8. The real numbers in a computer are similar to the scientific notation above, except that a computer works in the base 2 system instead of the base 10 system. Real num- bers usually occupy 32 bits (4 bytes) of computer memory, divided into two compo- nents: a 24-bit mantissa and an 8-bit exponent (Figure 1-3).4 The mantissa contains a number between −1.0 and 1.0, and the exponent contains the power of 2 required to scale the number to its actual value. Real numbers are characterized by two quantities: precision and range. ­ Precision is the number of significant digits that can be preserved in a number, and range is the difference between the largest and smallest numbers that can be ­ represented. The precision of a real number depends on the number of bits in its mantissa, while the range of the number depends on the number of bits in its expo- nent. A 24-bit mantissa can represent approximately ±223 numbers, or about seven significant decimal digits, so the precision of real numbers is about seven significant digits. An 8-bit ­ exponent can represent multipliers between 2−128 and 2127 , so the range of real numbers is from about 10−38 to 1038 . Note that the real data type can represent numbers much larger or much smaller than integers can, but only with seven significant digits of precision. 3 When an overflow condition occurs, some processors will abort the program causing the overflow condi- tion. Other processors will “wrap around” from the most positive integer to the most negative integer with- out giving the user a warning that anything has happened. This behavior varies for different types of computers. 4 This discussion is based on the IEEE Standard 754 for floating-point numbers, which is representative of most modern computers.
  • 32. Introduction to Computers and the Fortran Language 11 1 When a value with more than seven digits of precision is stored in a real vari- able, only the most significant 7 bits of the number will be preserved. The ­ remaining information will be lost forever. For example, if the value 12,345,678.9 is stored in a real variable on a PC, it will be rounded off to 12,345,680.0. This difference ­ between the original value and the number stored in the computer is known as ­ round-off error. You will use the real data type in many places throughout this book and in your programs after you finish this course. It is quite useful, but you must always remember the limitations associated with round-off error, or your programs might give you an unpleasant surprise. For example, if your program must be able to distinguish between the numbers 1,000,000.0 and 1,000,000.1, then you cannot use the standard real data type.5 It simply does not have enough precision to tell the difference between these two numbers! FIGURE 1-3 This floating-point number includes a 24-bit mantissa and an 8-bit exponent. Value = mantissa × 2exponent 10 20 30 Mantissa Exponent mmmmmmmmmmmmmmmmmmmmmmmmeeeeeeee 5 We will learn how to use high-precision floating-point numbers in Chapter 11. Programming Pitfalls Always remember the precision and range of the data types that you are working with. Failure to do so can result in subtle programming errors that are very hard to find. Quiz 1-1 This quiz provides a quick check to see if you have understood the concepts intro- duced in Section 1.2. If you have trouble with the quiz, reread the section, ask your instructor, or discuss the material with a fellow student. The answers to this quiz are found in the back of the book. 1. Express the following decimal numbers as their binary equivalents: (a) 2710 (b) 1110 (c) 3510 (d) 12710 (continued)
  • 33. Random documents with unrelated content Scribd suggests to you:
  • 34. Greensleeves was my delight! Greensleeves was my heart of gold! And who but my Lady Greensleeves! Greensleeves now farewell! adieu! God I pray to prosper thee! For I am still thy lover true: Come once again and love me! Greensleeves was all my joy! Greensleeves was my delight! Greensleeves was my heart of gold! And who but my Lady Greensleeves!
  • 35. MY TRUE LOVE SIR PHILIP SIDNEY My true love hath my heart, and I have his, By just exchange one for another given: I hold his dear, and mine he cannot miss; There never was a better bargain driven: My true love hath my heart, and I have his. His heart in me keeps him and me in one, My heart in him his thoughts and senses guides: He loves my heart, for once it was his own, I cherish his because in me it bides: My true love hath my heart, and I have his.
  • 36. DIRGE JOHN WEBSTER Call for the robin-redbreast and the wren, Since o'er shady groves they hover, And with leaves and flowers do cover The friendless bodies of unburied men. Call unto his funeral dole The ant, the field-mouse, and the mole, To rear him hillocks that shall keep him warm, And (when gay tombs are robb'd) sustain no harm; But keep the wolf far thence, that's foe to men, For with his nails he'll dig them up again.
  • 37. THE SHROUDING Hark! now everything is still, The screech-owl and the whistler shrill, Call upon our dame aloud, And bid her quickly don her shroud! Much you had of land and rent; Your length in clay's now competent: A long war disturb'd your mind; Here your perfect peace is sign'd. Of what is 't fools make such vain keeping? Sin their conception, their birth weeping, Their life a general mist of error, Their death a hideous storm of terror. Strew your hair with powders sweet, Don clean linen, bathe your feet, And—the foul fiend more to check— A crucifix let bless your neck; 'Tis now full tide 'tween night and day; End your groan and come away.
  • 38. CONTENT THOMAS DEKKER Art thou poor, yet hast thou golden slumbers? O sweet content! Art thou rich, yet is thy mind perplex'd? O punishment! Dost thou laugh to see how fools are vex'd To add to golden numbers, golden numbers? O sweet content! O sweet, O sweet content! Work apace, apace, apace, apace; Honest labour bears a lovely face; Then hey nonny nonny, hey nonny nonny! Canst drink the waters of the crispèd spring? O sweet content! Swimm'st thou in wealth, yet sink'st in thine own tears? O punishment! Then he that patiently want's burden bears No burden bears, but is a king, a king! O sweet content! O sweet, O sweet content! Work apace, apace, apace, apace; Honest labour bears a lovely face; Then hey nonny nonny, hey nonny nonny!
  • 39. TROLL THE BOWL Cold's the wind, and wet's the rain, Saint Hugh be our good speed! Ill is the weather that bringeth no gain, Nor helps good hearts in need. Troll the bowl, the jolly nut-brown bowl, And here, kind mate, to thee! Let's sing a dirge for Saint Hugh's soul, And down it merrily. Down-a-down, hey, down-a-down, Hey derry derry down-a-down. Ho! well done, to let me come, Ring compass, gentle joy! Troll the bowl, the nut-brown bowl, And here, kind mate, to thee! Let's sing a dirge for Saint Hugh's soul, And down it merrily. Cold's the wind, and wet's the rain, Saint Hugh be our good speed! Ill is the weather that bringeth no gain, Nor helps good hearts in need.
  • 40. SIR PATRICK SPENS ANONYMOUS The king sits in Dunfermline toun, Drinking the blude-red wine; 'Oh whare will I get a gude sailor, To sail this ship o' mine?' Then up and spake an eldern knight Sat at the king's right knee; 'Sir Patrick Spens is the best sailor That ever sail'd the sea.' The king has written a braid letter, And seal'd it wi' his hand, And sent it to Sir Patrick Spens Was walking on the strand. 'To Noroway, to Noroway, To Noroway o'er the faem; The king's daughter to Noroway, 'Tis thou maun tak' her hame.' The first line that Sir Patrick read, A loud laugh laughed he; The neist line that Sir Patrick read, The tear blinded his ee. 'O wha is this has done this deed,
  • 41. And tauld the king o' me, To send us out at this time o' the year, To sail upon the sea?' 'Be 't wind or weet, be't hail or sleet, Our ship maun sail the faem; The king's daughter to Noroway, 'Tis we maun tak' her hame.' They hoisted their sails on Monenday morn, Wi' a' the speed they may; And they hae landed in Noroway Upon a Wodensday. They hadna been a week, a week, In Noroway but twae, When that the lords o' Noroway Began aloud to say— 'Ye Scotisman spend a' our king's gowd, And a' our queenis fee.' 'Ye lee, ye lee, ye leears loud, Sae loud's I hear ye lee! 'For I brought as much o' the white monie As gane my men and me, And a half-fou o' the gude red gowd, Out owre the sea with me. 'Mak' ready, mak' ready, my merry men a', Our gude ship sails the morn.' 'O say na sae, my master dear, I fear a deadlie storm. 'I saw the new moon late yestreen, Wi' the auld moon in her arm; And if we gang to sea, master,
  • 42. I fear we'll come to harm!' They hadna sail'd a league, a league, A league but barely three, When the lift grew dark, and the wind blew loud And gurly grew the sea. The ankers brak, and the tap-masts lap, It was sic a deadlie storm; And the waves cam' owre the broken ship, Till a' her sides were torn. 'O whare will I get a gude sailor Will tak' the helm in hand, Till I get up to the tall tap-mast, To see if I can spy land.' 'O here am I, a sailor gude, To tak' the helm in hand, Till ye get up to the tall tap-mast, But I fear ye'll ne'er spy land.' He hadna gane a step, a step, A step but barely ane, When a bout flew out o' the gude ship's side, And the saut sea it cam' in. 'Gae, fetch a web o' the silken claith, Anither o' the twine, And wap them into our gude ship's side, And letna the sea come in.' They fetch'd a wab o' the silken claith, Anither o' the twine, And they wapp'd them into the gude ship's side, But aye the sea cam' in.
  • 43. O laith, laith were our Scots lords' sons To weet their coal-black shoon, But lang ere a' the play was play'd, They wat their hats abune. And mony was the feather-bed That fluttered on the faem, And mony was the gude lord's son That never mair cam' hame. O lang, lang may the ladies sit, Wi' their fans into their hand, Before they see Sir Patrick Spens Come sailing to the strand. And lang, lang may the maidens sit, Wi' the gowd kaims in their hair, A' waiting for their ain dear loves, For them they'll see nae mair. Half owre, half owre to Aberdour 'Tis fifty fathom deep, And there lies gude Sir Patrick Spens Wi' the Scots lords at his feet.
  • 44. THE BEGGAR'S DAUGHTER OF BEDNALL-GREEN PART I It was a blind beggar, had long lost his sight, He had a fair daughter of beauty most bright; And many a gallant brave suitor had she, For none was so comely as pretty Bessee. And though she was of favour most faire, Yet seeing she was but a poor beggar's heyre, Of ancyent housekeepers despised was she, Whose sons came as suitors to pretty Bessee. Wherefore in great sorrow fair Bessy did say, Good father, and mother, let me go away To seek out my fortune, whatever it be, This suite then they granted to pretty Bessee. Then Bessy, that was of beauty so bright, All cladd in grey russet, and late in the night From father and mother alone parted she, Who sighed and sobbed for pretty Bessee. She went till she came to Stratford-le-Bow; Then knew she not whither, nor which way to go: With tears she lamented her hard destinìe, So sad and so heavy was pretty Bessee. She kept on her journey until it was day,
  • 45. And went unto Rumford along the high way; Where at the Queen's arms entertained was she: So fair and well-favoured was pretty Bessee. She had not been there a month to an end, But master and mistress and all was her friend: And every brave gallant, that once did her see, Was straightway enamour'd of pretty Bessee. Great gifts they did send her of silver and gold, And in their songs daily her love was extolled; Her beauty was blazed in every degree; So fair and so comely was pretty Bessee. The young men of Rumford in her had their joy She showed herself courteous, and modestly coy; And at her commandment still would they be; So fair and so comely was pretty Bessee. Four suitors at once unto her did go; They craved her favour, but still she said no; I would not wish gentles to marry with me; Yet ever they honoured pretty Bessee. The first of them was a gallant young knight, And he came unto her disguised in the night: The second a gentleman of good degree, Who wooed and sued for pretty Bessee. A merchant of London, whose wealth was not small, He was the third suitor, and proper withal: Her master's own son the fourth man must be, Who swore he would die for pretty Bessee. And, if thou wilt marry with me, quoth the knight, I'll make thee a lady with joy and delight; My heart's so enthralled by thy beautie,
  • 46. That soon I shall die for pretty Bessee. The gentleman said, Come, marry with me, As fine as a lady my Bessy shall be: My life is distressed: O hear me, quoth he; And grant me thy love, my pretty Bessee. Let me be thy husband, the merchant did say, Thou shalt live in London both gallant and gay; My ships shall bring home rich jewels for thee, And I will for ever love pretty Bessee. Then Bessy she sighed, and thus she did say, My father and mother I mean to obey; First get their good will, and be faithful to me, And then you shall marry your pretty Bessee. To every one this answer she made, Wherefore unto her they joyfully said, This thing to fulfil we all do agree; But where dwells thy father, my pretty Bessee? My father, she said, is soon to be seen: The silly blind beggar of Bednall-green, That daily sits begging for charitìe, He is the good father of pretty Bessee. His marks and his tokens are known very well; He always is led with a dog and a bell: A silly old man, God knoweth, is he, Yet he is the father of pretty Bessee. Nay then, quoth the merchant, thou art not for me. Nor, quoth the innholder, my wife thou shalt be: I loth, said the gentle, a beggar's degree, And therefore adieu, my pretty Bessee.
  • 47. Why then, quoth the knight, hap better or worse, I weigh not true love by the weight of the purse, And beauty is beauty in every degree; Then welcome unto me, my pretty Bessee. With thee to thy father forthwith I will go. Nay soft, quoth his kinsmen, it must not be so; A poor beggar's daughter no lady shall be, Then take thy adieu of pretty Bessee. But soon after this, by break of the day The knight had from Rumford stole Bessy away. The young men of Rumford, as thick as might be, Rode after to fetch again pretty Bessee. As swift as the wind to ryde they were seen, Until they came near unto Bednall-green; And as the knight lighted most courteouslìe, They all fought against him for pretty Bessee. But rescue came speedily over the plain, Or else the young knight for his love had been slain. This fray being ended, then straightway he see His kinsmen come railing at pretty Bessee. Then spake the blind beggar, Although I be poor, Yet rail not against my child at my own door: Though she be not decked in velvet and pearl, Yet will I drop angels with you for my girl. And then, if my gold may better her birth, And equal the gold that you lay on the earth, Then neither rail nor grudge you to see The blind beggar's daughter a lady to be. But first you shall promise, and have it well known, The gold that you drop shall all be your own.
  • 48. With that they replied, Contented be we. Then here's, quoth the beggar, for pretty Bessee. With that an angel he cast on the ground, And dropped in angels full three thousand pound; And oftentimes it was proved most plain, For the gentlemen's one the beggar dropt twain: So that the place, wherein they did sit, With gold it was covered every whit. The gentlemen then having dropt all their store, Said, Now, beggar, hold, for we have no more, Thou hast fulfilled thy promise aright. Then marry, quoth he, my girl to this knight; And here, added he, I will now throw you down A hundred pounds more to buy her a gown. The gentlemen all, that this treasure had seen, Admired the beggar of Bednall-green: And all those, that were her suitors before, Their flesh for very anger they tore. Thus was fair Bessy matched to the knight, And then made a lady in others' despite: A fairer lady there never was seen, Than the blind beggar's daughter of Bednall-green. But of their sumptuous marriage and feast, What brave lords and knights thither were prest, The second fitt shall set forth to your sight With marvellous pleasure and wished delight. PART II Of a blind beggar's daughter most bright, That late was betrothed unto a young knight;
  • 49. All the discourse thereof you did see: But now comes the wedding of pretty Bessee. Within a gorgeous palace most brave, Adorned with all the cost they could have, This wedding was kept most sumptuouslìe, And all for the credit of pretty Bessee. All kind of dainties and delicates sweet Were bought for the banquet, as it was most meet; Partridge, and plover, and venison most free, Against the brave wedding of pretty Bessee. This marriage through England was spread by report, So that a great number thereto did resort Of nobles and gentles in every degree; And all for the fame of pretty Bessee. To church then went this gallant young knight; His bride followed after, an angel most bright, With troops of ladies, the like ne'er was seen, As went with sweet Bessy of Bednall-green. This marriage being solemnized then, With musick performed by the skilfullest men, The nobles and gentles sat down at that tide, Each one admiring the beautiful bride. Now, after the sumptuous dinner was done, To talk, and to reason a number begun: They talked of the blind beggar's daughter most bright, And what with his daughter he gave to the knight. Then spake the nobles, 'Much marvel have we, This jolly blind beggar we cannot here see.' My lords, quoth the bride, my father's so base, He is loth with his presence these states to disgrace.
  • 50. 'The praise of a woman in question to bring Before her own face, were a flattering thing, But we think thy father's baseness,' quoth they, 'Might by thy beauty be clean put away.' They had no sooner these pleasant words spoke, But in comes the beggar clad in a silk cloak; A fair velvet cap, and a feather had he, And now a musician forsooth he would be. He had a dainty lute under his arm, He touched the strings, which made such a charm, Says, Please you to hear any musick of me, I'll sing you a song of pretty Bessee. With that his lute he twanged straightway, And thereon began most sweetly to play; And after that lessons were played two or three, He strain'd out this song most delicatelìe. 'A poor beggar's daughter did dwell on a green, Who for her fairness might well be a queen: A blithe bonny lass, and a dainty was she, And many one called her pretty Bessee. 'Her father he had no goods, nor no land, But begged for a penny all day with his hand; And yet to her marriage he gave thousands three, And still he hath somewhat for pretty Bessee. 'And if any one here her birth do disdain, Her father is ready, with might and with main, To prove she is come of noble degree: Therefore never flout at pretty Bessee.' With that the lords and the company round With hearty laughter were ready to swound;
  • 51. At last said the lords, Full well we may see, The bride and the beggar's beholden to thee. On this the bride all blushing did rise, The pearly drops standing within her fair eyes, O pardon my father, grave nobles, quoth she, That through blind affection thus doteth on me. If this be thy father, the nobles did say, Well may he be proud of this happy day; Yet by his countenance well may we see, His birth and his fortune did never agree: 'And therefore, blind man, we pray thee bewray (And look that the truth thou to us do say) Thy birth and thy parentage, what it may be; For the love that thou bearest to pretty Bessee.' 'Then give me leave, nobles and gentles, each one, One song more to sing, and then I have done; And if that it may not win good report, Then do not give me a groat for my sport. 'Sir Simon de Montfort my subject shall be; Once chief of all the great barons was he, Yet fortune so cruel this lord did abase, Now lost and forgotten are he and his race. 'When the barons in arms did king Henry oppose, Sir Simon de Montfort their leader they chose; A leader of courage undaunted was he, And oft-times he made their enemies flee. 'At length in the battle on Evesham plain, The barons were routed, and Montfort was slain; Most fatal that battle did prove unto thee, Though thou wast not born then, my pretty Bessee!
  • 52. 'Along with the nobles, that fell at that tide, His eldest son Henry, who fought by his side, Was felled by a blow he received in the fight; A blow that deprived him for ever of sight. 'Among the dead bodies all lifeless he lay, Till evening drew on of the following day, When by a young lady discovered was he; And this was thy mother, my pretty Bessee! 'A baron's fair daughter stept forth in the night To search for her father, who fell in the fight, And seeing young Montfort, where gasping he lay, Was moved with pity, and brought him away. 'In secret she nurst him, and swaged his pain, While he through the realm was believed to be slain: At length his fair bride she consented to be, And made him glad father of pretty Bessee. 'And now, lest our foes our lives should betray, We clothed ourselves in beggars' array; Her jewels she sold, and hither came we: All our comfort and care was our pretty Bessee. 'And here have we lived in fortune's despite, Though poor, yet contented with humble delight: Full forty winters thus have I been A silly blind beggar of Bednall-green. 'And here, noble lords, is ended the song Of one, that once to your own rank did belong: And thus have you learned a secret from me, That ne'er had been known, but for pretty Bessee.' Now when the fair company every one, Had heard the strange tale in the song he had shown,
  • 53. They all were amazed, as well they might be, Both at the blind beggar, and pretty Bessee. With that the fair bride they all did embrace, Saying, Sure thou art come of an honourable race Thy father likewise is of noble degree, And thou art well worthy a lady to be. Thus was the feast ended with joy and delight, A bridegroom most happy then was the young knight, In joy and felicitie long lived he, All with his fair lady, the pretty Bessee.
  • 54. THE BABES IN THE WOOD Now ponder well, you parents dear, These words, which I shall write; A doleful story you shall hear, In time brought forth to light. A gentleman of good account In Norfolk dwelt of late, Who did in honour far surmount Most men of his estate. Sore sick he was, and like to die, No help his life could save; His wife by him as sick did lie, And both possest one grave. No love between these two was lost, Each was to other kind, In love they liv'd, in love they died, And left two babes behind: The one a fine and pretty boy, Not passing three yeares old; The other a girl more young than he, And fram'd in beauty's mould. The father left his little son, As plainly doth appeare, When he to perfect age should come, Three hundred pounds a yeare. And to his little daughter Jane Five hundred pounds in gold, To be paid down on marriage-day,
  • 55. Which might not be controll'd: But if the children came to die, Ere they to age should come, Their uncle should possesse their wealth; For so the will did run. Now, brother, said the dying man, Look to my children dear; Be good unto my boy and girl, No friends else have they here: To God and you I recommend My children dear this daye; But little while be sure we have Within this world to stay. You must be father and mother both, And uncle all in one; God knows what will become of them, When I am dead and gone. With that bespake their mother dear, O brother kind, quoth she, You are the man must bring our babes To wealth or miserie: And if you keep them carefully, Then God will you reward; But if you otherwise should deal, God will your deeds regard. With lips as cold as any stone, They kist their children small: God bless you both, my children dear; With that the tears did fall. These speeches then their brother spake To this sick couple there, The keeping of your little ones,
  • 56. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! textbookfull.com