SlideShare a Scribd company logo
Download the full version and explore a variety of ebooks
or textbooks at https://ebookmass.com
Fortran for Scientists and Engineers 4th Edition
Stephen J. Chapman
_____ Follow the link below to get your download now _____
https://ebookmass.com/product/fortran-for-scientists-and-
engineers-4th-edition-stephen-j-chapman/
Access ebookmass.com now to download high-quality
ebooks or textbooks
We have selected some products that you may be interested in
Click the link to download now or visit ebookmass.com
for more options!.
MATLAB Programming for Engineers 6th Edition Stephen J.
Chapman
https://ebookmass.com/product/matlab-programming-for-engineers-6th-
edition-stephen-j-chapman/
Modern Physics for Scientists and Engineers 5th Edition
Stephen Thornton & Andrew Rex
https://ebookmass.com/product/modern-physics-for-scientists-and-
engineers-5th-edition-stephen-thornton-andrew-rex/
Technical Writing for Engineers & Scientists, 4th Edition
Leo Finkelstein
https://ebookmass.com/product/technical-writing-for-engineers-
scientists-4th-edition-leo-finkelstein/
Technical Writing for Engineers & Scientists 4th Edition
Leo Finkelstein
https://ebookmass.com/product/technical-writing-for-engineers-
scientists-4th-edition-leo-finkelstein-2/
Physics for Scientists and Engineers with Modern Physics
4th Edition Douglas C. Giancoli
https://ebookmass.com/product/physics-for-scientists-and-engineers-
with-modern-physics-4th-edition-douglas-c-giancoli/
eTextbook 978-0131495081 Physics for Scientists &
Engineers with Modern Physics (4th Edition)
https://ebookmass.com/product/etextbook-978-0131495081-physics-for-
scientists-engineers-with-modern-physics-4th-edition/
Physics for Scientists and Engineers 9th Edition, (Ebook
PDF)
https://ebookmass.com/product/physics-for-scientists-and-
engineers-9th-edition-ebook-pdf/
Statistics for Engineers and Scientists 5th Edition
William Navidi
https://ebookmass.com/product/statistics-for-engineers-and-
scientists-5th-edition-william-navidi-2/
Statistics for Engineers and Scientists, 6th Edition
William Navidi
https://ebookmass.com/product/statistics-for-engineers-and-
scientists-6th-edition-william-navidi-2/
Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman
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)
12 chapter 1:   Introduction to Computers and the Fortran Language
1
1.3
COMPUTER LANGUAGES
When a computer executes a program, it executes a string of very simple operations
such as load, store, add, subtract, multiply, and so on. Each such operation has a unique
binary pattern called an operation code (op code) to specify it. The program that a com-
puter executes is just a string of op codes (and the data associated with the op codes6
) in
the order necessary to achieve a purpose. Op codes are collectively called machine
language, since they are the actual language that a computer recognizes and executes.
Unfortunately, we humans find machine language very hard to work with. We
prefer to work with English-like statements and algebraic equations that are expressed
in forms familiar to us, instead of arbitrary patterns of zeros and ones. We like to pro-
gram computers with high-level languages. We write out our instructions in a high-
level language, and then use special programs called compilers and linkers to convert
the instructions into the machine language that the computer understands.
(concluded)
2. Express the following binary numbers as their decimal equivalents:
(a) 11102
(b) 010101012
(c) 10012
3. Express the following binary numbers as octal and hexadecimal numbers:
(a) 11100101101011012
(b) 11101111012
(c) 10010111001111112
4. Is the fourth bit of the number 13110
a 1 or a 0?
5. Assume that the following numbers are the contents of a character variable.
Find the character corresponding to each number according to the ASCII
encoding scheme (The character codes in the ASCII encoding scheme are
defined in Appendix A):
(a) 7710
(b) 011110112
(c) 24910
6. Find the maximum and minimum values that can be stored in a 2-byte
­integer variable.
7. Can a 4-byte variable of the real data type be used to store larger numbers
than a 4-byte variable of the integer data type? Why or why not? If it can,
what is given up by the real variable to make this possible?
6
The data associated with op codes is called operands.
Introduction to Computers and the Fortran Language 13
1
There are many different high-level languages, with different characteristics.
Some of them are designed to work well for business problems, while others are
­
designed for general scientific use. Still others are especially suited for applications
like operating systems programming. It is important to pick a proper language to match
the problem that you are trying to solve.
Some common high-level computer languages today include Ada, C, C++, ­
Fortran,
and Java. Historically, Fortran has been the pre-eminent language for general scientific
computations. It has been around in one form or another for more than 60 years, and has
been used to implement everything from computer models of nuclear power plants to
aircraft design programs to seismic signal processing systems, including some projects
requiring literally millions of lines of code. The language is especially useful for numer-
ical analysis and technical calculations. In addition, Fortran is the dominant language in
the world of supercomputers and massively parallel computers.
1.4
THE HISTORY OF THE FORTRAN LANGUAGE
Fortran is the grandfather of all scientific computer languages. The name Fortran is
derived from FORmula TRANSlation, indicating that the language was intended from
the start for translating scientific equations into computer code. The first version of the
FORTRAN7
language was developed during the years 1954–1957 by IBM for use with
its Type 704 computer (see Figure 1-4). Before that time, essentially all computer pro-
grams were generated by hand in machine language, which was a slow, tedious, and
error-prone process. FORTRAN was a truly revolutionary product. For the first time,
a programmer could write a desired algorithm as a series of standard algebraic equa-
tions, and the FORTRAN compiler would convert the statements into the machine
language that the computer could recognize and execute.
7
Versions of the language before Fortran 90 were known as FORTRAN (written with all capital letters),
while Fortran 90 and later versions are known as Fortran (with only the first letter capitalized).
THE IBM TYPE 704 COMPUTER
The IBM Type 704 computer was the first computer ever to use the FORTRAN lan-
guage. It was released in 1954, and was widely used from then until about 1960, when
it was replaced by the Model 709. As you can see from Figure 1-4, the computer occu-
pied a whole room.
What could a computer like that do in 1954? Not much, by today’s standards. Any
PC sitting on a desktop can run rings around it. The 704 could perform about
4000 ­
integer multiplications and divisions per second, and an average of about 8000
­
floating-point operations per second. It could read data from magnetic drums
14 chapter 1:   Introduction to Computers and the Fortran Language
1
FIGURE 1-4
The IBM Type 704 computer. (© Bettmann/Getty Images)
(the equivalent of a disk drive) into memory at a rate of about 50,000 bytes per second.
The amount of data storage available on a magnetic drum was also very small, so most
programs that were not currently in use were stored as decks of punched cards.
By comparison, a typical modern personal computer (circa 2006) performed more than
20,000,000,000 integer multiplications and divisions per second, and hundreds of millions
of floating-point operations per second. Some of today’s workstations are small enough to
sit on a desktop, and yet can perform more than 5,000,000,000 floating-point operations per
second! Reads from disk into memory occur at rates greater than 25,000,000 bytes per
second, and a typical PC disk drive can store more than 200,000,000,000 bytes of data.
The limited resources available in the 704 and other machines of that generation
placed a great premium on efficient programming. The structured programming tech-
niques that we use today were simply not possible, because there was not enough
speed or memory to support them. The earliest versions of FORTRAN were designed
with those limitations in mind, which is why we find many archaic features preserved
as living fossils in modern versions of Fortran.
Introduction to Computers and the Fortran Language 15
1
FORTRAN was a wonderful idea! People began using it as soon as it was avail-
able, because it made programming so much easier than machine language did. The
language was officially released in April 1957, and by the fall of 1958, more than half
of all IBM 704 computer programs were being written in Fortran.
The original FORTRAN language was very small compared to our modern ver-
sions of Fortran. It contained only a limited number of statement types, and supported
only the integer and real data types. There were also no subroutines in the first
­
FORTRAN. It was a first effort at writing a high-level computer language, and natu-
rally many deficiencies were found as people started using the language regularly.
IBM addressed those problems, releasing FORTRAN II in the spring of 1958.
Further developments continued through 1962, when FORTRAN IV was released.
FORTRAN IV was a great improvement, and it became the standard version of ­
Fortran
for the next 15 years. In 1966, FORTRAN IV was adopted as an ANSI standard, and it
came to be known as FORTRAN 66.
The Fortran language received another major update in 1977. FORTRAN 77
­
included many new features designed to make structured programs easier to write and
maintain, and it quickly became “the” Fortran. FORTRAN 77 introduced such struc-
tures as the block IF, and was the first version of Fortran in which character variables
were truly easy to manipulate.
The next major update of Fortran was Fortran 90.8
Fortran 90 included all of
­
FORTRAN 77 as a subset, and extended the language in many important new direc-
tions. Among the major improvements introduced to the language in Fortran 90 were
a new free source format, array sections, whole-array operations, parameterized data
types, derived data types, and explicit interfaces. Fortran 90 was a dramatic improve-
ment over earlier versions of the language.
Fortran 90 was followed in 1996 by a minor update called Fortran 95. Fortran 95
added a number of new features to the language such as the FORALL construct, pure
functions, and some new intrinsic procedures. In addition, it clarified numerous ambi-
guities in the Fortran 90 standard.
Fortran 2003 was the next update.9
This is a more major change from Fortran 95,
including new features such as enhanced derived types, object-oriented programming
support, Unicode character set support, data manipulation enhancements, procedure
pointers, and interoperability with the C language. It was followed by a more minor
update called Fortran 2008.
The subject of this book is the Fortran 2008 language. The designers of Fortran
2008 were careful to make the language backward compatible with FORTRAN 77 and
earlier versions. Because of this backward compatibility, most of the millions of pro-
grams written in FORTRAN 77 also work with Fortran 2008. Unfortunately, being
backward compatible with earlier versions of Fortran required that Fortran 2008 retain
some archaic features that should never be used in any modern program. In this book,
8
American National Standard Programming Language Fortran, ANSI X3.198-1992; and International
Standards Organization ISO/IEC 1539: 1991, Information Technology—Programming Languages—­
Fortran.
9
International Standards Organization ISO/IEC 1539: 2004, Information Technology—Programming
­Languages—Fortran.
16 chapter 1:   Introduction to Computers and the Fortran Language
1
we will learn to program in Fortran using only its modern features. The older features
that are retained for backward compatibility are relegated to Chapter 18 of this book.
They are described there in case you run into any of them in older programs, but they
should never be used in any new program.
1.5
THE EVOLUTION OF FORTRAN
The Fortran language is a dynamic language that is constantly evolving to keep up
with advances in programming practice and computing technology. A major new ver-
sion appears about once per decade.
The responsibility for developing new versions of the Fortran language lies with
the International Organization for Standardization’s (ISO) Fortran Working Group,
WG5. That organization has delegated authority to the J3 Committee of the
­
InterNational Committee for Information Technology Standards (INCITS) to actually
prepare new versions of the language. The preparation of each new version is an
­
extended process involving first asking for suggestions for inclusion in the language,
deciding which suggestions are feasible to implement, writing and circulating drafts
to all interested parties throughout the world, and correcting the drafts and trying
again until general agreement is reached. Eventually, a worldwide vote is held and the
standard is adopted.
The designers of new versions of the Fortran language must strike a delicate
balance between backward compatibility with the existing base of Fortran programs
and the introduction of desirable new features. Although modern structured pro-
gramming features and approaches have been introduced into the language, many
undesirable features from earlier versions of Fortran have been retained for backward
compatibility.
The designers have developed a mechanism for identifying undesirable and
­
obsolete features of the Fortran language that should no longer be used, and for even-
tually eliminating them from the language. Those parts of the language that have
been superseded by new and better methods are declared to be obsolescent features.
Features that have been declared obsolescent should never be used in any new pro-
grams. As the use of these features declines in the existing Fortran code base, they
will then be considered for deletion from the language. No feature will ever be
­
deleted from a version of the language unless it was on the obsolescent list in at least
one previous version, and unless the usage of the feature has dropped off to negligi-
ble levels. In this fashion, the language can evolve without threatening the existing
Fortran code base.
The redundant, obsolescent, and deleted features of Fortran 2008 are described in
Chapter 18 in case a programmer runs into them in existing programs, but they should
never be used in any new programs.
We can get a feeling for just how much the Fortran language has evolved over the
years by examining Figures 1-5 through 1-7. These three figures show programs for
calculating the solutions to the quadratic equation ax2
+ bx + c = 0 in the styles of
the original FORTRAN I, of FORTRAN 77, and of Fortran 2008. It is obvious that the
Introduction to Computers and the Fortran Language 17
1
language has become more readable and structured over the years. Amazingly, though,
Fortran 2008 compilers will still compile the FORTRAN I program with just a few
minor changes!10
FIGURE 1-5
A FORTRAN I program to solve for the roots of the quadratic equation ax2
+ bx + c = 0.
C SOLVE QUADRATIC EQUATION IN FORTRAN I
READ 100,A,B,C
100 FORMAT(3F12.4)
DISCR = B**2-4*A*C
IF (DISCR) 10,20,30
10 X1=(-B)/(2.*A)
X2=SQRTF(ABSF(DISCR))/(2.*A)
PRINT 110,X1,X2
110 FORMAT(5H X = ,F12.3,4H +i ,F12.3)
PRINT 120,X1,X2
120 FORMAT(5H X = ,F12.3,4H -i ,F12.3)
GOTO 40
20 X1=(-B)/(2.*A)
PRINT 130,X1
130 FORMAT(11H X1 = X2 = ,F12.3)
GOTO 40
30 X1=((-B)+SQRTF(ABSF(DISCR)))/(2.*A)
X2=((-B)-SQRTF(ABSF(DISCR)))/(2.*A)
PRINT 140,X1
140 FORMAT(6H X1 = ,F12.3)
PRINT 150,X2
150 FORMAT(6H X2 = ,F12.3)
40 CONTINUE
STOP 25252
FIGURE 1-6
A FORTRAN 77 program to solve for the roots of the quadratic equation ax2
+ bx + c = 0.
PROGRAM QUAD4
C
C This program reads the coefficients of a quadratic equation of
C the form
C A * X**2 + B * X + C = 0,
C and solves for the roots of the equation (FORTRAN 77 style).
C
C Get the coefficients of the quadratic equation.
C
WRITE (*,*) 'Enter the coefficients A, B and C: '
READ (*,*) A, B, C
C
C Echo the coefficients to make sure they are entered correctly.
C
(continued)
10
Change SQRTF to SQRT, ABSF to ABS, and add an END statement.
18 chapter 1:   Introduction to Computers and the Fortran Language
1
(concluded)
WRITE (*,100) 'The coefficients are : ', A, B, C
100 FORMAT (1X,A,3F10.4)
C
C Check the discriminant and calculate its roots.
C
DISCR = B**2 - 4.*A*C
IF ( DISCR .LT. 0) THEN
WRITE (*,*) ' This equation has complex roots:'
WRITE (*,*) ' X = ', -B/(2.*A), ' +i ', SQRT(ABS(DISCR))/(2.*A)
WRITE (*,*) ' X = ', -B/(2.*A), ' -i ', SQRT(ABS(DISCR))/(2.*A)
ELSE IF ( (B**2 - 4.*A*C) .EQ. 0) THEN
WRITE (*,*) ' This equation has a single repeated real root:'
WRITE (*,*) ' X = ', -B/(2.*A)
ELSE
WRITE (*,*) ' This equation has two distinct real roots:'
WRITE (*,*) ' X = ', (-B + SQRT(ABS(DISCR)))/(2.*A)
WRITE (*,*) ' X = ', (-B - SQRT(ABS(DISCR)))/(2.*A)
END IF
C
END
FIGURE 1-7
A Fortran 2008 program to solve for the roots of the quadratic equation ax2
+ bx + c = 0.
PROGRAM roots
! Purpose:
! This program solves for the roots of a quadratic equation of the form
! A * X**2 + B * X + C = 0. It calculates the answers regardless of the
! type of roots that the equation possesses (Fortran 95/2003 style).
!
IMPLICIT NONE
! Declare the variables used in this program
REAL :: a ! Coefficient of X**2 term of equation
REAL :: b ! Coefficient of X term of equation
REAL :: c ! Constant term of equation
REAL :: discriminant ! Discriminant of the equation
REAL :: imag_part ! Imaginary part of equation (for complex roots)
REAL :: real_part ! Real part of equation (for complex roots)
REAL :: x1 ! First solution of equation (for real roots)
REAL :: x2 ! Second solution of equation (for real roots)
! Prompt the user for the coefficients of the equation
WRITE (*,*) 'This program solves for the roots of a quadratic '
WRITE (*,*) 'equation of the form A * X**2 + B * X + C = 0. '
WRITE (*,*) 'Enter the coefficients A, B, and C:'
READ (*,*) a, b, c
! Echo back coefficients
WRITE (*,*) 'The coefficients A, B, and C are: ', a, b, c
(continued)
Introduction to Computers and the Fortran Language 19
1
(concluded)
! Calculate discriminant
discriminant = b**2 - 4. * a * c
! Solve for the roots, depending upon the value of the discriminant
IF ( discriminant  0. ) THEN ! there are two real roots, so...
X1 = ( -b + sqrt(discriminant) ) / ( 2. * a )
X2 = ( -b - sqrt(discriminant) ) / ( 2. * a )
WRITE (*,*) 'This equation has two real roots:'
WRITE (*,*) 'X1 = ', x1
WRITE (*,*) 'X2 = ', x2
ELSE IF ( discriminant == 0. ) THEN ! there is one repeated root, so...
x1 = ( -b ) / ( 2. * a )
WRITE (*,*) 'This equation has two identical real roots:'
WRITE (*,*) 'X1 = X2 = ', x1
ELSE ! there are complex roots, so ...
real_part = ( -b ) / ( 2. * a )
imag_part = sqrt ( abs ( discriminant ) ) / ( 2. * a )
WRITE (*,*) 'This equation has complex roots:'
WRITE (*,*) 'X1 = ', real_part, ' +i ', imag_part
WRITE (*,*) 'X2 = ', real_part, ' -i ', imag_part
END IF
END PROGRAM roots
1.6
SUMMARY
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 com-
puter what sequence of calculations is required, and which information to perform the
calculations on.
The major components of a computer are the central processing unit (CPU), cache
memory, main memory, secondary memory, and input and output devices. The CPU
performs all of the control and calculation functions of the computer. Cache memory
is very fact memory integrated directly on the CPU chip. Main memory is somewhat
slower memory that is used to store the program being executed and its associated
data. Main memory is volatile, meaning that its contents are lost whenever power is
turned off. Secondary memory is slower and cheaper than main memory. It is nonvol-
atile. Hard disks are common secondary memory devices. Input and output devices are
used to read data into the computer and to output data from the computer. The most
20 chapter 1:   Introduction to Computers and the Fortran Language
1
common input device is a keyboard, and the most common output devices are displays
or printers.
Computer memories are composed of millions of individual switches, each of which
can be ON or OFF, but not at a state in between. These individual switches are binary
devices called bits. Eight bits are grouped together to form a byte of memory, and 2 or
more bytes (depending on the computer) are grouped together to form a word of memory.
Computer memories can be used to store character, integer, or real data. Each character
in most character data sets occupies 1 byte of memory. The 256 possible values in the byte
allow for 256 possible character codes. (Characters in the Unicode character set occupy 2
bytes, allowing for 65,536 possible character codes.) Integer values occupy 1, 2, 4, or 8 bytes
of memory, and store integer quantities. Real values store numbers in a kind of scientific
notation. They usually occupy 4 bytes of memory. The bits are divided into a separate man-
tissa and exponent. The precision of the number depends upon the number of bits in the
mantissa, and the range of the number ­
depends upon the number of bits in the exponent.
The earliest computers were programmed in machine language. This process was
slow, cumbersome, and error-prone. High-level languages began to appear in about
1954, and they quickly replaced machine language coding for most uses. FORTRAN
was one of the first high-level languages ever created.
The FORTRAN I computer language and compiler were originally developed in
1954–1957. The language has since gone through many revisions, and a standard
mechanism has been created to evolve the language. This book teaches good program-
ming practices using the modern Fortran language.
1.6.1. Exercises
1-1. Express the following decimal numbers as their binary equivalents:
(a) 1010
(b) 3210
(c) 7710
(d) 6310
1-2. Express the following binary numbers as their decimal equivalents:
(a) 010010002
(b) 100010012
(c) 111111112
(d) 01012
1-3. Express the following numbers in both octal and hexadecimal forms:
(a) 10101110111100012
(b) 33010
(c) 11110
(d) 111111011012
Introduction to Computers and the Fortran Language 21
1
1-4. Express the following numbers in binary and decimal forms:
(a) 3778
(b) 1A816
(c) 1118
(d) 1FF16
1-5. Some computers (such as IBM mainframes) used to implement real data using a 23-bit
mantissa and a 9-bit exponent. What precision and range can we expect from real data on
these machines?
1-6. Some Cray supercomputers used to support 46-bit and 64-bit integer data types. What
are the maximum and minimum values that we could express in a 46-bit integer? in a
64-bit integer?
1-7. Find the 16-bit two’s complement representation of the following decimal numbers:
(a) 5510
(b) −510
(c) 102410
(d) −102410
1-8. Add the two’s complement numbers 00100100100100102
and 11111100111111002
­
using binary arithmetic. Convert the two numbers to decimal form, and add them as
decimals. Do the two answers agree?
1-9. The largest possible 8-bit two’s complement number is 011111112
, and the smallest pos-
sible 8-bit two’s complement number is 100000002
. Convert these numbers to decimal
form. How do they compare to the results of Equations (1-1) and (1-2)?
1-10. The Fortran language includes a second type of floating-point data known as double
precision. A double-precision number usually occupies 8 bytes (64 bits), instead of the
4 bytes occupied by a real number. In the most common implementation, 53 bits are
used for the mantissa and 11 bits are used for the exponent. How many significant digits
does a double-precision value have? What is the range of double-precision numbers?
22
2
Basic Elements of Fortran
OBJECTIVES
∙ Know which characters are legal in a Fortran statement.
∙ Know the basic structure of a Fortran statement and a Fortran program.
∙ Know the difference between executable and nonexecutable statements.
∙ Know the difference between constants and variables.
∙ Understand the differences among the INTEGER, REAL, and CHARACTER data
types.
∙ Learn the difference between default and explicit typing, and understand why
explicit typing should always be used.
∙ Know the structure of a Fortran assignment statement.
∙ Learn the differences between integer arithmetic and real arithmetic, and when
each one should be used.
∙ Know the Fortran hierarchy of operations.
∙ Learn how Fortran handles mixed-mode arithmetic expressions.
∙ Learn what intrinsic functions are, and how to use them.
∙ Know how to use list-directed input and output statements.
∙ Know why it is important to always use the IMPLICIT NONE statement.
2.1
INTRODUCTION
As engineers and scientists, we design and execute computer programs to accomplish
a goal. The goal typically involves technical calculations that would be too difficult or
take too long to be performed by hand. Fortran is one of the computer languages com-
monly used for these technical calculations.
This chapter introduces the basic elements of the Fortran language. By the end of
the chapter, we will be able to write simple but functional Fortran programs.
Basic Elements of Fortran 23
2
2.2
THE FORTRAN CHARACTER SET
Every language, whether it is a natural language such as English or a computer lan-
guage such as Fortran, Java, or C++, has its own special alphabet. Only the characters
in this alphabet may be used with the language.
The special alphabet used with the Fortran language is known as the Fortran
­character set. The Fortran character set consists of 97 characters, as shown in Table 2-1.
Note that the uppercase letters of the alphabet are equivalent to the lowercase ones
in the Fortran character set. (For example, the uppercase letter A is equivalent to the
lowercase letter a.) In other words, Fortran is case insensitive. This behavior is in con-
trast with such case sensitive languages as C++ and Java, in which A and a are two
totally different things.
2.3
THE STRUCTURE OF A FORTRAN STATEMENT
A Fortran program consists of a series of statements designed to accomplish the goal
of the programmer. There are two basic types of statements: executable statements
and nonexecutable statements. Executable statements describe the actions taken by
the program when it is executed (additions, subtractions, multiplications, divisions,
etc.), while nonexecutable statements provide information necessary for the proper
operation of the program. We will see many examples of each type of statement as we
learn more about the Fortran language.
Fortran statements may be entered anywhere on a line, and each line may be up to
132 characters long. If a statement is too long to fit onto a single line, then it may be
continued on the next line by ending the current line (and optionally starting the next
line) with an ampersand () character. For example, the following three Fortran
­
statements are identical:
output = input1 + input2 ! Sum the inputs
output = input1 
+ input2 ! Sum the inputs
TABLE 2-1
The Fortran character set
Number of symbols Type Values
26 Uppercase letters A-Z
26 Lowercase letters a-z
10 Digits 0-9
1 Underscore character _
5 Arithmetic symbols + - * / **
28 Miscellaneous symbols ( ) . = , ' $ : !  %  ; 
 ? ~  [ ] ` ^ { } | # @ and
blank
24 chapter 2:   Basic Elements of Fortran
2
999 output = input1  ! Sum the inputs
 + input2
Each of the statements specifies that the computer should add the two quantities stored
in input1 and input2 and save the result in output. A Fortran statement can be
continued over up to 256 lines, if required.
The last statement shown above starts with a number, known as a statement
label. A statement label can be any number between 1 and 99,999. It is the “name”
of a Fortran statement, and may be used to refer to the statement in other parts of
the program. Note that a statement label has no significance other than as a “name”
for the statement. It is not a line number, and it tells nothing about the order in
which statements are executed. Statement labels are rare in modern Fortran, and
most statements will not have one. If a statement label is used, it must be unique
within a given program unit. For example, if 100 is used as a statement label on one
line, it cannot be used again as a statement label on any other line in the same pro-
gram unit.
Any characters following an exclamation point are comments, and are ignored by
the Fortran compiler. All text from the exclamation point to the end of the line will be
ignored, so comments may appear on the same line as an executable statement.
­
Comments are very important, because they help us document the proper operation of
a program. In the third example above, the comment is ignored, so the ampersand is
treated by the compiler as the last character on the line.
2.4
THE STRUCTURE OF A FORTRAN PROGRAM
Each Fortran program consists of a mixture of executable and nonexecutable state-
ments, which must occur in a specific order. An example Fortran program is shown in
Figure 2-1. This program reads in two numbers, multiplies them together, and prints
out the result. Let’s examine the significant features of this program.
FIGURE 2-1
A simple Fortran program.
PROGRAM my_first_program
! Purpose:
! To illustrate some of the basic features of a Fortran program.
!
! Declare the variables used in this program.
INTEGER :: i, j, k ! All variables are integers
! Get two values to store in variables i and j
WRITE (*,*) 'Enter the numbers to multiply: '
READ (*,*) i, j
(continued)
Basic Elements of Fortran 25
2
(concluded)
! Multiply the numbers together
k = i * j
! Write out the result.
WRITE (*,*) 'Result = ', k
! Finish up.
STOP
END PROGRAM my_first_program
This Fortran program, like all Fortran program units,1
is divided into three
­sections:
1. The declaration section. This section consists of a group of nonexecutable state-
ments at the beginning of the program that define the name of the program and the
number and types of variables referenced in the program.
2. The execution section. This section consists of one or more statements describing
the actions to be performed by the program.
3. The termination section. This section consists of a statement or statements stop-
ping the execution of the program and telling the compiler that the program is
complete.
Note that comments may be inserted freely anywhere within, before, or after the
program.
2.4.1 The Declaration Section
The declaration section consists of the nonexecutable statements at the beginning of
the program that define the name of the program and the number and types of vari-
ables referenced in the program.
The first statement in this section is the PROGRAM statement. It is a nonexecutable
statement that specifies the name of the program to the Fortran compiler. Fortran
­
program names may be up to 63 characters long and contain any combination of alpha-
betic characters, digits, and the underscore (_) character. However, the first character
in a program name must always be alphabetic. If present, the PROGRAM statement must
be the first line of the program. In this example, the program has been named
my_first_program.
The next several lines in the program are comments that describe the purpose of
the program. Next comes the INTEGER type declaration statement. This nonexecutable
statement will be described later in this chapter. Here, it declares that three integer
variables called i, j, and k will be used in this program.
1
A program unit is a separately-compiled piece of Fortran code. We will meet several other types of pro-
gram units beginning in Chapter 7.
26 chapter 2:   Basic Elements of Fortran
2
2.4.2 The Execution Section
The execution section consists of one or more executable statements describing the
actions to be performed by the program.
The first executable statement in this program is the WRITE statement, which
writes out a message prompting the user to enter the two numbers to be multiplied
together. The next executable statement is a READ statement, which reads in the two
integers supplied by the user. The third executable statement instructs the computer to
multiply the two numbers i and j together, and to store the result in variable k. The
final WRITE statement prints out the result for the user to see. Comments may be
embedded anywhere throughout the execution section.
All of these statements will be explained in detail later in this chapter.
2.4.3 The Termination Section
The termination section consists of the STOP and END PROGRAM statements. The STOP
statement is a statement that tells the computer to stop running the program. The END
PROGRAM statement is a statement that tells the compiler that there are no more state-
ments to be compiled in the program.
The STOP statement takes one of the following forms:
STOP
STOP 3
STOP 'Error stop'
If the STOP statement is used by itself, execution will stop. If the STOP statement is
used with a number, that number will be printed out when the program stops, and will
normally be returned to the operating system as an error code. If the STOP statement is
used with a character string, that string will be printed out when the program stops.
When the STOP statement immediately precedes the END PROGRAM statement as in this
example, it is optional. The compiler will automatically generate a STOP command when the
END PROGRAM statement is reached. The STOP statement is therefore rarely used.2
There is an alternate version of the STOP statement called ERROR STOP. This ver-
sion stops the program, but it also notifies the operating system that the program failed
to execute properly. An example might be:
ERROR STOP 'Cannot access database'
This version of the STOP statement was added in Fortran 2008, and it might be useful
if you need to inform an operating system script that a program failed abnormally.
2
There is a philosophical disagreement among Fortran programmers about the use of the STOP statement.
Some programming instructors believe that it should always be used, even though it is redundant when
located before an END PROGRAM statement. They argue that the STOP statement makes the end of execu-
tion explicit. The author of this book is of the school that believes that a good program should only have
one starting point and one ending point, with no additional stopping points anywhere along the way. In that
case, a STOP is totally redundant and will never be used. Depending on the philosophy of your instructor,
you may or may not be encouraged to use this statement.
Basic Elements of Fortran 27
2
2.4.4 Program Style
This example program follows a commonly used Fortran convention of capitalizing
keywords such as PROGRAM, READ, and WRITE, while using lowercase for the program
variables. Names are written with underscores between the words, as in my_first_
program above. It also uses capital letters for named constants such as PI (π). This is
not a Fortran requirement; the program would have worked just as well if all capital
letters or all lowercase letters were used. Since uppercase and lowercase letters are
equivalent in Fortran, the program functions identically in either case.
Throughout this book, we will follow this convention of capitalizing Fortran
­
keywords and constants, and using lowercase for variables, procedure names, etc.
Some programmers use other styles to write Fortran programs. For example, Java
programmers who also work with Fortran might adopt a Java-like convention in
which keywords and names are in lowercase, with capital letters at the beginning of
each word (sometimes called “camel case”). Such a programmer might give this pro-
gram the name myFirstProgram. This is an equally valid way to write a Fortran
program.
It is not necessary for you to follow any specific convention to write a Fortran
program, but you should always be consistent in your programming style. Establish a
standard practice, or adopt the standard practice of the organization in which you
work, and then follow it consistently in all of your programs.
Good Programming Practice
Adopt a programming style, and then follow it consistently in all of your programs.
2.4.5 Compiling, Linking, and Executing the Fortran Program
Before the sample program can be run, it must be compiled into object code with a
Fortran compiler, and then linked with a computer’s system libraries to produce an
executable program (Figure 2-2). These two steps are usually done together in
­
response to a single programmer command. The details of compiling and linking
are different for every compiler and operating system. You should ask your
­
instructor or consult the appropriate manuals to determine the proper procedure for
your system.
Fortran
program
Compile
Object file
Link
Executable
program
FIGURE 2-2
Creating an executable Fortran program involves two steps, compiling and linking.
Other documents randomly have
different content
Pois hylkäsin haaveeni hullut:
sydän sairas ei terveeksi tullut.
Sydän parkani riutuen huokaa:
Tään maanpaon päättyä suokaa!
Jos käyt maan äärihin hamaan,
ei riitä se erottamaan…
Jo sain minä kohtalon polon:
elinkautisen vankina olon.
Olen kytketty, ah, sydänjuurin
häneen, mi on murheeni suurin!
Käykäämme yhteen vaieten, anteeksiantain
Käykäämme yhteen vaieten, anteeksiantain ja muistaen
menneisyydestä pelkkää hyvää; ja hetket mustat jos saapuvat
syyttäin ja kantain, niin olkaamme kaksi kaunista kyyneltyvää,
kuin siskot armaat, leikkihin herääväiset, kuin kukkaset
yrttitarhassa lempeän Herran, ei mies eikä nainen, vaan
lapset seppelepäiset, unohtain kaikki, mi meidät vieroitti
kerran…
Näin lapsina painumme jälleen tarujen lehtoon. Ei
kuolevaisella onnea muuta, ma vannon, kuin hymytä silmästä
silmään helmassa ehtoon ja vailla varjoa syyn tai
anteeksiannon.
Uni suuri ylleni lankeaa
Uni suuri ylleni lankeaa, sen siimes silmäni peittää: nyt aika
on tullut huoahtaa ja toiveet pettävät heittää.
Näkö mennyttä on, äly ollutta on,
ei aatosta huonoa, hyvää.
Voi, kurjuutta ihmiskohtalon,
voi, voimaani menehtyvää!
Mun henkeni kehto keinuva on,
käsi käyttäjän pimeään hukkuu.
Ma keinun portilla kalmiston.
Ah, hiljaa! lapsi jo nukkuu…
SERENAADI
Kuin vainajan ääni, mi vihloen soi läpi aution kalmiston, niin,
valtiatar, niin armaani, oi, tää soittoni särkynyt on!
Jo heltyykö mielesi vihdoinkin,
jo käännätkö ylpeän pään?
Vain sulle, sa ainut armahin,
tein kuolinlauluni tään!
Ma laulan: on kultaa silmäsi tuo,
salamoita mi syytää ja lyö,
on povesi huumaava Lethen vuo
ja hapsesi Styxin yö.
Kuin vainajan ääni, mi vihloen soi
läpi aution kalmiston,
niin, valtiatar, niin, armaani, oi,
tää soittoni särkynyt on!
Ma laulan varttasi valkeaa
ja hipiää hienoa sen,
ma laulan, kun unta en silmiini saa
sun tähtesi, hirtehinen.
Ma laulan autuutta miehen sen,
jolle huultesi huumat suot.
Valo taivainen, tuli helvettien,
sinä hurman ja turman tuot!
Jo heltyykö mielesi vihdoinkin, jo käännätkö ylpeän pään?
Vain sulle, sa ainut armahin, tein kuolinlauluni tään!
CHARLES BAUDELAIRE
SPLEEN I
Mulla muistoja enemmän on, tuhatvuotias jos oisin.
Jos lipaston raskaan eteenne romulla täytetyn toisin, mi
runoja, rakkauskirjeitä, kuitteja, haasteita vihan ja
hiustukkoja, vanhaa kuonaa täynnä ois ihan, se vähemmän
salaisuuksia kätkee kuin aivoni mun. Pyramiidi se on,
maakellari kadotetun, kukkurallaan kuolleiden luita kuin
köyhien yhteis-hauta.
— Olen kalmisto kammoma kuun, olen syyllisen kirstun
lauta; omantunnon tuskien lailla laulut raadoissa vertyy,
ikävöityjen vainajain ylle ne kummuksi kertyy. Olen
lempikammio vanha, miss' uinuu kuihtuneet kukat ja
muodista ammoin hyljätyt pukurukat, joku haaltunut taulu, mi
yksinäisyyttään itkee. Hajuvetten pinttynyt tuoksu ilmassa
viipyy sitkee…
Ja päivät pitkät vierii antaen tylsää unta, elo sammunut on,
ja vuodet sataa raskasta lunta. Ikävyys, taimi tiedon ja
haluttomuuden vain yksin heilimöi rannalla ikuisuuden.
— Olen liikkuva ruumis enää, kaukaisen haamun lainen,
kuin kivi, jota ympäröi yö ja hämäryys kauhistavainen,
Saharan erämaa sankka ja hietapyörtehet sen, ikivanha
Sfinksi, mi karttaa touhua kansojen, unohdettuna kartalle
maan, ulkopuolella toivon ja uskon, vain laulava säteille
sammuvan ehtooruskon.
SPLEEN II
Ma olen kuin kuningas sateesta samean maan, rikas ja nuori,
mut riutuva vanhuuttaan; hoviseuroja halveksuin ei liiku hän
missään, kera koirainsa istuu torkkuen ikävissään. Ei ärsytä
saalis, ei liikuta metsämaan ansa, ei linnan porteilla viruva
kuoleva kansa. Ei ballaadi narrinkaan, mi pieksää kieltä, voi
virkistää tuon kolkon sairahan mieltä. Huvivuoteensa kukkain
peittämä hauta on vain, sitä lempi ja naiset ja nauru ei ilota
lain, ei hempein hekkuman harso, ei taitavin keima luo hymyä
huuliin, joilla on kalman leima. Myös kullankeittäjä viisailla
valkeillansa pois turhaan on loihtinut kuonaa rinnastansa. Ei
keinot, joita käyttävät mahtavat maan, ei verikylvyt
roomalaistenkaan saa elon lämpimyyttä sydämeen, miss'
verta ei, vain laulu Lethen veen.
Sua lemmin, sa yöllisen taivaan lainen
Sua lemmin, sa yöllisen taivaan lainen, sa murheen kalkki,
suur' vaikenevainen, sa karttava kaunis, mi häivyt pois kuin
tähtihärmää varjosi ois, sa öitteni koru, jota silmäni pyytää,
mi haihtuu ja ivalla ikäväni hyytää.
Sua ryntään ahneena ahdistamaan kuin ruumista tuoretta
matoset maan. Tyly luontokappale, armastan sua, sun
kylmyytes julmakin miellyttää mua!
MERI JA IHMINEN
Sa merta lemmit, vapaa ihminen, on meri kuvastin sun
sydämesi, tuo lakkaamatta vyöryväinen vesi, ja sielus katkera
kuin kuilu sen.
Sa syöksyt synkkään pohjaan poves oman,
siell' omaa kuvaas syöt ja syleilet,
ain' armaat kuulla mielit nyyhkehet
sen valituksen raskaan, loputtoman.
Syyt, salaisuudet sanattomat on
niin syömmess' ihmisen kuin meren syvän;
ja alle vaahtopinnan hämärtyvän
te piiloitatte aarteet pimennon.
Tuo joka päivä teille taiston uuden, ei sääli kiellä, omatunto
lyö; on ystävänne kuolema ja yö, te sotaveikot halki
ikuisuuden!
*** END OF THE PROJECT GUTENBERG EBOOK RANSKALAISTA
LAULURUNOUTTA ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the free
distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only be
used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E. Unless you have removed all references to Project Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is derived
from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is posted
with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute this
electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or providing
access to or distributing Project Gutenberg™ electronic works
provided that:
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You provide a full refund of any money paid by a user who
notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.
• You provide, in accordance with paragraph 1.F.3, a full refund of
any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™
electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend
considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.
1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for
the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.
1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you
discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,
the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.
Section 2. Information about the Mission
of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.
The Foundation’s business office is located at 809 North 1500 West,
Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.
The Foundation is committed to complying with the laws regulating
charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.
While we cannot and do not solicit contributions from states where
we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.
International donations are gratefully accepted, but we cannot make
any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Section 5. General Information About
Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookmasss.com

More Related Content

PDF
Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman
PPTX
introduction to FORTRAN programming for ABU students
PPTX
intro2fortran.pptx
PDF
PPTX
Fortran - concise review
PPTX
Fortran 95
PDF
Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists...
PDF
Fortran introduction
Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman
introduction to FORTRAN programming for ABU students
intro2fortran.pptx
Fortran - concise review
Fortran 95
Introduction To Fortran 95 And Numerical Computing A Jumpstart For Scientists...
Fortran introduction

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

PDF
452042223-Modern-Fortran-in-practice-pdf.pdf
PDF
Uni leicester
 
PDF
Cours_Fortran_Chapitre3_Tableaux_ehtp.pdf
PDF
Uni texus austin
 
PPTX
1922071042 - Mohammad Saiful Islam - CSE425.5 (MSAH) - Presentation - Fortran...
PDF
Fortran Programming Language in short with fortran codes.pdf
PPT
03-fortran.ppt
PPT
Fortran90 Aplicada a programas de ingeniera.ppt
PDF
Modern Fortran Explained 4th Edition Michael Metcalf
PDF
Modern Fortran Explained Numerical Mathematics and Scientific Computation 4th...
PDF
Fortran apesteguia (1)
PDF
Fortran 90 Basics
PDF
Enterprise Cobol Programming Guide For Zos And Os390 32 Ibm
PDF
Vic broquard c++ for computer science and engineering 2006
PDF
Engineering Computation With Matlab 2nd Ed David M Smith
PDF
Modern Fortran Explained 4th Edition Michael Metcalf John Reid
PDF
Engineering Computation: An Introduction Using MATLAB and Exce, 2nd Edition M...
PDF
Fortran 90 overview
DOCX
Ece 1322 programming_for_engineers_s1_201213(1)
PDF
Modern Fortran Explained: Incorporating Fortran 2018 Michael Metcalf
452042223-Modern-Fortran-in-practice-pdf.pdf
Uni leicester
 
Cours_Fortran_Chapitre3_Tableaux_ehtp.pdf
Uni texus austin
 
1922071042 - Mohammad Saiful Islam - CSE425.5 (MSAH) - Presentation - Fortran...
Fortran Programming Language in short with fortran codes.pdf
03-fortran.ppt
Fortran90 Aplicada a programas de ingeniera.ppt
Modern Fortran Explained 4th Edition Michael Metcalf
Modern Fortran Explained Numerical Mathematics and Scientific Computation 4th...
Fortran apesteguia (1)
Fortran 90 Basics
Enterprise Cobol Programming Guide For Zos And Os390 32 Ibm
Vic broquard c++ for computer science and engineering 2006
Engineering Computation With Matlab 2nd Ed David M Smith
Modern Fortran Explained 4th Edition Michael Metcalf John Reid
Engineering Computation: An Introduction Using MATLAB and Exce, 2nd Edition M...
Fortran 90 overview
Ece 1322 programming_for_engineers_s1_201213(1)
Modern Fortran Explained: Incorporating Fortran 2018 Michael Metcalf
Ad

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Lesson notes of climatology university.
PDF
Complications of Minimal Access Surgery at WLH
PPTX
GDM (1) (1).pptx small presentation for students
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
master seminar digital applications in india
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cell Structure & Organelles in detailed.
PPTX
Institutional Correction lecture only . . .
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Classroom Observation Tools for Teachers
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana
Lesson notes of climatology university.
Complications of Minimal Access Surgery at WLH
GDM (1) (1).pptx small presentation for students
O7-L3 Supply Chain Operations - ICLT Program
A systematic review of self-coping strategies used by university students to ...
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
master seminar digital applications in india
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cell Structure & Organelles in detailed.
Institutional Correction lecture only . . .
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Supply Chain Operations Speaking Notes -ICLT Program
Classroom Observation Tools for Teachers
STATICS OF THE RIGID BODIES Hibbelers.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Ad

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

  • 1. Download the full version and explore a variety of ebooks or textbooks at https://ebookmass.com Fortran for Scientists and Engineers 4th Edition Stephen J. Chapman _____ Follow the link below to get your download now _____ https://ebookmass.com/product/fortran-for-scientists-and- engineers-4th-edition-stephen-j-chapman/ Access ebookmass.com now to download high-quality ebooks or textbooks
  • 2. We have selected some products that you may be interested in Click the link to download now or visit ebookmass.com for more options!. MATLAB Programming for Engineers 6th Edition Stephen J. Chapman https://ebookmass.com/product/matlab-programming-for-engineers-6th- edition-stephen-j-chapman/ Modern Physics for Scientists and Engineers 5th Edition Stephen Thornton & Andrew Rex https://ebookmass.com/product/modern-physics-for-scientists-and- engineers-5th-edition-stephen-thornton-andrew-rex/ Technical Writing for Engineers & Scientists, 4th Edition Leo Finkelstein https://ebookmass.com/product/technical-writing-for-engineers- scientists-4th-edition-leo-finkelstein/ Technical Writing for Engineers & Scientists 4th Edition Leo Finkelstein https://ebookmass.com/product/technical-writing-for-engineers- scientists-4th-edition-leo-finkelstein-2/
  • 3. Physics for Scientists and Engineers with Modern Physics 4th Edition Douglas C. Giancoli https://ebookmass.com/product/physics-for-scientists-and-engineers- with-modern-physics-4th-edition-douglas-c-giancoli/ eTextbook 978-0131495081 Physics for Scientists & Engineers with Modern Physics (4th Edition) https://ebookmass.com/product/etextbook-978-0131495081-physics-for- scientists-engineers-with-modern-physics-4th-edition/ Physics for Scientists and Engineers 9th Edition, (Ebook PDF) https://ebookmass.com/product/physics-for-scientists-and- engineers-9th-edition-ebook-pdf/ Statistics for Engineers and Scientists 5th Edition William Navidi https://ebookmass.com/product/statistics-for-engineers-and- scientists-5th-edition-william-navidi-2/ Statistics for Engineers and Scientists, 6th Edition William Navidi https://ebookmass.com/product/statistics-for-engineers-and- scientists-6th-edition-william-navidi-2/
  • 5. Fortran for Scientists and Engineers Fourth Edition Stephen J. Chapman BAE Systems Australia
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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.   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.   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
  • 15. 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
  • 16.   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
  • 17. 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.
  • 18. 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.
  • 19. 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.
  • 20. 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
  • 21. ­ 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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).
  • 27. 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.
  • 28. 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.
  • 29. 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.
  • 30. 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
  • 31. 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.
  • 32. 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.
  • 33. 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)
  • 34. 12 chapter 1:   Introduction to Computers and the Fortran Language 1 1.3 COMPUTER LANGUAGES When a computer executes a program, it executes a string of very simple operations such as load, store, add, subtract, multiply, and so on. Each such operation has a unique binary pattern called an operation code (op code) to specify it. The program that a com- puter executes is just a string of op codes (and the data associated with the op codes6 ) in the order necessary to achieve a purpose. Op codes are collectively called machine language, since they are the actual language that a computer recognizes and executes. Unfortunately, we humans find machine language very hard to work with. We prefer to work with English-like statements and algebraic equations that are expressed in forms familiar to us, instead of arbitrary patterns of zeros and ones. We like to pro- gram computers with high-level languages. We write out our instructions in a high- level language, and then use special programs called compilers and linkers to convert the instructions into the machine language that the computer understands. (concluded) 2. Express the following binary numbers as their decimal equivalents: (a) 11102 (b) 010101012 (c) 10012 3. Express the following binary numbers as octal and hexadecimal numbers: (a) 11100101101011012 (b) 11101111012 (c) 10010111001111112 4. Is the fourth bit of the number 13110 a 1 or a 0? 5. Assume that the following numbers are the contents of a character variable. Find the character corresponding to each number according to the ASCII encoding scheme (The character codes in the ASCII encoding scheme are defined in Appendix A): (a) 7710 (b) 011110112 (c) 24910 6. Find the maximum and minimum values that can be stored in a 2-byte ­integer variable. 7. Can a 4-byte variable of the real data type be used to store larger numbers than a 4-byte variable of the integer data type? Why or why not? If it can, what is given up by the real variable to make this possible? 6 The data associated with op codes is called operands.
  • 35. Introduction to Computers and the Fortran Language 13 1 There are many different high-level languages, with different characteristics. Some of them are designed to work well for business problems, while others are ­ designed for general scientific use. Still others are especially suited for applications like operating systems programming. It is important to pick a proper language to match the problem that you are trying to solve. Some common high-level computer languages today include Ada, C, C++, ­ Fortran, and Java. Historically, Fortran has been the pre-eminent language for general scientific computations. It has been around in one form or another for more than 60 years, and has been used to implement everything from computer models of nuclear power plants to aircraft design programs to seismic signal processing systems, including some projects requiring literally millions of lines of code. The language is especially useful for numer- ical analysis and technical calculations. In addition, Fortran is the dominant language in the world of supercomputers and massively parallel computers. 1.4 THE HISTORY OF THE FORTRAN LANGUAGE Fortran is the grandfather of all scientific computer languages. The name Fortran is derived from FORmula TRANSlation, indicating that the language was intended from the start for translating scientific equations into computer code. The first version of the FORTRAN7 language was developed during the years 1954–1957 by IBM for use with its Type 704 computer (see Figure 1-4). Before that time, essentially all computer pro- grams were generated by hand in machine language, which was a slow, tedious, and error-prone process. FORTRAN was a truly revolutionary product. For the first time, a programmer could write a desired algorithm as a series of standard algebraic equa- tions, and the FORTRAN compiler would convert the statements into the machine language that the computer could recognize and execute. 7 Versions of the language before Fortran 90 were known as FORTRAN (written with all capital letters), while Fortran 90 and later versions are known as Fortran (with only the first letter capitalized). THE IBM TYPE 704 COMPUTER The IBM Type 704 computer was the first computer ever to use the FORTRAN lan- guage. It was released in 1954, and was widely used from then until about 1960, when it was replaced by the Model 709. As you can see from Figure 1-4, the computer occu- pied a whole room. What could a computer like that do in 1954? Not much, by today’s standards. Any PC sitting on a desktop can run rings around it. The 704 could perform about 4000 ­ integer multiplications and divisions per second, and an average of about 8000 ­ floating-point operations per second. It could read data from magnetic drums
  • 36. 14 chapter 1:   Introduction to Computers and the Fortran Language 1 FIGURE 1-4 The IBM Type 704 computer. (© Bettmann/Getty Images) (the equivalent of a disk drive) into memory at a rate of about 50,000 bytes per second. The amount of data storage available on a magnetic drum was also very small, so most programs that were not currently in use were stored as decks of punched cards. By comparison, a typical modern personal computer (circa 2006) performed more than 20,000,000,000 integer multiplications and divisions per second, and hundreds of millions of floating-point operations per second. Some of today’s workstations are small enough to sit on a desktop, and yet can perform more than 5,000,000,000 floating-point operations per second! Reads from disk into memory occur at rates greater than 25,000,000 bytes per second, and a typical PC disk drive can store more than 200,000,000,000 bytes of data. The limited resources available in the 704 and other machines of that generation placed a great premium on efficient programming. The structured programming tech- niques that we use today were simply not possible, because there was not enough speed or memory to support them. The earliest versions of FORTRAN were designed with those limitations in mind, which is why we find many archaic features preserved as living fossils in modern versions of Fortran.
  • 37. Introduction to Computers and the Fortran Language 15 1 FORTRAN was a wonderful idea! People began using it as soon as it was avail- able, because it made programming so much easier than machine language did. The language was officially released in April 1957, and by the fall of 1958, more than half of all IBM 704 computer programs were being written in Fortran. The original FORTRAN language was very small compared to our modern ver- sions of Fortran. It contained only a limited number of statement types, and supported only the integer and real data types. There were also no subroutines in the first ­ FORTRAN. It was a first effort at writing a high-level computer language, and natu- rally many deficiencies were found as people started using the language regularly. IBM addressed those problems, releasing FORTRAN II in the spring of 1958. Further developments continued through 1962, when FORTRAN IV was released. FORTRAN IV was a great improvement, and it became the standard version of ­ Fortran for the next 15 years. In 1966, FORTRAN IV was adopted as an ANSI standard, and it came to be known as FORTRAN 66. The Fortran language received another major update in 1977. FORTRAN 77 ­ included many new features designed to make structured programs easier to write and maintain, and it quickly became “the” Fortran. FORTRAN 77 introduced such struc- tures as the block IF, and was the first version of Fortran in which character variables were truly easy to manipulate. The next major update of Fortran was Fortran 90.8 Fortran 90 included all of ­ FORTRAN 77 as a subset, and extended the language in many important new direc- tions. Among the major improvements introduced to the language in Fortran 90 were a new free source format, array sections, whole-array operations, parameterized data types, derived data types, and explicit interfaces. Fortran 90 was a dramatic improve- ment over earlier versions of the language. Fortran 90 was followed in 1996 by a minor update called Fortran 95. Fortran 95 added a number of new features to the language such as the FORALL construct, pure functions, and some new intrinsic procedures. In addition, it clarified numerous ambi- guities in the Fortran 90 standard. Fortran 2003 was the next update.9 This is a more major change from Fortran 95, including new features such as enhanced derived types, object-oriented programming support, Unicode character set support, data manipulation enhancements, procedure pointers, and interoperability with the C language. It was followed by a more minor update called Fortran 2008. The subject of this book is the Fortran 2008 language. The designers of Fortran 2008 were careful to make the language backward compatible with FORTRAN 77 and earlier versions. Because of this backward compatibility, most of the millions of pro- grams written in FORTRAN 77 also work with Fortran 2008. Unfortunately, being backward compatible with earlier versions of Fortran required that Fortran 2008 retain some archaic features that should never be used in any modern program. In this book, 8 American National Standard Programming Language Fortran, ANSI X3.198-1992; and International Standards Organization ISO/IEC 1539: 1991, Information Technology—Programming Languages—­ Fortran. 9 International Standards Organization ISO/IEC 1539: 2004, Information Technology—Programming ­Languages—Fortran.
  • 38. 16 chapter 1:   Introduction to Computers and the Fortran Language 1 we will learn to program in Fortran using only its modern features. The older features that are retained for backward compatibility are relegated to Chapter 18 of this book. They are described there in case you run into any of them in older programs, but they should never be used in any new program. 1.5 THE EVOLUTION OF FORTRAN The Fortran language is a dynamic language that is constantly evolving to keep up with advances in programming practice and computing technology. A major new ver- sion appears about once per decade. The responsibility for developing new versions of the Fortran language lies with the International Organization for Standardization’s (ISO) Fortran Working Group, WG5. That organization has delegated authority to the J3 Committee of the ­ InterNational Committee for Information Technology Standards (INCITS) to actually prepare new versions of the language. The preparation of each new version is an ­ extended process involving first asking for suggestions for inclusion in the language, deciding which suggestions are feasible to implement, writing and circulating drafts to all interested parties throughout the world, and correcting the drafts and trying again until general agreement is reached. Eventually, a worldwide vote is held and the standard is adopted. The designers of new versions of the Fortran language must strike a delicate balance between backward compatibility with the existing base of Fortran programs and the introduction of desirable new features. Although modern structured pro- gramming features and approaches have been introduced into the language, many undesirable features from earlier versions of Fortran have been retained for backward compatibility. The designers have developed a mechanism for identifying undesirable and ­ obsolete features of the Fortran language that should no longer be used, and for even- tually eliminating them from the language. Those parts of the language that have been superseded by new and better methods are declared to be obsolescent features. Features that have been declared obsolescent should never be used in any new pro- grams. As the use of these features declines in the existing Fortran code base, they will then be considered for deletion from the language. No feature will ever be ­ deleted from a version of the language unless it was on the obsolescent list in at least one previous version, and unless the usage of the feature has dropped off to negligi- ble levels. In this fashion, the language can evolve without threatening the existing Fortran code base. The redundant, obsolescent, and deleted features of Fortran 2008 are described in Chapter 18 in case a programmer runs into them in existing programs, but they should never be used in any new programs. We can get a feeling for just how much the Fortran language has evolved over the years by examining Figures 1-5 through 1-7. These three figures show programs for calculating the solutions to the quadratic equation ax2 + bx + c = 0 in the styles of the original FORTRAN I, of FORTRAN 77, and of Fortran 2008. It is obvious that the
  • 39. Introduction to Computers and the Fortran Language 17 1 language has become more readable and structured over the years. Amazingly, though, Fortran 2008 compilers will still compile the FORTRAN I program with just a few minor changes!10 FIGURE 1-5 A FORTRAN I program to solve for the roots of the quadratic equation ax2 + bx + c = 0. C SOLVE QUADRATIC EQUATION IN FORTRAN I READ 100,A,B,C 100 FORMAT(3F12.4) DISCR = B**2-4*A*C IF (DISCR) 10,20,30 10 X1=(-B)/(2.*A) X2=SQRTF(ABSF(DISCR))/(2.*A) PRINT 110,X1,X2 110 FORMAT(5H X = ,F12.3,4H +i ,F12.3) PRINT 120,X1,X2 120 FORMAT(5H X = ,F12.3,4H -i ,F12.3) GOTO 40 20 X1=(-B)/(2.*A) PRINT 130,X1 130 FORMAT(11H X1 = X2 = ,F12.3) GOTO 40 30 X1=((-B)+SQRTF(ABSF(DISCR)))/(2.*A) X2=((-B)-SQRTF(ABSF(DISCR)))/(2.*A) PRINT 140,X1 140 FORMAT(6H X1 = ,F12.3) PRINT 150,X2 150 FORMAT(6H X2 = ,F12.3) 40 CONTINUE STOP 25252 FIGURE 1-6 A FORTRAN 77 program to solve for the roots of the quadratic equation ax2 + bx + c = 0. PROGRAM QUAD4 C C This program reads the coefficients of a quadratic equation of C the form C A * X**2 + B * X + C = 0, C and solves for the roots of the equation (FORTRAN 77 style). C C Get the coefficients of the quadratic equation. C WRITE (*,*) 'Enter the coefficients A, B and C: ' READ (*,*) A, B, C C C Echo the coefficients to make sure they are entered correctly. C (continued) 10 Change SQRTF to SQRT, ABSF to ABS, and add an END statement.
  • 40. 18 chapter 1:   Introduction to Computers and the Fortran Language 1 (concluded) WRITE (*,100) 'The coefficients are : ', A, B, C 100 FORMAT (1X,A,3F10.4) C C Check the discriminant and calculate its roots. C DISCR = B**2 - 4.*A*C IF ( DISCR .LT. 0) THEN WRITE (*,*) ' This equation has complex roots:' WRITE (*,*) ' X = ', -B/(2.*A), ' +i ', SQRT(ABS(DISCR))/(2.*A) WRITE (*,*) ' X = ', -B/(2.*A), ' -i ', SQRT(ABS(DISCR))/(2.*A) ELSE IF ( (B**2 - 4.*A*C) .EQ. 0) THEN WRITE (*,*) ' This equation has a single repeated real root:' WRITE (*,*) ' X = ', -B/(2.*A) ELSE WRITE (*,*) ' This equation has two distinct real roots:' WRITE (*,*) ' X = ', (-B + SQRT(ABS(DISCR)))/(2.*A) WRITE (*,*) ' X = ', (-B - SQRT(ABS(DISCR)))/(2.*A) END IF C END FIGURE 1-7 A Fortran 2008 program to solve for the roots of the quadratic equation ax2 + bx + c = 0. PROGRAM roots ! Purpose: ! This program solves for the roots of a quadratic equation of the form ! A * X**2 + B * X + C = 0. It calculates the answers regardless of the ! type of roots that the equation possesses (Fortran 95/2003 style). ! IMPLICIT NONE ! Declare the variables used in this program REAL :: a ! Coefficient of X**2 term of equation REAL :: b ! Coefficient of X term of equation REAL :: c ! Constant term of equation REAL :: discriminant ! Discriminant of the equation REAL :: imag_part ! Imaginary part of equation (for complex roots) REAL :: real_part ! Real part of equation (for complex roots) REAL :: x1 ! First solution of equation (for real roots) REAL :: x2 ! Second solution of equation (for real roots) ! Prompt the user for the coefficients of the equation WRITE (*,*) 'This program solves for the roots of a quadratic ' WRITE (*,*) 'equation of the form A * X**2 + B * X + C = 0. ' WRITE (*,*) 'Enter the coefficients A, B, and C:' READ (*,*) a, b, c ! Echo back coefficients WRITE (*,*) 'The coefficients A, B, and C are: ', a, b, c (continued)
  • 41. Introduction to Computers and the Fortran Language 19 1 (concluded) ! Calculate discriminant discriminant = b**2 - 4. * a * c ! Solve for the roots, depending upon the value of the discriminant IF ( discriminant 0. ) THEN ! there are two real roots, so... X1 = ( -b + sqrt(discriminant) ) / ( 2. * a ) X2 = ( -b - sqrt(discriminant) ) / ( 2. * a ) WRITE (*,*) 'This equation has two real roots:' WRITE (*,*) 'X1 = ', x1 WRITE (*,*) 'X2 = ', x2 ELSE IF ( discriminant == 0. ) THEN ! there is one repeated root, so... x1 = ( -b ) / ( 2. * a ) WRITE (*,*) 'This equation has two identical real roots:' WRITE (*,*) 'X1 = X2 = ', x1 ELSE ! there are complex roots, so ... real_part = ( -b ) / ( 2. * a ) imag_part = sqrt ( abs ( discriminant ) ) / ( 2. * a ) WRITE (*,*) 'This equation has complex roots:' WRITE (*,*) 'X1 = ', real_part, ' +i ', imag_part WRITE (*,*) 'X2 = ', real_part, ' -i ', imag_part END IF END PROGRAM roots 1.6 SUMMARY 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 com- puter what sequence of calculations is required, and which information to perform the calculations on. The major components of a computer are the central processing unit (CPU), cache memory, main memory, secondary memory, and input and output devices. The CPU performs all of the control and calculation functions of the computer. Cache memory is very fact memory integrated directly on the CPU chip. Main memory is somewhat slower memory that is used to store the program being executed and its associated data. Main memory is volatile, meaning that its contents are lost whenever power is turned off. Secondary memory is slower and cheaper than main memory. It is nonvol- atile. Hard disks are common secondary memory devices. Input and output devices are used to read data into the computer and to output data from the computer. The most
  • 42. 20 chapter 1:   Introduction to Computers and the Fortran Language 1 common input device is a keyboard, and the most common output devices are displays or printers. Computer memories are composed of millions of individual switches, each of which can be ON or OFF, but not at a state in between. These individual switches are binary devices called bits. Eight bits are grouped together to form a byte of memory, and 2 or more bytes (depending on the computer) are grouped together to form a word of memory. Computer memories can be used to store character, integer, or real data. Each character in most character data sets occupies 1 byte of memory. The 256 possible values in the byte allow for 256 possible character codes. (Characters in the Unicode character set occupy 2 bytes, allowing for 65,536 possible character codes.) Integer values occupy 1, 2, 4, or 8 bytes of memory, and store integer quantities. Real values store numbers in a kind of scientific notation. They usually occupy 4 bytes of memory. The bits are divided into a separate man- tissa and exponent. The precision of the number depends upon the number of bits in the mantissa, and the range of the number ­ depends upon the number of bits in the exponent. The earliest computers were programmed in machine language. This process was slow, cumbersome, and error-prone. High-level languages began to appear in about 1954, and they quickly replaced machine language coding for most uses. FORTRAN was one of the first high-level languages ever created. The FORTRAN I computer language and compiler were originally developed in 1954–1957. The language has since gone through many revisions, and a standard mechanism has been created to evolve the language. This book teaches good program- ming practices using the modern Fortran language. 1.6.1. Exercises 1-1. Express the following decimal numbers as their binary equivalents: (a) 1010 (b) 3210 (c) 7710 (d) 6310 1-2. Express the following binary numbers as their decimal equivalents: (a) 010010002 (b) 100010012 (c) 111111112 (d) 01012 1-3. Express the following numbers in both octal and hexadecimal forms: (a) 10101110111100012 (b) 33010 (c) 11110 (d) 111111011012
  • 43. Introduction to Computers and the Fortran Language 21 1 1-4. Express the following numbers in binary and decimal forms: (a) 3778 (b) 1A816 (c) 1118 (d) 1FF16 1-5. Some computers (such as IBM mainframes) used to implement real data using a 23-bit mantissa and a 9-bit exponent. What precision and range can we expect from real data on these machines? 1-6. Some Cray supercomputers used to support 46-bit and 64-bit integer data types. What are the maximum and minimum values that we could express in a 46-bit integer? in a 64-bit integer? 1-7. Find the 16-bit two’s complement representation of the following decimal numbers: (a) 5510 (b) −510 (c) 102410 (d) −102410 1-8. Add the two’s complement numbers 00100100100100102 and 11111100111111002 ­ using binary arithmetic. Convert the two numbers to decimal form, and add them as decimals. Do the two answers agree? 1-9. The largest possible 8-bit two’s complement number is 011111112 , and the smallest pos- sible 8-bit two’s complement number is 100000002 . Convert these numbers to decimal form. How do they compare to the results of Equations (1-1) and (1-2)? 1-10. The Fortran language includes a second type of floating-point data known as double precision. A double-precision number usually occupies 8 bytes (64 bits), instead of the 4 bytes occupied by a real number. In the most common implementation, 53 bits are used for the mantissa and 11 bits are used for the exponent. How many significant digits does a double-precision value have? What is the range of double-precision numbers?
  • 44. 22 2 Basic Elements of Fortran OBJECTIVES ∙ Know which characters are legal in a Fortran statement. ∙ Know the basic structure of a Fortran statement and a Fortran program. ∙ Know the difference between executable and nonexecutable statements. ∙ Know the difference between constants and variables. ∙ Understand the differences among the INTEGER, REAL, and CHARACTER data types. ∙ Learn the difference between default and explicit typing, and understand why explicit typing should always be used. ∙ Know the structure of a Fortran assignment statement. ∙ Learn the differences between integer arithmetic and real arithmetic, and when each one should be used. ∙ Know the Fortran hierarchy of operations. ∙ Learn how Fortran handles mixed-mode arithmetic expressions. ∙ Learn what intrinsic functions are, and how to use them. ∙ Know how to use list-directed input and output statements. ∙ Know why it is important to always use the IMPLICIT NONE statement. 2.1 INTRODUCTION As engineers and scientists, we design and execute computer programs to accomplish a goal. The goal typically involves technical calculations that would be too difficult or take too long to be performed by hand. Fortran is one of the computer languages com- monly used for these technical calculations. This chapter introduces the basic elements of the Fortran language. By the end of the chapter, we will be able to write simple but functional Fortran programs.
  • 45. Basic Elements of Fortran 23 2 2.2 THE FORTRAN CHARACTER SET Every language, whether it is a natural language such as English or a computer lan- guage such as Fortran, Java, or C++, has its own special alphabet. Only the characters in this alphabet may be used with the language. The special alphabet used with the Fortran language is known as the Fortran ­character set. The Fortran character set consists of 97 characters, as shown in Table 2-1. Note that the uppercase letters of the alphabet are equivalent to the lowercase ones in the Fortran character set. (For example, the uppercase letter A is equivalent to the lowercase letter a.) In other words, Fortran is case insensitive. This behavior is in con- trast with such case sensitive languages as C++ and Java, in which A and a are two totally different things. 2.3 THE STRUCTURE OF A FORTRAN STATEMENT A Fortran program consists of a series of statements designed to accomplish the goal of the programmer. There are two basic types of statements: executable statements and nonexecutable statements. Executable statements describe the actions taken by the program when it is executed (additions, subtractions, multiplications, divisions, etc.), while nonexecutable statements provide information necessary for the proper operation of the program. We will see many examples of each type of statement as we learn more about the Fortran language. Fortran statements may be entered anywhere on a line, and each line may be up to 132 characters long. If a statement is too long to fit onto a single line, then it may be continued on the next line by ending the current line (and optionally starting the next line) with an ampersand () character. For example, the following three Fortran ­ statements are identical: output = input1 + input2 ! Sum the inputs output = input1 + input2 ! Sum the inputs TABLE 2-1 The Fortran character set Number of symbols Type Values 26 Uppercase letters A-Z 26 Lowercase letters a-z 10 Digits 0-9 1 Underscore character _ 5 Arithmetic symbols + - * / ** 28 Miscellaneous symbols ( ) . = , ' $ : ! % ; ? ~ [ ] ` ^ { } | # @ and blank
  • 46. 24 chapter 2:   Basic Elements of Fortran 2 999 output = input1 ! Sum the inputs + input2 Each of the statements specifies that the computer should add the two quantities stored in input1 and input2 and save the result in output. A Fortran statement can be continued over up to 256 lines, if required. The last statement shown above starts with a number, known as a statement label. A statement label can be any number between 1 and 99,999. It is the “name” of a Fortran statement, and may be used to refer to the statement in other parts of the program. Note that a statement label has no significance other than as a “name” for the statement. It is not a line number, and it tells nothing about the order in which statements are executed. Statement labels are rare in modern Fortran, and most statements will not have one. If a statement label is used, it must be unique within a given program unit. For example, if 100 is used as a statement label on one line, it cannot be used again as a statement label on any other line in the same pro- gram unit. Any characters following an exclamation point are comments, and are ignored by the Fortran compiler. All text from the exclamation point to the end of the line will be ignored, so comments may appear on the same line as an executable statement. ­ Comments are very important, because they help us document the proper operation of a program. In the third example above, the comment is ignored, so the ampersand is treated by the compiler as the last character on the line. 2.4 THE STRUCTURE OF A FORTRAN PROGRAM Each Fortran program consists of a mixture of executable and nonexecutable state- ments, which must occur in a specific order. An example Fortran program is shown in Figure 2-1. This program reads in two numbers, multiplies them together, and prints out the result. Let’s examine the significant features of this program. FIGURE 2-1 A simple Fortran program. PROGRAM my_first_program ! Purpose: ! To illustrate some of the basic features of a Fortran program. ! ! Declare the variables used in this program. INTEGER :: i, j, k ! All variables are integers ! Get two values to store in variables i and j WRITE (*,*) 'Enter the numbers to multiply: ' READ (*,*) i, j (continued)
  • 47. Basic Elements of Fortran 25 2 (concluded) ! Multiply the numbers together k = i * j ! Write out the result. WRITE (*,*) 'Result = ', k ! Finish up. STOP END PROGRAM my_first_program This Fortran program, like all Fortran program units,1 is divided into three ­sections: 1. The declaration section. This section consists of a group of nonexecutable state- ments at the beginning of the program that define the name of the program and the number and types of variables referenced in the program. 2. The execution section. This section consists of one or more statements describing the actions to be performed by the program. 3. The termination section. This section consists of a statement or statements stop- ping the execution of the program and telling the compiler that the program is complete. Note that comments may be inserted freely anywhere within, before, or after the program. 2.4.1 The Declaration Section The declaration section consists of the nonexecutable statements at the beginning of the program that define the name of the program and the number and types of vari- ables referenced in the program. The first statement in this section is the PROGRAM statement. It is a nonexecutable statement that specifies the name of the program to the Fortran compiler. Fortran ­ program names may be up to 63 characters long and contain any combination of alpha- betic characters, digits, and the underscore (_) character. However, the first character in a program name must always be alphabetic. If present, the PROGRAM statement must be the first line of the program. In this example, the program has been named my_first_program. The next several lines in the program are comments that describe the purpose of the program. Next comes the INTEGER type declaration statement. This nonexecutable statement will be described later in this chapter. Here, it declares that three integer variables called i, j, and k will be used in this program. 1 A program unit is a separately-compiled piece of Fortran code. We will meet several other types of pro- gram units beginning in Chapter 7.
  • 48. 26 chapter 2:   Basic Elements of Fortran 2 2.4.2 The Execution Section The execution section consists of one or more executable statements describing the actions to be performed by the program. The first executable statement in this program is the WRITE statement, which writes out a message prompting the user to enter the two numbers to be multiplied together. The next executable statement is a READ statement, which reads in the two integers supplied by the user. The third executable statement instructs the computer to multiply the two numbers i and j together, and to store the result in variable k. The final WRITE statement prints out the result for the user to see. Comments may be embedded anywhere throughout the execution section. All of these statements will be explained in detail later in this chapter. 2.4.3 The Termination Section The termination section consists of the STOP and END PROGRAM statements. The STOP statement is a statement that tells the computer to stop running the program. The END PROGRAM statement is a statement that tells the compiler that there are no more state- ments to be compiled in the program. The STOP statement takes one of the following forms: STOP STOP 3 STOP 'Error stop' If the STOP statement is used by itself, execution will stop. If the STOP statement is used with a number, that number will be printed out when the program stops, and will normally be returned to the operating system as an error code. If the STOP statement is used with a character string, that string will be printed out when the program stops. When the STOP statement immediately precedes the END PROGRAM statement as in this example, it is optional. The compiler will automatically generate a STOP command when the END PROGRAM statement is reached. The STOP statement is therefore rarely used.2 There is an alternate version of the STOP statement called ERROR STOP. This ver- sion stops the program, but it also notifies the operating system that the program failed to execute properly. An example might be: ERROR STOP 'Cannot access database' This version of the STOP statement was added in Fortran 2008, and it might be useful if you need to inform an operating system script that a program failed abnormally. 2 There is a philosophical disagreement among Fortran programmers about the use of the STOP statement. Some programming instructors believe that it should always be used, even though it is redundant when located before an END PROGRAM statement. They argue that the STOP statement makes the end of execu- tion explicit. The author of this book is of the school that believes that a good program should only have one starting point and one ending point, with no additional stopping points anywhere along the way. In that case, a STOP is totally redundant and will never be used. Depending on the philosophy of your instructor, you may or may not be encouraged to use this statement.
  • 49. Basic Elements of Fortran 27 2 2.4.4 Program Style This example program follows a commonly used Fortran convention of capitalizing keywords such as PROGRAM, READ, and WRITE, while using lowercase for the program variables. Names are written with underscores between the words, as in my_first_ program above. It also uses capital letters for named constants such as PI (π). This is not a Fortran requirement; the program would have worked just as well if all capital letters or all lowercase letters were used. Since uppercase and lowercase letters are equivalent in Fortran, the program functions identically in either case. Throughout this book, we will follow this convention of capitalizing Fortran ­ keywords and constants, and using lowercase for variables, procedure names, etc. Some programmers use other styles to write Fortran programs. For example, Java programmers who also work with Fortran might adopt a Java-like convention in which keywords and names are in lowercase, with capital letters at the beginning of each word (sometimes called “camel case”). Such a programmer might give this pro- gram the name myFirstProgram. This is an equally valid way to write a Fortran program. It is not necessary for you to follow any specific convention to write a Fortran program, but you should always be consistent in your programming style. Establish a standard practice, or adopt the standard practice of the organization in which you work, and then follow it consistently in all of your programs. Good Programming Practice Adopt a programming style, and then follow it consistently in all of your programs. 2.4.5 Compiling, Linking, and Executing the Fortran Program Before the sample program can be run, it must be compiled into object code with a Fortran compiler, and then linked with a computer’s system libraries to produce an executable program (Figure 2-2). These two steps are usually done together in ­ response to a single programmer command. The details of compiling and linking are different for every compiler and operating system. You should ask your ­ instructor or consult the appropriate manuals to determine the proper procedure for your system. Fortran program Compile Object file Link Executable program FIGURE 2-2 Creating an executable Fortran program involves two steps, compiling and linking.
  • 50. Other documents randomly have different content
  • 51. Pois hylkäsin haaveeni hullut: sydän sairas ei terveeksi tullut. Sydän parkani riutuen huokaa: Tään maanpaon päättyä suokaa! Jos käyt maan äärihin hamaan, ei riitä se erottamaan… Jo sain minä kohtalon polon: elinkautisen vankina olon. Olen kytketty, ah, sydänjuurin häneen, mi on murheeni suurin! Käykäämme yhteen vaieten, anteeksiantain Käykäämme yhteen vaieten, anteeksiantain ja muistaen menneisyydestä pelkkää hyvää; ja hetket mustat jos saapuvat syyttäin ja kantain, niin olkaamme kaksi kaunista kyyneltyvää, kuin siskot armaat, leikkihin herääväiset, kuin kukkaset yrttitarhassa lempeän Herran, ei mies eikä nainen, vaan lapset seppelepäiset, unohtain kaikki, mi meidät vieroitti kerran… Näin lapsina painumme jälleen tarujen lehtoon. Ei kuolevaisella onnea muuta, ma vannon, kuin hymytä silmästä silmään helmassa ehtoon ja vailla varjoa syyn tai anteeksiannon.
  • 52. Uni suuri ylleni lankeaa Uni suuri ylleni lankeaa, sen siimes silmäni peittää: nyt aika on tullut huoahtaa ja toiveet pettävät heittää. Näkö mennyttä on, äly ollutta on, ei aatosta huonoa, hyvää. Voi, kurjuutta ihmiskohtalon, voi, voimaani menehtyvää! Mun henkeni kehto keinuva on, käsi käyttäjän pimeään hukkuu. Ma keinun portilla kalmiston. Ah, hiljaa! lapsi jo nukkuu…
  • 53. SERENAADI Kuin vainajan ääni, mi vihloen soi läpi aution kalmiston, niin, valtiatar, niin armaani, oi, tää soittoni särkynyt on! Jo heltyykö mielesi vihdoinkin, jo käännätkö ylpeän pään? Vain sulle, sa ainut armahin, tein kuolinlauluni tään! Ma laulan: on kultaa silmäsi tuo, salamoita mi syytää ja lyö, on povesi huumaava Lethen vuo ja hapsesi Styxin yö. Kuin vainajan ääni, mi vihloen soi läpi aution kalmiston, niin, valtiatar, niin, armaani, oi, tää soittoni särkynyt on! Ma laulan varttasi valkeaa ja hipiää hienoa sen, ma laulan, kun unta en silmiini saa sun tähtesi, hirtehinen.
  • 54. Ma laulan autuutta miehen sen, jolle huultesi huumat suot. Valo taivainen, tuli helvettien, sinä hurman ja turman tuot! Jo heltyykö mielesi vihdoinkin, jo käännätkö ylpeän pään? Vain sulle, sa ainut armahin, tein kuolinlauluni tään! CHARLES BAUDELAIRE
  • 55. SPLEEN I Mulla muistoja enemmän on, tuhatvuotias jos oisin. Jos lipaston raskaan eteenne romulla täytetyn toisin, mi runoja, rakkauskirjeitä, kuitteja, haasteita vihan ja hiustukkoja, vanhaa kuonaa täynnä ois ihan, se vähemmän salaisuuksia kätkee kuin aivoni mun. Pyramiidi se on, maakellari kadotetun, kukkurallaan kuolleiden luita kuin köyhien yhteis-hauta. — Olen kalmisto kammoma kuun, olen syyllisen kirstun lauta; omantunnon tuskien lailla laulut raadoissa vertyy, ikävöityjen vainajain ylle ne kummuksi kertyy. Olen lempikammio vanha, miss' uinuu kuihtuneet kukat ja muodista ammoin hyljätyt pukurukat, joku haaltunut taulu, mi yksinäisyyttään itkee. Hajuvetten pinttynyt tuoksu ilmassa viipyy sitkee… Ja päivät pitkät vierii antaen tylsää unta, elo sammunut on, ja vuodet sataa raskasta lunta. Ikävyys, taimi tiedon ja haluttomuuden vain yksin heilimöi rannalla ikuisuuden.
  • 56. — Olen liikkuva ruumis enää, kaukaisen haamun lainen, kuin kivi, jota ympäröi yö ja hämäryys kauhistavainen, Saharan erämaa sankka ja hietapyörtehet sen, ikivanha Sfinksi, mi karttaa touhua kansojen, unohdettuna kartalle maan, ulkopuolella toivon ja uskon, vain laulava säteille sammuvan ehtooruskon.
  • 57. SPLEEN II Ma olen kuin kuningas sateesta samean maan, rikas ja nuori, mut riutuva vanhuuttaan; hoviseuroja halveksuin ei liiku hän missään, kera koirainsa istuu torkkuen ikävissään. Ei ärsytä saalis, ei liikuta metsämaan ansa, ei linnan porteilla viruva kuoleva kansa. Ei ballaadi narrinkaan, mi pieksää kieltä, voi virkistää tuon kolkon sairahan mieltä. Huvivuoteensa kukkain peittämä hauta on vain, sitä lempi ja naiset ja nauru ei ilota lain, ei hempein hekkuman harso, ei taitavin keima luo hymyä huuliin, joilla on kalman leima. Myös kullankeittäjä viisailla valkeillansa pois turhaan on loihtinut kuonaa rinnastansa. Ei keinot, joita käyttävät mahtavat maan, ei verikylvyt roomalaistenkaan saa elon lämpimyyttä sydämeen, miss' verta ei, vain laulu Lethen veen. Sua lemmin, sa yöllisen taivaan lainen Sua lemmin, sa yöllisen taivaan lainen, sa murheen kalkki, suur' vaikenevainen, sa karttava kaunis, mi häivyt pois kuin
  • 58. tähtihärmää varjosi ois, sa öitteni koru, jota silmäni pyytää, mi haihtuu ja ivalla ikäväni hyytää. Sua ryntään ahneena ahdistamaan kuin ruumista tuoretta matoset maan. Tyly luontokappale, armastan sua, sun kylmyytes julmakin miellyttää mua!
  • 59. MERI JA IHMINEN Sa merta lemmit, vapaa ihminen, on meri kuvastin sun sydämesi, tuo lakkaamatta vyöryväinen vesi, ja sielus katkera kuin kuilu sen. Sa syöksyt synkkään pohjaan poves oman, siell' omaa kuvaas syöt ja syleilet, ain' armaat kuulla mielit nyyhkehet sen valituksen raskaan, loputtoman. Syyt, salaisuudet sanattomat on niin syömmess' ihmisen kuin meren syvän; ja alle vaahtopinnan hämärtyvän te piiloitatte aarteet pimennon. Tuo joka päivä teille taiston uuden, ei sääli kiellä, omatunto lyö; on ystävänne kuolema ja yö, te sotaveikot halki ikuisuuden!
  • 60. *** END OF THE PROJECT GUTENBERG EBOOK RANSKALAISTA LAULURUNOUTTA *** Updated editions will replace the previous one—the old editions will be renamed. Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution. START: FULL LICENSE
  • 61. THE FULL PROJECT GUTENBERG LICENSE
  • 62. PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK To protect the Project Gutenberg™ mission of promoting the free distribution of electronic works, by using or distributing this work (or any other work associated in any way with the phrase “Project Gutenberg”), you agree to comply with all the terms of the Full Project Gutenberg™ License available with this file or online at www.gutenberg.org/license. Section 1. General Terms of Use and Redistributing Project Gutenberg™ electronic works 1.A. By reading or using any part of this Project Gutenberg™ electronic work, you indicate that you have read, understand, agree to and accept all the terms of this license and intellectual property (trademark/copyright) agreement. If you do not agree to abide by all the terms of this agreement, you must cease using and return or destroy all copies of Project Gutenberg™ electronic works in your possession. If you paid a fee for obtaining a copy of or access to a Project Gutenberg™ electronic work and you do not agree to be bound by the terms of this agreement, you may obtain a refund from the person or entity to whom you paid the fee as set forth in paragraph 1.E.8. 1.B. “Project Gutenberg” is a registered trademark. It may only be used on or associated in any way with an electronic work by people who agree to be bound by the terms of this agreement. There are a few things that you can do with most Project Gutenberg™ electronic works even without complying with the full terms of this agreement. See paragraph 1.C below. There are a lot of things you can do with Project Gutenberg™ electronic works if you follow the terms of this agreement and help preserve free future access to Project Gutenberg™ electronic works. See paragraph 1.E below.
  • 63. 1.C. The Project Gutenberg Literary Archive Foundation (“the Foundation” or PGLAF), owns a compilation copyright in the collection of Project Gutenberg™ electronic works. Nearly all the individual works in the collection are in the public domain in the United States. If an individual work is unprotected by copyright law in the United States and you are located in the United States, we do not claim a right to prevent you from copying, distributing, performing, displaying or creating derivative works based on the work as long as all references to Project Gutenberg are removed. Of course, we hope that you will support the Project Gutenberg™ mission of promoting free access to electronic works by freely sharing Project Gutenberg™ works in compliance with the terms of this agreement for keeping the Project Gutenberg™ name associated with the work. You can easily comply with the terms of this agreement by keeping this work in the same format with its attached full Project Gutenberg™ License when you share it without charge with others. 1.D. The copyright laws of the place where you are located also govern what you can do with this work. Copyright laws in most countries are in a constant state of change. If you are outside the United States, check the laws of your country in addition to the terms of this agreement before downloading, copying, displaying, performing, distributing or creating derivative works based on this work or any other Project Gutenberg™ work. The Foundation makes no representations concerning the copyright status of any work in any country other than the United States. 1.E. Unless you have removed all references to Project Gutenberg: 1.E.1. The following sentence, with active links to, or other immediate access to, the full Project Gutenberg™ License must appear prominently whenever any copy of a Project Gutenberg™ work (any work on which the phrase “Project Gutenberg” appears, or with which the phrase “Project Gutenberg” is associated) is accessed, displayed, performed, viewed, copied or distributed:
  • 64. This eBook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this eBook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. 1.E.2. If an individual Project Gutenberg™ electronic work is derived from texts not protected by U.S. copyright law (does not contain a notice indicating that it is posted with permission of the copyright holder), the work can be copied and distributed to anyone in the United States without paying any fees or charges. If you are redistributing or providing access to a work with the phrase “Project Gutenberg” associated with or appearing on the work, you must comply either with the requirements of paragraphs 1.E.1 through 1.E.7 or obtain permission for the use of the work and the Project Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9. 1.E.3. If an individual Project Gutenberg™ electronic work is posted with the permission of the copyright holder, your use and distribution must comply with both paragraphs 1.E.1 through 1.E.7 and any additional terms imposed by the copyright holder. Additional terms will be linked to the Project Gutenberg™ License for all works posted with the permission of the copyright holder found at the beginning of this work. 1.E.4. Do not unlink or detach or remove the full Project Gutenberg™ License terms from this work, or any files containing a part of this work or any other work associated with Project Gutenberg™. 1.E.5. Do not copy, display, perform, distribute or redistribute this electronic work, or any part of this electronic work, without prominently displaying the sentence set forth in paragraph 1.E.1
  • 65. with active links or immediate access to the full terms of the Project Gutenberg™ License. 1.E.6. You may convert to and distribute this work in any binary, compressed, marked up, nonproprietary or proprietary form, including any word processing or hypertext form. However, if you provide access to or distribute copies of a Project Gutenberg™ work in a format other than “Plain Vanilla ASCII” or other format used in the official version posted on the official Project Gutenberg™ website (www.gutenberg.org), you must, at no additional cost, fee or expense to the user, provide a copy, a means of exporting a copy, or a means of obtaining a copy upon request, of the work in its original “Plain Vanilla ASCII” or other form. Any alternate format must include the full Project Gutenberg™ License as specified in paragraph 1.E.1. 1.E.7. Do not charge a fee for access to, viewing, displaying, performing, copying or distributing any Project Gutenberg™ works unless you comply with paragraph 1.E.8 or 1.E.9. 1.E.8. You may charge a reasonable fee for copies of or providing access to or distributing Project Gutenberg™ electronic works provided that: • You pay a royalty fee of 20% of the gross profits you derive from the use of Project Gutenberg™ works calculated using the method you already use to calculate your applicable taxes. The fee is owed to the owner of the Project Gutenberg™ trademark, but he has agreed to donate royalties under this paragraph to the Project Gutenberg Literary Archive Foundation. Royalty payments must be paid within 60 days following each date on which you prepare (or are legally required to prepare) your periodic tax returns. Royalty payments should be clearly marked as such and sent to the Project Gutenberg Literary Archive Foundation at the address specified in Section 4, “Information
  • 66. about donations to the Project Gutenberg Literary Archive Foundation.” • You provide a full refund of any money paid by a user who notifies you in writing (or by e-mail) within 30 days of receipt that s/he does not agree to the terms of the full Project Gutenberg™ License. You must require such a user to return or destroy all copies of the works possessed in a physical medium and discontinue all use of and all access to other copies of Project Gutenberg™ works. • You provide, in accordance with paragraph 1.F.3, a full refund of any money paid for a work or a replacement copy, if a defect in the electronic work is discovered and reported to you within 90 days of receipt of the work. • You comply with all other terms of this agreement for free distribution of Project Gutenberg™ works. 1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™ electronic work or group of works on different terms than are set forth in this agreement, you must obtain permission in writing from the Project Gutenberg Literary Archive Foundation, the manager of the Project Gutenberg™ trademark. Contact the Foundation as set forth in Section 3 below. 1.F. 1.F.1. Project Gutenberg volunteers and employees expend considerable effort to identify, do copyright research on, transcribe and proofread works not protected by U.S. copyright law in creating the Project Gutenberg™ collection. Despite these efforts, Project Gutenberg™ electronic works, and the medium on which they may be stored, may contain “Defects,” such as, but not limited to, incomplete, inaccurate or corrupt data, transcription errors, a copyright or other intellectual property infringement, a defective or
  • 67. damaged disk or other medium, a computer virus, or computer codes that damage or cannot be read by your equipment. 1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the “Right of Replacement or Refund” described in paragraph 1.F.3, the Project Gutenberg Literary Archive Foundation, the owner of the Project Gutenberg™ trademark, and any other party distributing a Project Gutenberg™ electronic work under this agreement, disclaim all liability to you for damages, costs and expenses, including legal fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE. 1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a defect in this electronic work within 90 days of receiving it, you can receive a refund of the money (if any) you paid for it by sending a written explanation to the person you received the work from. If you received the work on a physical medium, you must return the medium with your written explanation. The person or entity that provided you with the defective work may elect to provide a replacement copy in lieu of a refund. If you received the work electronically, the person or entity providing it to you may choose to give you a second opportunity to receive the work electronically in lieu of a refund. If the second copy is also defective, you may demand a refund in writing without further opportunities to fix the problem. 1.F.4. Except for the limited right of replacement or refund set forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
  • 68. INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE. 1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions. 1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause. Section 2. Information about the Mission of Project Gutenberg™ Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life. Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will
  • 69. remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org. Section 3. Information about the Project Gutenberg Literary Archive Foundation The Project Gutenberg Literary Archive Foundation is a non-profit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws. The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission of increasing the number of public domain and licensed works that can be freely distributed in machine-readable form accessible by the widest array of equipment including outdated equipment. Many
  • 70. small donations ($1 to $5,000) are particularly important to maintaining tax exempt status with the IRS. The Foundation is committed to complying with the laws regulating charities and charitable donations in all 50 states of the United States. Compliance requirements are not uniform and it takes a considerable effort, much paperwork and many fees to meet and keep up with these requirements. We do not solicit donations in locations where we have not received written confirmation of compliance. To SEND DONATIONS or determine the status of compliance for any particular state visit www.gutenberg.org/donate. While we cannot and do not solicit contributions from states where we have not met the solicitation requirements, we know of no prohibition against accepting unsolicited donations from donors in such states who approach us with offers to donate. International donations are gratefully accepted, but we cannot make any statements concerning tax treatment of donations received from outside the United States. U.S. laws alone swamp our small staff. Please check the Project Gutenberg web pages for current donation methods and addresses. Donations are accepted in a number of other ways including checks, online payments and credit card donations. To donate, please visit: www.gutenberg.org/donate. Section 5. General Information About Project Gutenberg™ electronic works Professor Michael S. Hart was the originator of the Project Gutenberg™ concept of a library of electronic works that could be freely shared with anyone. For forty years, he produced and distributed Project Gutenberg™ eBooks with only a loose network of volunteer support.
  • 71. Project Gutenberg™ eBooks are often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition. Most people start at our website which has the main PG search facility: www.gutenberg.org. This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.
  • 72. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookmasss.com