0864 Introduction To Programming Using Fortran 9520032008 PDF
0864 Introduction To Programming Using Fortran 9520032008 PDF
Programming
using
Fortran 95/2003/2008
Ed Jorgensen
March 2018
Version 3.0.51
Cover Diagram
The cover image is the plotted output from the chaos game program from chapter 11.
The image was plotted with GNUplot.
Copyright
Ed Jorgensen 2013, 2014, 2015, 2016, 2017, 2018
ii
Table of Contents
1 Introduction...................................................................................................................................... 1
1.1 Why Learn Programming........................................................................................................... 1
1.2 Fortran........................................................................................................................................ 1
1.3 Complete Fortran 95/2003/2008 Documentation....................................................................... 1
1.4 What Is A Program..................................................................................................................... 2
1.5 Operating System....................................................................................................................... 2
2 Computer Organization................................................................................................................... 3
2.1 Architecture Overview............................................................................................................... 3
2.2 Compiler..................................................................................................................................... 4
2.3 Information Representation........................................................................................................ 4
2.3.1 Decimal Numbers............................................................................................................... 4
2.3.2 Binary Numbers.................................................................................................................. 5
2.3.3 Character Representation.................................................................................................... 5
2.4 Exercises..................................................................................................................................... 5
2.4.1 Quiz Questions.................................................................................................................... 5
3 Getting Started................................................................................................................................. 7
3.1 Required Skills........................................................................................................................... 7
3.2 Program Formats........................................................................................................................ 7
3.2.1 Program Statement.............................................................................................................. 7
3.2.2 Comments........................................................................................................................... 8
3.2.3 Simple Output..................................................................................................................... 8
3.2.4 Example – First Program.................................................................................................... 8
3.3 Text Editor.................................................................................................................................. 8
3.4 Compiling................................................................................................................................... 9
3.4.1 Advanced Compiler Options............................................................................................... 9
3.5 Executing.................................................................................................................................... 9
3.6 Exercises................................................................................................................................... 10
3.6.1 Quiz Questions.................................................................................................................. 10
3.6.2 Suggested Projects............................................................................................................ 11
iii
4.3.1 Declaring Variables........................................................................................................... 16
4.3.2 Variable Ranges................................................................................................................ 16
4.3.3 Type Checking.................................................................................................................. 16
4.3.4 Initialization...................................................................................................................... 17
4.3.5 Constants.......................................................................................................................... 17
4.4 Comments................................................................................................................................. 17
4.5 Continuation Lines................................................................................................................... 18
4.5.1 Example............................................................................................................................ 18
4.6 Declarations, Extended Size Variables..................................................................................... 18
4.6.1 Integers............................................................................................................................. 19
4.6.2 Real................................................................................................................................... 19
4.7 Exercises................................................................................................................................... 19
4.7.1 Quiz Questions.................................................................................................................. 19
4.7.2 Suggested Projects............................................................................................................ 20
5 Expressions..................................................................................................................................... 21
5.1 Literals...................................................................................................................................... 21
5.1.1 Integer Literals.................................................................................................................. 21
5.1.2 Real Literals...................................................................................................................... 21
5.1.2.1 E-Notation................................................................................................................. 21
5.1.3 Complex Literals.............................................................................................................. 22
5.1.4 Character Literals.............................................................................................................. 22
5.1.5 Logical Constants............................................................................................................. 23
5.2 Arithmetic Operations.............................................................................................................. 23
5.2.1 Assignment....................................................................................................................... 23
5.2.2 Addition............................................................................................................................ 23
5.2.3 Subtraction........................................................................................................................ 24
5.2.4 Multiplication................................................................................................................... 24
5.2.5 Division............................................................................................................................ 24
5.2.6 Exponentiation.................................................................................................................. 25
5.3 Order of Operations.................................................................................................................. 25
5.4 Intrinsic Functions.................................................................................................................... 26
5.4.1 Mathematical Intrinsic Functions..................................................................................... 26
5.4.2 Conversion Functions....................................................................................................... 26
5.4.3 Summary........................................................................................................................... 27
5.5 Mixed Mode............................................................................................................................. 27
5.6 Examples.................................................................................................................................. 28
5.7 Exercises................................................................................................................................... 28
5.7.1 Quiz Questions.................................................................................................................. 28
5.7.2 Suggested Projects............................................................................................................ 29
iv
6.4.1 Quiz Questions.................................................................................................................. 34
6.4.2 Suggested Projects............................................................................................................ 34
7 Program Development................................................................................................................... 37
7.1 Understand the Problem........................................................................................................... 37
7.2 Create the Algorithm................................................................................................................ 38
7.3 Implement the Program............................................................................................................ 38
7.4 Test/Debug the Program........................................................................................................... 39
7.4.1 Error Terminology............................................................................................................ 40
7.4.1.1 Compiler Error.......................................................................................................... 40
7.4.1.2 Run-time Error.......................................................................................................... 40
7.4.1.3 Logic Error................................................................................................................ 41
7.5 Exercises................................................................................................................................... 42
7.5.1 Quiz Questions.................................................................................................................. 42
7.5.2 Suggested Projects............................................................................................................ 42
8 Selection Statements...................................................................................................................... 43
8.1 Conditional Expressions........................................................................................................... 43
8.2 Logical Operators..................................................................................................................... 44
8.3 IF Statements............................................................................................................................ 44
8.3.1 IF THEN Statement.......................................................................................................... 45
8.3.1.1 IF THEN Statement, Simple Form........................................................................... 45
8.3.2 IF THEN ELSE Statement................................................................................................ 45
8.3.3 IF THEN ELSE IF Statement........................................................................................... 46
8.4 Example One............................................................................................................................ 47
8.4.1 Understand the Problem................................................................................................... 47
8.4.2 Create the Algorithm......................................................................................................... 48
8.4.3 Implement the Program.................................................................................................... 49
8.4.4 Test/Debug the Program................................................................................................... 50
8.5 SELECT CASE Statement....................................................................................................... 50
8.6 Example Two............................................................................................................................ 53
8.6.1 Understand the Problem................................................................................................... 53
8.6.2 Create the Algorithm......................................................................................................... 53
8.6.3 Implement the Program.................................................................................................... 53
8.6.4 Test/Debug the Program................................................................................................... 54
8.7 Exercises................................................................................................................................... 55
8.7.1 Quiz Questions.................................................................................................................. 55
8.7.2 Suggested Projects............................................................................................................ 56
9 Looping........................................................................................................................................... 59
9.1 Counter Controlled Looping.................................................................................................... 59
9.2 EXIT and CYCLE Statements.................................................................................................. 61
9.3 Counter Controlled Example.................................................................................................... 61
9.3.1 Understand the Problem................................................................................................... 62
9.3.2 Create the Algorithm......................................................................................................... 62
9.3.3 Implement the Program.................................................................................................... 62
9.3.4 Test/Debug the Program................................................................................................... 63
v
9.4 Conditional Controlled Looping.............................................................................................. 63
9.5 Conditionally Controlled Loop Example................................................................................. 65
9.5.1 Understand the Problem................................................................................................... 65
9.5.2 Create the Algorithm......................................................................................................... 65
9.5.3 Implement the Program.................................................................................................... 66
9.5.4 Test/Debug the Program................................................................................................... 67
9.6 Exercises................................................................................................................................... 67
9.6.1 Quiz Questions.................................................................................................................. 67
9.6.2 Suggested Projects............................................................................................................ 69
10 Formatted Input/Output............................................................................................................. 71
10.1 Format.................................................................................................................................... 71
10.2 Format Specifiers................................................................................................................... 71
10.3 Integer Format Specifier......................................................................................................... 72
10.4 Real Format Specifier............................................................................................................. 73
10.5 Horizontal Positioning Specifiers........................................................................................... 73
10.6 Logical Format Specifier........................................................................................................ 74
10.7 Character Format Specifier.................................................................................................... 74
10.8 Advance Clause...................................................................................................................... 75
10.9 Example.................................................................................................................................. 76
10.9.1 Understand the Problem................................................................................................. 76
10.9.2 Create the Algorithm....................................................................................................... 76
10.9.3 Implement the Program.................................................................................................. 77
10.9.4 Test/Debug the Program................................................................................................. 79
10.10 Exercises............................................................................................................................... 79
10.10.1 Quiz Questions.............................................................................................................. 79
10.10.2 Suggested Projects........................................................................................................ 80
vi
12 File Operations............................................................................................................................. 91
12.1 File Open................................................................................................................................ 91
12.2 File Write................................................................................................................................ 92
12.3 Stop Statement........................................................................................................................ 92
12.4 File Read................................................................................................................................. 93
12.5 Rewind.................................................................................................................................... 93
12.6 Backspace............................................................................................................................... 93
12.7 Close File................................................................................................................................ 94
12.8 Example.................................................................................................................................. 94
12.8.1 Understand the Problem................................................................................................. 94
12.8.2 Create the Algorithm....................................................................................................... 94
12.8.3 Implement the Program.................................................................................................. 95
12.8.4 Test/Debug the Program................................................................................................. 96
12.9 Exercises................................................................................................................................. 96
12.9.1 Quiz Questions................................................................................................................ 97
12.9.2 Suggested Projects.......................................................................................................... 97
vii
14.3.3 Implement the Program................................................................................................ 118
14.3.4 Test/Debug the Program............................................................................................... 119
14.4 Exercises............................................................................................................................... 119
14.4.1 Quiz Questions.............................................................................................................. 119
14.4.2 Suggested Projects........................................................................................................ 120
15 Subprograms.............................................................................................................................. 123
15.1 Subprogram Types................................................................................................................ 123
15.2 Program Layout.................................................................................................................... 123
15.2.1 Internal Routines........................................................................................................... 124
15.2.2 External Routines.......................................................................................................... 124
15.3 Arguments............................................................................................................................. 124
15.3.1 Argument Intent............................................................................................................ 124
15.4 Variable Scope...................................................................................................................... 124
15.5 Using Functions and Subroutines......................................................................................... 124
15.5.1 Argument Passing......................................................................................................... 125
15.6 Functions.............................................................................................................................. 125
15.6.1 Intrinsic Functions........................................................................................................ 126
15.6.2 User-Defined Functions................................................................................................ 126
15.6.2.1 Side Effects........................................................................................................... 126
15.7 Subroutines........................................................................................................................... 127
15.8 Example................................................................................................................................ 128
15.8.1 Understand the Problem............................................................................................... 129
15.8.2 Create the Algorithm..................................................................................................... 130
15.8.3 Implement the Program................................................................................................ 131
15.8.4 Test/Debug the Program............................................................................................... 132
15.9 Exercises............................................................................................................................... 132
15.9.1 Quiz Questions.............................................................................................................. 132
15.9.2 Suggested Projects........................................................................................................ 134
viii
16.7.2 Suggested Projects........................................................................................................ 149
17 Modules....................................................................................................................................... 151
17.1 Module Declaration.............................................................................................................. 151
17.2 Use Statement....................................................................................................................... 152
17.3 Updated Compilation Commands........................................................................................ 152
17.4 Module Example Program.................................................................................................... 153
17.4.1 Understand the Problem............................................................................................... 153
17.4.2 Create the Algorithm..................................................................................................... 153
17.4.3 Implement the Program................................................................................................ 154
17.4.3.1 Main Program....................................................................................................... 154
17.4.3.2 Module Routines................................................................................................... 155
17.4.4 Compile the Program.................................................................................................... 156
17.4.5 Test/Debug the Program............................................................................................... 156
17.5 Exercises............................................................................................................................... 156
17.5.1 Quiz Questions.............................................................................................................. 156
17.5.2 Suggested Projects........................................................................................................ 157
18 Recursion.................................................................................................................................... 159
18.1 Recursive Subroutines.......................................................................................................... 159
18.2 Recursive Print Binary Example.......................................................................................... 160
18.2.1 Understand the Problem............................................................................................... 160
18.2.2 Create the Algorithm..................................................................................................... 160
18.2.3 Implement the Program................................................................................................ 161
18.2.4 Test/Debug the Program............................................................................................... 162
18.3 Recursive Functions............................................................................................................. 162
18.4 Recursive Factorial Example................................................................................................ 162
18.4.1 Understand the Problem............................................................................................... 162
18.4.2 Create the Algorithm..................................................................................................... 163
18.4.3 Implement the Program................................................................................................ 163
18.4.4 Test/Debug the Program............................................................................................... 164
18.5 Recursive Factorial Function Call Tree................................................................................ 165
18.6 Exercises............................................................................................................................... 166
18.6.1 Quiz Questions.............................................................................................................. 166
18.6.2 Suggested Projects........................................................................................................ 166
ix
20.2 Command Line Arguments................................................................................................... 178
20.2.1 Argument Count............................................................................................................ 179
20.2.2 Get Arguments.............................................................................................................. 179
20.2.3 Command Line Arguments, Example Program............................................................ 180
20.3 Exercises............................................................................................................................... 182
20.3.1 Quiz Questions.............................................................................................................. 183
20.3.2 Suggested Projects........................................................................................................ 183
x
25.2 Formatting Plot Files............................................................................................................ 203
25.2.1 Header........................................................................................................................... 204
25.2.2 Footer............................................................................................................................ 204
25.3 Plotting Files......................................................................................................................... 204
25.4 Example................................................................................................................................ 204
25.4.1 Plot Program................................................................................................................. 205
25.4.2 Plot File......................................................................................................................... 206
25.4.3 Plot Output.................................................................................................................... 206
Index................................................................................................................................................... 223
Illustration Index
Illustration 1: Computer Architecture........................................................................................................3
Illustration 2: Fortran 95/2003/2008 Compile Process..............................................................................4
Illustration 3: Factorial Recursion Tree.................................................................................................165
xi
xii
1 Introduction
Computers are everywhere in our daily lives. Between the desktop, laptop, phone, bank, and vehicle, it
is difficult to completely get away from computers. It only makes sense to learn a little about how a
computer really works.
This text provides an introduction to programming and problem solving using the Fortran
95/2003/2008 programming language. This introduction is geared for non-computer science majors.
The primary focus is on an introduction to problem solving and algorithm development. As such,
many details of the Fortran 95/2003/2008 language are omitted.
1.2 Fortran
Fortran is a programming language often used by the scientific community. Its name is a contraction of
FORmula TRANslation. FORTRAN is one of the earliest programming languages and was designed
specifically for solving scientific and engineering computational problems.
This text utilizes the Fortran 95/2003/2008 standard. Older versions of Fortran, like Fortran 77, are not
referenced. The older Fortran versions have less features and require additional, often burdensome,
formatting requirements.
If this location changes, a web search will be able to find the new location.
1
Chapter 1 ► Introduction
2
2 Computer Organization
Before writing programs, it is useful to understand some basics about how a computer is organized.
This section provides a brief, high-level overview of the basic components of a computer and how they
interact.
Primary Storage
CPU Random Access
Memory (RAM)
BUS
(Interconnection)
Programs and data are typically stored on the disk drive. When a program is executed, it must be
copied from the disk drive into the RAM memory. The CPU executes the program from RAM. This is
similar to storing a term paper on the disk drive, and when writing/editing the term paper, it is copied
from the disk drive into memory. When done, the updated version is stored back to the disk drive.
3
Chapter 2 ► Computer Organization
2.2 Compiler
Programs can be written in the Fortran programming language. However, the CPU does not read
Fortran directly. Instead, the Fortran program that we create will be converted into binary (1's and 0's)
by the compiler. These 1's and 0's are typically referred to as machine language. The CPU will read
the instructions and information, represented in binary as machine language, and perform the
commands from the program.
The compiler is a program itself and is required in order to create the files needed to execute programs
written in Fortran 95/2003/2008.
Which means,
1234 = 1×1000 2×100 3×10 4×1
3 2 1 0
1234 = 1×10 2×10 3×10 4×10
The decimal system is base 10 using the digits 0 through 9.
4
Chapter 2 ◄ Computer Organization
In base 2, we put the digits 0 or 1 in columns 20, 21, 23, and so on. For example,
11012 = 1×23 1×22 0×21 1×20 = 841
Which in decimal is 1310.
A set of 8 bits is a referred to as a byte. Computer data is typically allocated in bytes or sets of bytes.
2.4 Exercises
Below are some quiz questions based on this chapter.
5
Chapter 2 ► Computer Organization
6
3 Getting Started
This section provides a brief overview of how to get started. This includes the general process for
creating a very simple program, compiling, and executing the program. Some detailed steps regarding
working with files, obtaining the compiler, and compiling a program are included in Appendix B,
Windows Start-up Instructions.
If you are unsure about any of these requirements you will need to learn them before continuing.
Fortunately, they are not difficult. Additionally, there are numerous tutorials available on the Web.
The following sections assume that the Fortran 95/2003/2008 compiler is installed and available. For
additional information regarding obtaining and installing the compiler, refer to Appendix B. The
Fortran 95/2003/2008 compiler is available for download at no cost.
7
Chapter 3 ► Getting Started
3.2.2 Comments
Comments are information for the programmer and are not read by the computer. For example,
comments typically include information about the program. For programming assignments, the
comments should include the programmer name, assignment number, and a brief description of the
program. In Fortran, the exclamation mark (!) denotes a comment. Any characters after the
exclamation mark (!) are ignored by the compiler and thus are comments as shown in following
example.
Will display the message Hello World to the screen. Additional information regarding the write
statement and outputting information is provided in later chapters.
In this example, the program is named 'first'. This file, provided as input to the compiler, is typically
referred to as the source file.
8
Chapter 3 ◄ Getting Started
3.4 Compiling
Once the program is typed into a file, the file must be compiled. Compiling will convert the human-
readable Fortran program, or source file, into a machine-readable version (in binary).
In order to compile, the command prompt (Windows) or terminal interface (Unix, MAC) is required.
This interface will allow commands to be typed directly into the computer (instead of using a mouse).
Once started, it is typically necessary to change directories (from the default location) to the location of
where the hw.f95 source file was located (from the previous steps). Changing directories is typically
done with a cd <directoryName> command. For example, cd fortran (which is the name of the
directory used in this example). The prompt typically changes to include the current directory location.
In the example below, the commands typed by the user are displayed in bold. The regular (non-bolded)
text refers to prompts or other information displayed by the computer (which need not be typed).
To compile the example program, the following command would be entered:
C:\fortran> gfortran -o hw hw.f95
This command will tell the 'gfortran' compiler to read the file hw.f95 and, if there are no errors,
create an output file referred to as an executable file. On Windows based machines the executable file
is named hw.exe. And on Unix or Mac based machines, the executable is named hw (no extension).
If there is an error, the compiler will generate an error message, sometimes cryptic, and provide a line
number. Such errors are usually the result of mistyping one of the instructions. Any errors must be
resolved before continuing.
This command will tell the 'gfortran' compiler to include bounds checking. More information
regarding arrays and bounds checking is addressed in chapters 13 and 14.
3.5 Executing
To execute or run a program on a Windows based machine, type the name of the executable file. For
example, to execute or run the hw.exe program:
C:\fortran> hw
Hello World.
C:\fortran>
Which will execute the example program and display the “Hello World.” message to the screen.
9
Chapter 3 ► Getting Started
It is not necessary to type the extension (i.e., “.exe”) portion of the file name. It should be noted that
the space prior to the “H” is not produced by the program, but is how the system displays output.
To execute or run a program on a Unix or MAC based machine, type “./” and the name of the
executable file. For example, to execute or run the hw program:
c:\fortran> ./hw
Hello World.
c:\fortran>
The output ('Hello World.' as displayed on the screen) will be the same for Windows, Unix, or MAC
based machines.
3.6 Exercises
Below are some quiz questions and project suggestions based on this chapter.
2) What is the typical name of the output file from the compiler?
3) Fortran program must start with and end with what statement?
10
Chapter 3 ◄ Getting Started
6) What is the typical Fortran 95/2003/2008 compiler output file, or executable file, extension
(after the program is compiled)?
2) Obtain and install the GNU Fortran 95/2003/2008 compiler on a suitable computer. Refer to
Appendix B as needed.
3) Type in the hello world program, compile, and execute the program.
4) Update the example program to display your name in addition to the Hello World message.
11
Chapter 3 ► Getting Started
12
4 Fortran 95/2003/2008 – Basic Elements
Before beginning to writing programs, it is necessary to know some of the basic elements of the
Fortran language. This section describes some of the basic elements of Fortran. Additional
information will be added in later sections.
4.1 Variables
The basic concept in a program is the concept of a variable. Variables in a program are like variables in
an algebraic expression. They are used to hold values and then write mathematical expressions using
them. Fortran allows us to have variables of different types.
A variable can hold one value at a time. If another value is placed in the variable, the previous value is
over-written and lost.
Variable Name → 42
Note that the space (between next and month) or the special character, @, is not allowed. Additionally,
each variable must have a type associated as explained in the following sections.
13
Chapter 4 ► Fortran 95/2003/2008 – Basic Elements
4.1.2 Keywords
In programming, a keyword is a word or identifier that has a special meaning in a programming
language. For example, in the “hello world” Fortran program from the previous chapter, the word
program has a special meaning in that it is used to note the start or beginning of a program.
Additionally, the word write has a special meaning to note an output action (e.g., writing some
information to an output device, like the screen).
Such keywords are reserved in that they cannot be used for anything else such as variable names. That
is, a variable name of program or write is not allowed.
As additional Fortran 95/2003/2008 statements and language constructs are explained, more keywords
will be identified. In general, words used for Fortran language statements, attributes, and constructs
will likely be keywords. A complete list of keywords or reserved words is located in Appendix G.
It is also possible to have derived types and pointers. Both of these can be useful for more advanced
programs and are described in later chapters.
4.2.1 Integer
An integer1 is a whole number (not a fraction) that can be positive, negative, or zero. Examples include
the numbers 10, 0, -25, and 5,148. Integers are the numbers people are most familiar with, and they
serve a crucial role in mathematics and computers. All integers are whole numbers, so operations like
one divided by two (1/2) is 0 since the result must be a whole number. For integer division, no
rounding will occur as the fractional part is truncated.
14
Chapter 4 ◄ Fortran 95/2003/2008 – Basic Elements
4.2.2 Real
A real number2 includes the fractional part, even if the fractional part is 0. Real numbers, also referred
to as floating-point numbers, include both rational numbers and irrational numbers. Examples of
irrational numbers or numbers with repeating decimals include π, 2 and e. Additional examples
include 1.5, 5.0, and 3.14159. Fortran 95/2003/2008 will accept 5. as 5.0. All examples in this text
will include the “.0” to ensure clarity.
4.2.3 Complex
A complex number3, in mathematics, is a number comprising a real number and an imaginary number. It
can be written in the form of a + bi, where a and b are real numbers, and the i is the standard imaginary
unit with the property that i2 = −1.0. The complex numbers contain the ordinary real numbers, but
extend them by adding in extra numbers like an extra dimension. This data type is not used
extensively, but can be useful when needed.
4.2.4 Character
A character4 is a symbol like a letter, numerical digit, or punctuation. A string5 is a sequence or set of
characters. Characters and strings are typically enclosed in quotes. For example, the upper case letter
“Z” is a character and “Hello World” is a string. The characters are represented in a standardized
format referred to as ASCII.
4.2.5 Logical
A logical6 is only allowed to have two values, true or false. A logical can also be referred to as a
boolean. In Fortran, the true and false values are formally expressed as .true. or .false. which are also
called logical constants. The leading and trailing . (period) are required for the true and false constants.
15
Chapter 4 ► Fortran 95/2003/2008 – Basic Elements
4.3 Declarations
Fortran variables must be declared before executable statements.
This section provides an introduction to how variables are
declared.
The type must be one of the predefined data types (integer, real, complex, character, logical) as outlined
in the previous section. Declarations are placed in the beginning of the program (after the program
statement).
For example, to define an integer variable today,
integer :: today
16
Chapter 4 ◄ Fortran 95/2003/2008 – Basic Elements
Conversions between types should be performed explicitly. Later chapters provide specific examples
of how this can be accomplished.
When initially learning to program, this may seem quite annoying. However, this type mismatch can
cause subtle errors that are difficult to find.
4.3.4 Initialization
It is possible to declare a variable and set its initial value at the same time. This initialization is not
required, but can sometimes be convenient.
For example, to define an integer variable todaysdate and set it to the 15th of the month:
integer :: todaysdate=15
Spaces or no spaces are allowed between the variable name. The variable declaration may or may not
include an equal signs (for initialization). Commas are used to separate multiple variable declarations
on the same line. Variables initialized at declaration can be changed later in the program as needed.
4.3.5 Constants
A constant is a variable that cannot be changed during program execution. For example, a program
might declare a variable for π and set it to 3.14159. It is unlikely that a program would need to change
the value for π. The parameter qualifier will declare the variable as a constant, set the initial value, and
not allow that initial value to be altered during the program execution.
For example, the declarations:
real, parameter :: pi = 3.14159
integer, parameter :: width = 1280
will set the variable pi to 3.14159 and width to 1280 and ensure that they cannot be changed while the
program is executing.
4.4 Comments
As previously noted, comments are information for the programmer and ignored by the compiler. The
exclamation mark (!) denotes a comment. Any information after the exclamation mark (!) is ignored by
the compiler. In general, comments typically include information about the program. For example, a
comment might include the last modification date, programmer name, and details about the update. For
programming assignments, the comments might include the programmer name, assignment number,
and a description of the program. The comments might include information about the approach being
used, source of formulas (if applicable), or maybe data requirements such as using positive values for
some geometric formulas. Commenting such reference information is strongly encouraged and will be
addressed in future sections.
17
Chapter 4 ► Fortran 95/2003/2008 – Basic Elements
4.5.1 Example
The following trivial program illustrates the program formatting requirements and variable
declarations.
! Example Program
program example1
implicit none
integer :: radius, diameter
integer :: height=100, width=150
real :: area, perimeter
real :: length = 123.5, distance=413.761
real, parameter :: pi = 3.14159
character(11) :: msg = "Hello World"
In this example, a series of variables are defined (as examples) with most not used. The program will
display Greeting: Hello World when executed. The following chapters will address how to use
the variables to perform calculations and display results. Additional information regarding character
variables is provided in chapter 11.
18
Chapter 4 ◄ Fortran 95/2003/2008 – Basic Elements
4.6.1 Integers
As previously noted, the range of an integer value can range between −2,147,483,648 and
+2,147,483,647. In the unlikely event that a larger range is required, a special declaration can be used
to extend the range. The kind specifier is used with the integer declaration.
For example, to declare a variable bignum with an extended range, the integer declaration would be as
follows:
integer*8 :: bignum
or
integer(kind=8) :: bignum
Both of these equivalent declarations use more space for the variables (8 bytes instead of the normal 4)
in order to provide a larger range. The extended range of integer variables declared with the *8 or
kind=8 is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
4.6.2 Real
As previously noted, the range is approximately ±1.7×10±38 supporting about 7 digits of precision.
If more precision is required, the kind specifier can be used.
For example, to declare a real variable rnum with an extended range, the declaration would be as
follows:
real*8 :: rnum
or
real(kind=8) :: rnum
Both of these equivalent declarations use more space for the variables (8 bytes instead of the normal 4)
in order to provide a larger range. The extended precision of real variables declared with the *8 or
kind=8 is approximately −2.2×10−308 to +1.8×10 +308 which supports a much larger range with
about 15 digits of precision.
4.7 Exercises
Below are some quiz questions and project suggestions based on this chapter.
19
Chapter 4 ► Fortran 95/2003/2008 – Basic Elements
3) What data type are each of the following numbers (integer or real)?
475 ____________
19.25 ____________
19123 ____________
5.0 ____________
123.456 ____________
4) Write the statements required to declare value as an integer and count as a real.
5) Write the statements required to declare rate as a real variable initialized to 7.5.
2) Update the example program (from 1) to display your name (instead of the 'Hello World'
message).
20
5 Expressions
This section describes how to form basic Fortran 95/2003/2008 expressions and perform arithmetic
operations (i.e., add, subtract, multiple, divide, etc.). Expressions are formed using literals (actual
values), variables, and operators (i.e., +, -, *, /, etc.). The previous chapter provides an explanation of
what variables are and a summary of the five Fortran data types.
5.1 Literals
The simplest expression is a direct value, referred to as a literal. Since literals are actual values, not
variables, they cannot be changed. There are various types of literal constants described in the
following sections that correspond to the Fortran data types.
The real number should include the decimal point (i.e., the “.”). A real number includes the fractional
part, even if the fraction is 0. Fortran will accept a number with the “.” and no further digits. For example,
5. is the same as 5.0. All examples in this text will include the “.0” to ensure clarity.
5.1.2.1 E-Notation
For larger real numbers, e-notation may be useful. The e-notation means that you should multiply the
constant by 10 raised to the power following the "E". This is sometimes referred to as scientific
notation.
21
Chapter 5 ► Expressions
The first number denotes the real part and the second the imaginary part. Although a complex number
always consists of two elements, it is considered a single value.
Character and string constants (enclosed with quotes) are case sensitive. So, character “X” (upper-
case) is not the same as “x” (lower-case).
A problem arises if you want to have a quote in the string itself. A double quote will be interpreted as a
single within a string. The two quotes must be together (no spaces between). For example, the string:
"He said ""wow"" when he heard"
Would be displayed as
"He said "wow" when he heard"
The double-quote is sometimes referred to as an escape character. Strings and characters must be
associated with the character data type.
22
Chapter 5 ◄ Expressions
5.2.1 Assignment
In programming, assignment is the term for setting a variable equal to some value. Assignment is
performed with an equal (=) sign. The general form is:
variable = expression
The expression may be a literal, variable, an arithmetic formula, or combination of each. Only one
assignment to a single variable can be made per line.
For example, to declare the variable answer1 as a real value,
real :: answer1
The value for answer1 can be changed as often as needed. However, it can only hold one value at a
time.
5.2.2 Addition
The Fortran addition operation is specified with a plus sign (+). For example, to declare the variables,
mysum, number1, number2, and number3,
integer :: mysum, number1=4, number2=5, number3=3
which will set the variable mysum to 9 in this example. The data types of the variables, integer in this
example, should be the same. Multiple variables can be added on one line. The line can also include
literal values. For example,
mysum = number1 + number2 + number3 + 2
which will set the variable mysum variable to 14. Additionally, it will write over the previous value of
9.
23
Chapter 5 ► Expressions
5.2.3 Subtraction
The Fortran subtraction operation is specified with a minus sign (-). For example, to declare the
variables, ans, value1, value2, and value3,
real :: ans, value1=4.5, value2=2.5, value3=1.0
which will set the variable ans to 2.0. The data types of the variables, real in this example, should be
the same. Multiple variables can be subtracted on one line. The line can also include literal values.
For example,
ans = value1 - value2 – value3
which will set the variable ans to 1.0. Additionally, it will over-write the previous value of 2.0.
5.2.4 Multiplication
The Fortran multiplication operation is specified with an asterisk (*). For example, to declare the
variables, ans, value1, value2, and value3,
real :: ans, value1=4.5, value2=2.0, value3=1.5
which will set the variable ans to 9.0. The data types of the variables, real in this example, should be
the same. Multiple variables can be multiplied on one line. The line can also include literal values.
For example,
ans = value1 * value2 * 2.0 * value3
which will set the variable ans to 27.0. Additionally, it will over-write the previous value of 9.0.
5.2.5 Division
The Fortran division operation is specified with a slash symbol (/). For example, to declare the
variables, ans, value1, value2, and value3,
real :: ans, value1=10.0, value2=2.5, value3=2.0
which will set the variable ans to 4.0. The data types of the variables, real in this example, should be
the same. Multiple variables can be divided on one line.
24
Chapter 5 ◄ Expressions
For example,
ans = value1 / value2 / value3
which will set the variable ans to 2.0. Additionally, it will over-write the previous value of 4.0.
5.2.6 Exponentiation
Exponentiation means “raise to the power of”. For example, 2 to the power of 3, or 23 is (2 * 2 * 2)
which is 8. The Fortran exponentiation operation is specified with a double asterisks (**).
For example, to declare the variables, ans and value1,
real :: ans, value1=2.0
which will set the variable ans to 8.0. When using exponentiation, pay close attention to the data types.
For example, raising an integer variable to the power 0.5 would produce a truncated integer result.
For operations of the same precedence level, the expression is evaluated left to right. Parentheses may
be used to change the order of evaluation as necessary. For example, declaring the variables ans1,
ans2, num1, num2, and num3.
integer :: ans1, ans2, num1=20, num2=50, num3=10
25
Chapter 5 ► Expressions
and then performing the calculation of the cosine the variable pi as follows,
z = cos(pi)
26
Chapter 5 ◄ Expressions
5.4.3 Summary
A summary of some of the more common intrinsic functions include:
Function Description
COS(W) Returns real cosine of real argument W in radians.
INT(A) Converts real argument A to integer, truncating (real part)
towards zero.
MOD(R1,R2) Returns remainder after division of R1 on division by R2.
Result, R1 and R2 should be all integer or all real types.
NINT(X) Returns the nearest integer to real value X (thus rounding
up or down as appropriate).
REAL(A) Converts integer argument A to real.
SIN(W) Returns real sine of real argument W in radians.
SQRT(W) Returns the real square root of real argument W; W must be
positive.
TAN(X) Returns the real tangent of real argument X in radians.
Any integers values are converted to real only when mixed-mode is encountered on the same operation
type. Conversion may also occur on assignment.
Unexpected conversions can cause problems when calculating values. In order to avoid such problems,
it is strongly recommended to not use mixed-mode. There are a series of rules associated with mixed
mode operations. In some circumstances, these rules can be confusing. For simplicity, those rules are
not covered in this text.
If it is necessary to perform calculations with different data types, such as integers and reals, the
intrinsic or built-in conversion functions should be used to ensure correct and predictable results. This
also allows the programming greater control of when types are converted. In very complex
calculations, this would help ensure clarity and address precision issues. Further recommendations to
address highly precise calculations are not addressed in this text.
27
Chapter 5 ► Expressions
5.6 Examples
Below is an example program that calculates velocity based on acceleration and time. The program
declares the appropriate variables and calculate the velocity.
program findvelocity
! Program to calculate the velocity from the
! acceleration and time
! Declare variables
implicit none
real :: velocity, acceleration = 128.0
real :: time = 8.0
Additional information regarding how to perform input and output in the next chapter. The comments
are not required, but help make the program easier to read and understand.
5.7 Exercises
Below are some quiz questions and project suggestion based on this chapter.
28
Chapter 5 ◄ Expressions
7) Write the single Fortran statement for each of the following formulas. You may assume all
variables are already declared as real values. Additionally, you may assume the variable PI is
set as a parameter and initialized to 3.14159.
x1 = ( π6 ) ( 3 a + 3 b + c )
2 2 2
2a
x2 = − cos ( b) sin( b)
c
−b + √ ( b 2−4 a c)
x3 =
2a
2) Write a program to calculate and display the difference between time as read from a sundial and
a clock (which is due to the irregular movement of the Sun). The difference can be calculated
with the Equation of Time7 which is as follows:
b = 2 π ( n − 81) / 365
e = 9.87 sin (2 b) − 7.53 cos (b) − 1.5 sin(b)
Where, n is the day number. For example, n = 1 for January 1, n = 2 for January 2, and so on.
The program should read the value for n (1-365) from the user as an integer. The program
should perform the appropriate type conversions, perform the required calculations, and display
the original n value, the calculated b (for reference), and final e value which represents the time
difference in minutes. Test the program on a series of different values. The formulas provided
are an approximation. For more accurate results, refer to the referenced Wikipedia entry for the
complete formula.
29
Chapter 5 ► Expressions
30
6 Simple Input and Output
Simple, unstructured, input and output can be performed with the write and read statements as
explained in the following sections. In a later chapter, a more structured approach will be presented in
later sections.
Which will send the message, referred to as a string, Hello World to the screen. The first “*” means
the default output device, which is the screen or monitor. The second “*” refers to the 'free format'.
Thus, the “(*,*)” means to send it to the screen in 'free format'.
The free format allows the Fortran compiler to determine the appropriate format for the information
being displayed. This is easy, especially when first getting started, but does not allow the program
much control over how the output will be formatted or displayed on the screen.
Additionally, the value held by declared variables can be displayed. For example, to declare the
variables num1, num2, and num3.
integer :: num1=20, num2=50, num3=10
The free format allows the Fortran compiler to determine the appropriate output format for the
information being displayed.
A write statement with no strings or variables,
write (*,*)
The information inside the quotes is displayed as is, including capitalization and any spelling errors.
When the quotes are not used, it is interpreted as a variable. If the variable is not declared, a compiler
error will be generated. The value assigned to each variable will be displayed. A value must have been
assigned to the variable prior to attempting to display.
31
Chapter 6 ► Simple Input and Output
The information inside the quotes is displayed as is, including capitalization and any spelling errors.
When the quotes are not used, it is interpreted as a variable. If the variable is not declared, an error will
be generated. If the variable is defined, the value assigned to that variable will be displayed.
In general, all examples will use the write statement.
Which will read a number from the user entered on the keyboard into the variable ans1. The (*,*)
means to send it to read the information in 'free format'. The free format allows the Fortran compiler to
determine the appropriate format for the information being read.
Multiple variables can be read with one read statement. For example, using the previous declarations,
read (*,*) ans1, ans2
will read two values from the user into the variables ans1 and ans2.
Since the read is using free format, two numbers will be required. The numbers can be entered on the
same line with one or more spaces between them or on separate lines. The read will wait until two
numbers are entered.
When reading information from the user, it is usually necessary to provide a prompt in order to ensure
that the user understands that input is being requested by the program. A suitable write statement with
an appropriate string, followed by a read statement will ensure that the user is notified that input is
being requested.
For example, to read a date, a program might request month, day, and year as three separate variables.
Given the following declarations,
integer :: month, day, year
the program might prompt for and read the data in the following manner,
write (*,*) "Enter date (month, day, and year)"
read (*,*) month, day, year
32
Chapter 6 ◄ Simple Input and Output
Since the program is requesting three integers, three integers must be entered before the program
continues. The three numbers may be entered on one line with a single space between them, with
multiple spaces or tab between them, or even on three different lines as in the following examples:
The type of number requested here is an integer, so integers should be entered. Providing a real
number or character (e.g., letter) would generate an error. Later chapters will address how to deal with
such errors.
6.3 Example
Below is an example program that calculates the area of a circle. The program will declare the
appropriate variables, read the radius, calculate the circle area, and display the result.
program circle
! Program to calculate the area of a circle
! Declare variables
implicit none
real :: radius, area
real, parameter :: pi = 3.14159
! Display result
write (*,*) "Circle Area: ", area
The comments are not required, but help make the program easier to read and understand. If the
program does not work at first, the comments can aid in determining the problem.
33
Chapter 6 ► Simple Input and Output
6.4 Exercises
Below are some quiz questions and project suggestions based on this chapter.
3) What are the statements to declare and read the value for a person's age in years?
2) Modify the circle area program to request a circle diameter. The formula for circle area must be
adjusted accordingly. Recall that radius = diameter divided by two. Test the program on
several sets of input.
3) Type in the velocity program from the previous chapter and update to prompt for and request
input for the acceleration and time, and then display the results. Test the program on several
sets of input.
4) Write a Fortran program to read the length of the a and b sides of a right triangle and compute
the perimeter length. The program should prompt for input and display the values for sides a, b,
c, and the perimeter with appropriate headings.
c= √ a2+ b2 c
a
perimeter = a +b+ c
b
Test the program on several sets of input.
34
Chapter 6 ◄ Simple Input and Output
5) Write a Fortran program to compute geometric information for a kite. The program should read
the a, c and p lengths and compute the q length. The program should display c
an appropriate prompt, read the values, compute the answer, and display the
original input and the final result.
q p
The formula for the q length is as follow:
a
√ √
2 2
p p
q = a2 − + c2 −
4 4
35
Chapter 6 ► Simple Input and Output
36
7 Program Development
Writing or developing programs is easier when following a clear methodology. The main steps in the
methodology are:
● Understand the Problem
● Create the Algorithm
● Implement the Program
● Test/Debug the Program
To help demonstrate this process in detail, these steps will be applied to a simple problem to calculate
and display the period of a pendulum.
As additional examples are presented in later chapters, they will be explained and presented using this
methodology.
Period = 2 π
√ (
L
g
1+
1
4 ( ))
sin 2
α
2
α
Where:
g = 980 cm/sec2 L
π = 3.14159
L = Pendulum length (cm)
α = Angle of displacement (degree)
Both g (gravity) and π should be declared as a constants. The formula is a simplified version of the
more general case. As such, for very large, very small, or zero angle values the formula will not
provide accurate results. For this example, that is acceptable.
As shown, the pendulum is attached to a fixed point, and set into motion by displacing the pendulum
by an angle, α, as shown in the diagram. The program must define the constants for g and π, declare
the variables, display appropriate prompts, read the values for L and α, then calculate and display the
original input and the period of the pendulum with the given length and angle of displacement.
37
Chapter 7 ► Program Development
! declare variables
! real constants -> gravity, pi
! reals -> angle, length, alpha
! display initial header
! prompt for and read the length and angle values
! convert degrees to radians
! calculate the period
! display the results
While this is a fairly straightforward algorithm, more complex problems would require more extensive
algorithms. Examples in later chapters will include more complex programs. For convenience, the
steps are written as program comments. This will allow the addition of the code to the basic algorithm.
program period
! Program to calculate the period of a pendulum
! declare variables
! real constants -> gravity, pi
! reals -> angle, length, alpha
implicit none
real :: angle, length, pperiod, alpha
38
Chapter 7 ◄ Program Development
The indentation is not required, but helps make the program easier to read. Note that the “2”, “1”, and
“4” in the algorithm are entered as 2.0, 1.0, and 4.0 to ensure consistent data typing (i.e., all reals).
When 1 divided by 4 is entered as “1/4” instead of “1.0/4.0” the result will be 0 because that would be
integer division.
C:\mydir> period
C:\mydir>
For this program, the results can be verified with a calculator. A series of different values should be
used for testing. If the program does not work, the program comments provide a checklist of steps and
can be used to help debug the program.
39
Chapter 7 ► Program Development
wrote (*,*)
1
Error: Unclassifiable statement at (1)
The first digit, 13 in this example, represents the line number where the error occurred. Using a text
editor that displays line numbers, the statement that caused the error can be quickly found and
corrected.
If the declaration for the variable length is omitted, the error would appear as follows:
In this case, the error is shown on line 18 (first digit after the “:”). However, the actual error is that the
variable length is not declared. Each error should be reviewed and evaluated.
40
Chapter 7 ◄ Program Development
c:\mydir> period
Pendulum Period Calculation Program
The program was expecting numeric values and letters were provided. Since letters are not meaningful
in this context, it is an error and the program “crashes” or stops with an error message.
Later chapters will provide additional information on how to deal with such errors. Until then,
providing the correct data type will avoid this kind of error.
The 1 over 4 is entered as “1/4” which are interpreted as integers. As integers, “1/4” results in 0. The
compiler will accept this, perform the calculations, and provide an incorrect result.
The program would compile and execute as follows.
c:\mydir> period
Pendulum Period Calculation Program
However, an incorrect answer would be generated as shown. This is why testing the program is
required. Logic errors can be the most difficult to find.
One of the best ways to handle logic errors is to avoid them by careful development of the algorithm
and writing the code.
If the program has a logic error, one way to find the error is to display intermediate values. Further
information will be provided in later chapters regarding advice on finding logic errors.
41
Chapter 7 ► Program Development
7.5 Exercises
Below are some quiz questions and project suggestions based on this chapter.
3) If a program to compute the area of a rectangle uses a formula, height × height × width, what
type of error would this be?
2) Create a program to prompt for and read the circle area from the user and calculate the
circumference of a circle using the following formula:
circumference = 2 √ π CircleArea
Test the program using several different input values.
3) Create a program to prompt for and read the radius of a sphere from the user and calculate the
surface area of the sphere using the following formula:
4) Create a program to prompt for and read the radius of a sphere from the user and calculate the
sphere volume using the following formula:
sphereVolume = (4 π / 3) r 3
42
8 Selection Statements
When writing a program, it may be necessary to take some action based on the outcome of comparing
the values of some variables. All programming languages have some facility for decision-making.
That is, doing one thing if some condition is true and (optionally) doing something else if it is not.
Fortran IF statements and/or CASE statements are used to allow a program to make decisions.
The normal form will be used for examples in this text. However, the alternate form may be used at
any time. The alternate forms may be required to support older Fortran programs.
A relational operation is used to form a conditional expression. The result of a conditional expression
must always result in either a true or false result.
The “==” (two equal signs) is used to compare. The “=” (single equal) is used for assignment (setting
a variable). The “==” does not change any values, while the “=” does.
For example, given the declaration of,
integer :: gameLives
43
Chapter 8 ► Selection Statements
Which will result in a true or false result based on the value of the variable gameLives.
Logical operators are used to combine conditional expressions as needed to form a more complex
conditional expression. For example, given the declaration of,
integer :: gameLives, extraLives
it might be useful to know if the current value of gameLives and extraLives are both 0 which would
indicate the game is over. In this case, the relational operator would be AND with the complete
conditional expression,
( (gameLives == 0) .and. (extraLives == 0) )
which will result in a true or false result. Since the AND logical operation is used, the final result will
be true only if both conditional expressions are true.
Another way of check the status to determine if the game should continue might be,
( (gameLives > 0) .or. (extraLives > 0) )
which still results in a true or false result. However, since the OR logical operation is used, the final
result will be true if either conditional expressions is true.
The relational operators (e.g., <, <=, >, >=, ==, /=) have higher precedence than logical operators
(AND, OR, NOT). This means each of the smaller conditional expressions will be completed before
the logical operation is applied.
A conditional expression can be a combination of multiple conditional expressions combined with
logical operators.
8.3 IF Statements
IF statements are used to perform different computations or actions based on the result of a conditional
expression (which evaluates to true or false). There are a series of different forms of the basic IF
statement. Each of the forms is explained in the following sections.
44
Chapter 8 ◄ Selection Statements
Where the <fortran statements> may include one or more valid Fortran statements.
For example, given the declaration of,
integer :: gameLives
which will display the message “Game Over.” and “Please try again.” on the next line if the value of
gameLives is equal to 0.
In this form, only a single statement is executed if the conditional expression evaluates to true. The
previous example might be written as;
if ( gameLives == 0 ) write (*,*) "Game Over."
In this form, no “then” or “end if” are required. However, only one statement can be executed.
Where the <fortran statements> may include one or more valid Fortran statements.
45
Chapter 8 ► Selection Statements
based on the current value of gameLives is, a reasonable IF THEN ELSE statement might be:
if ( gameLives > 0 ) then
write (*,*) "Still Alive, Keep Going!"
else
write (*,*) "Extra Life Granted."
gameLives = 1
end if
Which will display the message “Still Alive, Keep Going!” if the value of gameLives is greater than 0
and display the message “Extra Life Granted.” if the value of gameLives is less than or equal to 0.
Where the <fortran statements> may include one or more valid Fortran statements.
For example, given the declaration of,
integer :: gameLives
based on the current value of gameLives, a reasonable IF THEN ELSE IF statement might be:
if ( gameLives > 0 ) then
write (*,*) "Still Alive, Keep Going!"
else if ( gameLives < 0 ) then
write (*,*) "Sorry, game over."
else
write (*,*) "Extra Life Granted."
gamesLives = 1
end if
Which will display the message “Still Alive, Keep Going!” if the value of gameLives is greater than 0,
display the message “Sorry, game over.” if the value of game lives is < 0, and display the message
“Extra Life Granted.” if the value of gameLives is equal to 0.
46
Chapter 8 ◄ Selection Statements
To help demonstrate this process in detail, these steps will be applied to a familiar problem as an
example. The example problem is to calculate the solution of a quadratic equation in the form:
a x2 + b x + c = 0
−b ± √ (b 2−4 a c)
x =
2a
In the quadratic equation, the term ( b 2−4 a c ) is the discriminant of the equation. There are three
possible results for the discriminant as described below:
● If ( b 2−4 a c ) > 0 then there are two distinct real roots to the quadratic equation. These two
solutions represent the two possible answers. If the equation solution is graphed, the curve
representing the solution will cross the x-axis (i.e., representing x=0) in two locations.
● If ( b 2−4 a c ) = 0 then there is a single, repeated root to the equation. If the equation solution
is graphed, the curve representing the solution will cross the x-axis in one location.
● If ( b 2−4 a c ) < 0 then there are two complex roots to the equation. If the equation solution is
graphed, the curve representing the solution will not cross the x-axis and therefore there no real
number solution. However, mathematically the square root of a negative value will provide a
complex result. A complex number includes a real component and an imaginary component.
A correct solution must address each of these possibilities. For this problem, it is appropriate to use
real values.
47
Chapter 8 ► Selection Statements
The relationship between the discriminant and the types of solutions (two different solutions, one
repeated solution, or no real solutions) is summarized in the below table:
X X
The examples provided above are included in the example solution in the following sections.
! declare variables
! reals -> a, b, c, discriminant, root1, root2
! display initial header
! read the a, b, and c values
48
Chapter 8 ◄ Selection Statements
! if discriminant is >0,
! calculate and display root1 and root2
! if discriminant is <0,
! calculate and display complex root1 and root2
program quadratic
! Quadratic equation solver program
! declare variables
! reals -> a, b, c, discriminant, root1, root2
implicit none
real :: a, b, c
real :: discriminant, root1, root2
! if discriminant is 0,
! calculate and display root
if ( discriminant == 0 ) then
root1 = -b / (2.0 * a)
write (*,*) "This equation has one root:"
write (*,*) "root = ", root1
end if
! if discriminant is >0,
! calculate and display root1 and root2
if ( discriminant > 0 ) then
root1 = (-b + sqrt(discriminant)) / (2.0 * a)
root2 = (-b - sqrt(discriminant)) / (2.0 * a)
write (*,*) "This equation has real roots:"
write (*,*) "root 1 = ", root1
write (*,*) "root 2 = ", root2
end if
! if discriminant is <0,
! calculate and display complex root1 and root2
49
Chapter 8 ► Selection Statements
The indentation is not required, but does help make the program easier to read.
C:\mydir> quad
Quadratic Equation Solver Program
Enter A, B, and C values
2 4 2
This equation has one root:
root = -1.0000000
C:\mydir> quad
Quadratic Equation Solver Program
C:\mydir> quad
Quadratic Equation Solver Program
Enter A, B, and C values
3 3 3
This equation has complex roots:
root 1 = -0.50000000 +i 0.86602539
root 2 = -0.50000000 -i 0.86602539
C:\mydir>
50
Chapter 8 ◄ Selection Statements
where value, value-1, and value-2 are constants or literals. The type of these constants must be
identical to that of the selector.
• The first form has only one value
• The second form means all values in the range of value-1 and value-2 (inclusive). In this form,
value-1 must be less than value-2
• The third form means all values that are greater than or equal to value-1
• The fourth form means all values that are less than or equal to value-2
In order, each selector expression is evaluated. If the variable value is the selector or in the selector
range, then the sequence of statements in <fortran statement(s)> are executed.
If the result is not in any one of the selectors, there are two possibilities:
• if CASE DEFAULT is there, then the sequence of statements in statements-DEFAULT are
executed, followed by the statement following END SELECT
• if the CASE DEFAULT is not there, the statement following END SELECT is executed
51
Chapter 8 ► Selection Statements
The constants listed in selectors must be unique. The CASE DEFAULT is optional. But with a CASE
DEFAULT, you are guaranteed that whatever the selector value, one of the labels will be used. The
place for CASE DEFAULT can be anywhere within a SELECT CASE statement; however, putting it at
the end would be more natural.
For example, given the declarations,
integer :: hours24, hours12, year
logical :: isAM
might be useful to convert 24-hour time into 12-hour time. In this example, a logical variable isAM is
used to indicate AM (true) or PM (false).
Additionally, the selectors can be combined and separated by commas. For example, given the
declarations,
integer :: monthnumber, daysinmonth
case default
write (*,*) "Error, month number not valid."
end select
52
Chapter 8 ◄ Selection Statements
might be useful to determine the number of days in a given month. The leap-year calculation is not
complete, but is adequate if the range of the year is sufficiently limited.
A B C D F
A>=90 80 - 89 70 - 79 60 - 69 <=59
The program will read three test scores, compute the average, and display the appropriate grade based
on the average.
Next, the average can be calculated. The average will be converted to the nearest integer and, based on
that, the appropriate grade can be determined and displayed. Formalizing this, the following steps can
be developed.
! calculate the testave and convert to integer
! determine grade
! A - >= 90
! B - 80 to 89
! C - 70 to 79
! D - 60 to 69
! F - <= 59
53
Chapter 8 ► Selection Statements
program grades
! declare variables
implicit none
real :: test1, test2, test3
integer :: testave
! determine grade
! A → >= 90, B → 80-89, C → 70-79, D → 60-69, F → <= 59
The indentation is not required, but does help make the program easier to read.
C:\mydir> grade
Grade Assignment Program
54
Chapter 8 ◄ Selection Statements
Grade is: B
C:\mydir>
The program should be tested with a series of data items to ensure appropriate grade assignment for
each grade. Test values for each grade should be entered for the testing.
8.7 Exercises
Below are some quiz questions and project suggestions based on this chapter.
3) For each of the following, answer .true. or .false. in the space provided.
( b1 .or. b2 ) ______________
( b1 .or. b3 ) ______________
( b1 .and. b2 ) ______________
( j < i ) ______________
4) Write the Fortran IF THEN statements to display the message "Game Over" if the integer
variable lives is ≤ to 0. You may assume the variable lives is already declared as an integer
and initialized.
5) Write the Fortran IF THEN statements to check the integer variable num and if the value is < 0,
take the absolute value of the number and display the message, "Variable num was made
positive". You may assume the variable num is already declared as an integer and initialized.
55
Chapter 8 ► Selection Statements
x
6) Write the Fortran statements to compute the formula z = assuming the values for integer
y
variables x, y, and z are previously set. However, if y = 0, do not compute the formula, set z =
0, and display an error message, "Z not calculated". You may assume the variables x, y, and z are
already declared as an integers and initialized.
7) Write the statements required to compute the following formula using real variables f, x, and y.
Use a single IF THEN ELSE IF statement. You may assume the values for f, x, and y have
already been declared as real values and initialized.
{
2
f ( x)= x ∗ y if x≤0.0
x∗ y if x> 0.0
2) Write a Fortran program to prompt for and read the year that a person was born. The year must
be between 1900 and 2015 (inclusive). If an invalid entry is read, the program should display
the message, "Sorry, that is not a valid year." and re-prompt. If the correct value is not provided
after 3 attempts, the program should display the message "Sorry, you're having problems.
Program terminated." and terminate. Once a valid year is read, the program should display the
year and a message "is a leap year" or "is not a leap year". Include appropriate declarations,
prompts, read statements, calculations, and write statements. Test the program on a series of
input values and verify that the output is correct.
3) Type in the grades program, compile, and execute the program. Test the program on a series of
input values that will check each grade.
A A- B+ B B- C+ C C- D F
³94 93-90 89-87 86-84 83-80 79-77 76-74 73-70 69-60 £59
Compile, and execute the program. Test the program on a series of input values that will check
each grade.
56
Chapter 8 ◄ Selection Statements
5) Write a Fortran program to prompt and read the Fahrenheit as an integer, convert to Celsius, and
display the result as a real. The formula to convert a Fahrenheit temperature to a Celsius
temperature is as follows:
celsius = ( 59 ) ( fahrenheit − 32 )
The Fahrenheit value must be between -50 and 150 (inclusive). If the Fahrenheit value is out of
range, the program should display an error message, "Temperature out of range", and terminate.
The calculations must be performed as real. Include program statements, appropriate
declarations, prompts, read statements, calculations, and write statements. Test the program on
a series of input values.
6) Write a Fortran program that reads an item cost (real numbers) and amount tendered (real
number) and compute the correct change. The correct change should be returned as the number
of twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. The main program should
ensure that the amount paid exceeds the item cost and, if not, display an appropriate error
message. Test the program multiple times using a series of input values.
7) Write a Fortran to program that reads a number from the user that represents a television
channel and then uses a CASE construct to determine the call letters for that station.
57
Chapter 8 ► Selection Statements
58
9 Looping
When a series of Fortran statements need to be repeated, it is referred to as a loop or do-loop. A
Fortran do-loop is a special control statement that allows a Fortran statement or set of statements to be
executed multiple times. This repetition can be based on a set number of times, referred to as counter
controlled, or based on a logical condition, referred to as conditionally controlled. Each of these
looping methods is explained in the following sections.
where the count variable must be an integer variable, start, stop, and step are integer variables or
integer expressions. The step value is optional. If it is omitted, the default value is 1. If used, the step
value cannot be zero. The <fortran statement(s)> is a sequence of statements and is referred to as the
body of the do-loop. You can use any executable statement within a do-loop, including IF-THEN-
ELSE-END IF and even another do-loop. Before the do-loop starts, the values of start, stop, and step
are computed exactly once. More precisely, during the course of executing the do-loop, these values
will not be re-computed.
The count variable receives the value of start variable or expression. If the value of control-var is less
than or equal to the value of stop-value, the <fortran statement(s)> part is executed. Then, the value of
step (1 if omitted) is added to the value of control-var. At the end, the loop goes back to the top and
compares the values of control-var and stop-value.
If the value of control-var is greater than the value of final-value, the do-loop completes and the
statement following end do is executed.
For example, with the declarations,
integer :: counter, init=1, final=10, sum=0
will add the numbers between 1 and 10 which will result in 55. Since the step was not specified, it is
defaulted 1.
59
Chapter 9 ► Looping
sum = 0
do number = 1, count
read (*,*) input
sum = sum + input
end do
The use of the function real() converts the sum and count variables from integers to real values as
required for the average calculation. Without this conversion, sum/count division would be interpreted
as dividing an integer by an integer, yielding an integer result.
A final example of a counter controlled loop is to compute the factorial of a positive integer. The
factorial of an integer n, written as n!, is defined to be the product of 1, 2, 3, ..., n-1, and n. More
precisely, n! = 1 * 2 * 3 * ... * n.
integer :: factorial, n, i
factorial = 1
do i = 1, n
factorial = factorial * i
end do
60
Chapter 9 ◄ Looping
The do-loop above iterates n times. The first iteration multiplies factorial with 1, the second iteration
multiplies factorial with 2, the third time with 3, ..., the ith time with i and so on. Thus, the values that
are multiplied with the initial value of factorial are 1, 2, 3, ..., n. At the end of the do-loop, the value of
factorial is 1 * 2 * 3 * ... * n which is n!.
will display the numbers from 1 to 4 skipping the remaining iterations. Since the variable i is checked
before the write statement, the value is not displayed with i is 5 and the loop is exited without
completing the remaining iterations. While it is possible to have multiple exit statements, typically
only one is used. However, multiple exit statements may be required for more complex problems.
The cycle statement will skip the remaining portion of the do-loop and start back at the top. The cycle
statement can be used in a counter controlled loop or a conditionally controlled loop. If the cycle
statement is used within a counter controlled loop, the next index counter is updated to the next
iteration, which could terminate the loop.
For example, given the following declarations,
integer :: i
61
Chapter 9 ► Looping
The square of the sum of the first ten natural numbers is,
1 2 ⋯ 102 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of
the sum is 3025 - 385 = 2640.
The program will display the N value, the sum of the squares, the square of the sum, and the difference
for each number from 2 to a given N value. The program should prompt for and read the N value. The
program will display appropriate headers.
! declare variables
! integer -> i, n, SumOfSqrs, SqrOfSums
! display initial header
! prompt for and read the n value
! loop from 1 to n
! compute sum of squares
! compute sums
! square the sums
! compute difference between sum of squares and square of sums
! display results
program SOSdifference
! declare variables
implicit none
integer :: i, n, SumOfSqrs=0, SqrOfSums=0, difference
62
Chapter 9 ◄ Looping
! loop from 1 to n
do i = 1, n
! compute sum of squares
SumOfSqrs = SumOfSqrs + i**2
! display results
write (*,*) "Difference: ", difference
The spacing and indentation are not required, but help to make the program more readable.
63
Chapter 9 ► Looping
In this form, the conditional expression is re-checked at the top of the loop on each iteration.
A more general format of the conditional loop is:
do
<fortran statement(s)>
end do
As is, this loop will continue forever. Probably not so good. A selection statement, such as an IF
statement, and an exit statement would be used to provide a means to terminate the looping.
For example,
do
<fortran statement(s)>
if (conditional expression) exit
<fortran statement(s)>
end do
Would stop looping only when the conditional expression evaluates to true. The exit statement can be
used multiple times in different locations as needed. An IF statement, in any form, can be used for
either the exit or cycle statements.
For example, a conditional loop could be used to request input from the user and keep re-prompting
until the input is correct.
integer :: month
do
write (*,*) "Enter month (1-12): "
read (*,*) month
if (month >= 1 .and. month <= 12) exit
write (*,*) "Error, month must be between 1 and 12."
write (*,*) "Please re-enter."
end do
This will keep re-prompting an unlimited number of times until the correct input (a number between 1
and 12) is entered.
64
Chapter 9 ◄ Looping
Since a counter controlled DO loop requires an integer loop counter, another use of conditional loops
would be to simulate a real counter. For example, to display the values from 1.5 to 4.5 stepping by
0.25, the following conditional loop could be used.
real :: currValue = 1.5
The values of currValue and amount of the increment, set as 0.25, can be adjusted as needed.
! loop
! request month, day, and year
! read month, day, and year
! check month (1-12)
! check year (1970-2020)
! check day
! 1,3,5,7,8,10,12 → 31 days
! 4,6,9,11 → 30 days
! 2 → if modulo of year/4 is 0 → 29 days
65
Chapter 9 ► Looping
program dateCheck
! declare variables
implicit none
integer :: month, day, year, dayMax
! loop
do
! request month, day, and year
write (*,*) "Enter month, day, and year"
! check day
! 1,3,5,7,8,10,12 → 31 days
! 4,6,9,11 → 30 days
! 2 → if modulo of year/4 is 0 → 29 days
! 2 → if modulo of year/4 is not 0 → 28 days
66
Chapter 9 ◄ Looping
exit
! end loop
end do
! display results
write (*,*) "Valid Date is:", month, day, year
The spacing and indentation are not required, but help to make the program more readable.
9.6 Exercises
Below are some quiz questions and project suggestions based on this chapter.
67
Chapter 9 ► Looping
5) If there are multiple cycle statements in a loop, which one will be executed?
6) What is the output of the following Fortran statements. Assume sum and i are declared as
integers.
sum = 0
do i = 1, 5
sum = sum + i
end do
write (*,*) "The SUM is:", sum
7) What is the output of the following Fortran statements. Assume i and j are declared as integer.
8) Are the following Fortran statements valid or invalid? If valid, what will happen?
do i = 3, 2
write (*,*) i
end do
9) Are the following Fortran statements valid or invalid? If valid, what will happen?
do i = 3, 2
if ( i == 3 ) then
write (*,*) i
end do
end if
11) When IF statements (any form) are nested inside a loop, what must be done to ensure the
statements are valid?
68
Chapter 9 ◄ Looping
2) Type in the date check program, compile, and execute the program. Test the program on a
series of different input values.
3) Write a program to calculate the range that a ball would travel when it is thrown with an initial
velocity v0 and angle θ. Based on an initial velocity provided by the user, calculate the range
every 5 degrees for angles between 5 and 85 degrees. If we assume negligible air friction and
ignore the curvature of the earth, a ball that is thrown into the air from any point on the earth's
surface will follow a parabolic flight path.
Origin Impact
θ Time
The range (distance between the initial origin and final impact) is determined by the formula:
2 v 20
range = − cos θ sin θ
g
where v0 is the initial velocity of the ball, θ is the angle of the throw, and g is the acceleration
due to the earth's gravity. The value for gravity should be defined as a constant and set to -9.81
meters per second.
Note, the intrinsic trigonometric functions work in radians, so the angle in degrees will need to
be converted to radians for the calculations. To convert degrees to radians:
69
Chapter 9 ► Looping
70
10 Formatted Input/Output
Fortran uses a FORMAT statement to allow control of how data is displayed or read. This is useful
when very specific input or output is required. For example, displaying money figures typically require
exactly two decimal places. There are format specifiers for each data type; integer, real, character,
logical, and complex.
10.1 Format
The format specifiers, separated by commas, are contained in a pair of parenthesis as a string literal.
There are multiple possible ways to define a format. However, we will focus on the easiest, most direct
method. The format specifier will replace the second “*” in the read or write statements. For example:
read (*,'(<format specifiers>)') <variables>
write (*,'(<format specifiers>)') <variables/expressions>
The following sections explain the options for the format specifiers.
Description Specifier
Integers rIw or rIw.m
Real rFw.d
Logicals rLw
Characters rA or rAw
71
Chapter 10 ► Formatted Input/Output
In addition, each specifier or group of specifiers can be repeated by preceding it with a repeat count.
Format specifiers for complex numbers will be addressed in later chapters.
the following write statement can be used to display the value in variable num1 with no leading or
trailing spaces.
write (*,'(i2)') num1
Which will display “42123” with no spaces between the two different values. However,
write (*,'(i2,i4)') num1, num2
will display “42 123” with one space between the values. Further,
write (*,'(i5,i5,i5)') num1, num2, num3
will display “ 42 123 4567” where each variable uses 5 spaces. And, finally,
write (*,'(i6.4)') num1
72
Chapter 10 ◄ Formatted Input/Output
the following write statement can be used to display the value in variable var1 with no leading or
trailing spaces.
write (*,'(f3.1)') var1
Which will display “4.5” with no leading spaces. Multiple variables can be displayed. For example,
to display the values in variables var1 and var2.
write (*,'(f5.2,f8.3)') var1, var2
Which will display “ 4.50 12.000”. Another example with three variables, var1, var2, and var3, is
as follows:
write (*,'(f10.4,f10.4,f10.4)') var1, var2, var3
Which will display “ 4.5000 12.0000 2145.5713” where each variable uses 10 spaces
with each having exactly 4 digits after the decimal point.
Although we may print a number using as many positions as you want, this is only for input/output
formatting. The number of positions or size is not the precision (i.e., the number of significant digits)
of that number. The default precision of real numbers is about seven significant digits. This is the
precision of real numbers. However, we can print a real number using 50 positions in which 25
positions are for the fractional part. This is only a way of describing the appearance and does not
change the precision of real numbers.
73
Chapter 10 ► Formatted Input/Output
For example,
write (*,’(a,2x,a,t20,a)’) "X", "Y", "Z"
The initial X and Y are separated by two spaces. The final Z is place in the 20 column.
the following write statement can be used to display the value in the logical variables dooropen and
windowopen with no leading or trailing spaces. It should be noted that only a T or F will be displayed.
The following write statement,
write (*,'(l1,1x,l1)') dooropen, windowopen
will display “ T F” , which will display a total of 8 characters; two spaces and a T from the right
justified L3 (__T), followed by 2 spaces from the 2X (__), and then two spaces followed by an F from
the L3 (__F).
74
Chapter 10 ◄ Formatted Input/Output
the following write statement can be used to display the string in variable msg with no leading or
trailing spaces. The following write statement,
write (*,'(a11)') msg
will display “Hello World”. The count is not required when using the character format specifier.
For example, the statement,
write (*,'(a)') msg
will display the same “Hello World” string. Multiple variables or strings can be displayed. Also, the
count can be used to display a portion of the string. For example, to display the string in variable msg
and the string “Goodbye cruel world”.
write (*,'(a9,2x,a)') msg, "Goodbye cruel world"
Which will display “Hello Wor Goodbye cruel world” to the screen. Note that for the first
string variable, msg, only the first 9 characters of the 11 total characters are displayed since the A9
format was used.
Which, when executed, the input is entered on the line following the prompt.
c:\mydir> sums
Example Program
Difference between sum of squares
and square of sums
75
Chapter 10 ► Formatted Input/Output
When the advance clause is used with the setting of “no”, as follows:
! prompt for and read the n value
write (*,'(a)', advance="no") "Enter count to sum: "
read (*,*) n
Which allows the input to be entered on the same line as the prompt.
10.9 Example
This example will read a date from the user (month, day, and year, on the same line), determine the day
of week (for that month/day/year). Then, the program will display the original input date (numeric
form) and the formatted date. The original input date will be displayed with the applicable fields
including the leading 0's (i.e., 01/01/2010).
The value of daynum is 0 for a Sunday, 1 for a Monday, 2 for a Tuesday, etc.
76
Chapter 10 ◄ Formatted Input/Output
Then the program can calculate the day of the week (based on the formula) and convert the resulting
number (0-6) into a date string and display the result.
! calculate day of week
! convert day of week (0-6) to string
! convert month (1-12) to string
! display formatted string for day, month, and year
program dateFormatter
! declare variables
implicit none
integer :: month, day, year
integer :: a, m, y, d
character(9) :: amonth, day_of_week
! ----------
! display initial header
write (*,*) "Date Formatting Example"
! ----------
! display formatted numeric month/day/year
! ----------
! calculate day of week
a = (14 - month) / 12
y = year - a
m = month + 12 * a - 2
77
Chapter 10 ► Formatted Input/Output
! ----------
! convert day-of-week integer to day-of-week string
! ----------
! convert month (1-12) to string
select case (month)
case (1)
amonth = "January "
case (2)
amonth = "February "
case (3)
amonth = "March "
case (4)
amonth = "April "
case (5)
amonth = "May "
case (6)
amonth = "June "
case (7)
amonth = "July "
case (8)
amonth = "August "
case (9)
amonth = "September"
case (10)
amonth = "October "
case (11)
amonth = "November "
case (12)
amonth = "December "
78
Chapter 10 ◄ Formatted Input/Output
end select
! ----------
! display formatted string for day, month, and year
The spacing and indentation is not required, but help to make the program more readable. The trim()
intrinsic function removes any trailing spaces from the input string. Additional information regarding
handling character data types is provided in the following section.
10.10 Exercises
Below are some quiz questions and project suggestions based on this chapter.
79
Chapter 10 ► Formatted Input/Output
4) What is the write statement and format specifier to output the integer variable num1 which
contains a value between 0 and 999 (right justified, no leading zero's, no additional spaces).
5) What is the write statement and format specifier to output the real value of pi which has been
initialized to 3.14159 (right justified, no additional spaces)?
6) What is the single write statement and format specifier to output "Programming" and "Is Fun!"
on two different lines?
7) What is the single write statement and format specifier to output "Enter Number:" and leave the
cursor on the current line?
2) Update the date formatting program to perform complete error checking on the date entered.
That is, the program should check for appropriate values for month (between 1 and 12), check
for appropriate values for date (between 1 and 31), including checking for a valid date for the
specific month, and ensure that the value for year is between 1970 and 3000 (inclusive). For
example, April 31 is not a valid date. Additionally, the program should check for a leap year to
see if February has 28 or 29 days for that year. Test the program on a series of different input
values and verify that the output is correct for those input values.
3) Write a Fortran program that displays an amortization schedule. The program should read the
loan amount, annual interest rate, and the loan term in months (from a single line).
The formula for calculating the monthly payment is:
80
Chapter 10 ◄ Formatted Input/Output
Output will consist of appropriate headings and aligned and formatted columns for payment
number, monthly payment, principal paid, interest paid, and outstanding balance. A sum will
appear at the bottom of each column.
Loan amounts shall not exceed $250,000 and the maximum loan term shall not exceed 360
months. Be sure to follow the requirement that the three input variables will be formatted on a
single line.
4) Write a Fortran program that calculates and displays compounded interest. The program should
read the initial principal amount, interest rate percentage, and the term (number of years). The
program should display a summary of the input and the yearly compounded interest. Refer to
the example output for formatting.
The formula for compounding interest is:
value = principal( 1+interest ) year
Note, the interest rate percentage read from the user must be converted to a number (i.e.,
divided by 100). The output must be formatted in a manner similar to the example output. This
includes ensuring that the dollar amounts are displayed with the appropriate two decimal points.
Test the program on a series of different input values and verify that the output is correct for
those input values.
81
Chapter 10 ► Formatted Input/Output
82
11 Characters and Strings
Fortran was originally developed for scientific and engineering application requiring significant
mathematical calculations. However, the Fortran 95/2003/2008 language includes extensive character
and string handling capabilities.
Character and string constants are case sensitive. So, character “X” (upper-case) is not the same as “x”
(lower-case). When a digit is enclosed in quotes, it is treated as a character and consequently
arithmetic operations (addition, subtraction, etc.) are not allowed.
A string is a series of characters. A string consists of an arbitrary sequence of characters also enclosed
in quotes. Some examples include:
"Hello World."
"456"
"1 2 3"
"456?"
"Goodbye cruel world!!"
"Have a nice day?"
Since digits enclosed in quotes are not numeric values, the strings “1 2 3” and “456?” are allowed.
A problem arises if you want to have a quote in the string itself. A double quote will be interpreted as a
single within a string. The two quotes must be together (no spaces between). For example, the string:
"He said ""wow"" when he heard"
Would be displayed as
"He said "wow" when he heard"
The double-quote is sometimes referred to as an escape character. Strings and characters must be
associated with the character data type.
83
Chapter 11 ► Characters and Strings
For character variables, the type is “character”. For example, to define a character variable to hold the
day of week (i.e., “Wednesday”), the following declaration,
character(len=9) :: dayofweek
Would define the variable, dayofweek, with a maximum length of 9 possible characters.
Additional examples include:
character(len=3) :: symbol1, symbol2
character :: symbol3
character(1) :: symbol4, symbol5
character(30) :: symbol6, symbol7
The declarations can be entered in any order, however they must be at the beginning of the program.
The “len=” is optional and can be omitted. When the length is omitted entirely, the default length is set
to 1. This, “character”, “character(len=1), and “character(1)” are all the same.
When multiple variables are included in a single declaration, they must all be the same length. If
different lengths are required, separate declaration lines are required.
Spaces or no spaces between the variables, equal signs, semicolons, and commas are allowed.
Variables initialized at declaration can be changed during program execution as needed.
84
Chapter 11 ◄ Characters and Strings
This instructs the Fortran compiler to count the characters and set the appropriate length.
When character variables are assigned, they are filled from the left and automatically padded with
blanks if necessary. For example, if the variable thismonth is reset
thismonth = "May"
The variable thismonth contains “May ” (e.g., “May” with an additional 6 blanks).
Characters variables and literals may be used with concatenation. For example, given the following
declaration,
character(len=6) :: str1="ABCDEF", str2="123456"
character(len=12) :: str3
85
Chapter 11 ► Characters and Strings
This is a result of the relational operations referring to the assigned values (based on their location in
the ASCII table located in Appendix A).
Comparisons between digits, “0” - “9”, will work relative to each other. Comparisons between upper-
case letters, “A” - “Z”, will also work relative to each other. Comparisons between lower-case letters,
“a” - “z”, will also work relative to each other. Since the lower case letters are after the upper case
letters in the table an upper-case letter will be less than a lower-case letter. The digits are in the table
before the letters (upper- and lower-case), so they will evaluate as less than letters. This must be taken
into account when dealing with character comparisons.
86
Chapter 11 ◄ Characters and Strings
11.10 Example
This example will scan a string and convert all lower-case letter to upper-case.
87
Chapter 11 ► Characters and Strings
program caseConverter
! declare variables
implicit none
integer :: i, strlen
character(80) :: string1
! ----------
! display initial header
write (*,'(a,/)') "Case Conversion Example"
! ----------
! prompt for string
! read string
write (*,'(a)',advance="no") "Enter String (80 char max): "
read (*,'(a)') string1
! ----------
! trim any trailing blanks
! determine length of string
strlen = len(trim(string1))
! loop
do i = 1, strlen
end do
! ----------
! display final string
The spacing and indentation are not required, but help to make the program more readable.
88
Chapter 11 ◄ Characters and Strings
-------------------------------------
Final String:
HELLO WORLD!?
Each lower-case letter was converted to upper-case while the upper-case, space, and punctuation were
unchanged. The program should be executed with a series of test inputs to verify the correct output.
11.11 Exercises
Below are some quiz questions and project suggestions based on this chapter.
89
Chapter 11 ► Characters and Strings
astr1 = str1(1:3)
astr2 = str3(4:6)
astr3 = str3 // str4
astr4 = str2(4:6) // str3(1:3) // str1(2:3)
4) How can the integer value (based on the ASCII table) of a character be obtained?
5) How can integer value be converted to a character (based on the ASCII table)?
2) Update the case conversion example program to convert any upper-case characters to lower-
case characters. Test the program on a series of different input values and verify that the output
is correct for those input values.
3) Write a program to read a string and count the vowels (“a”, “e”, “i”, “o”, and “u”). The
program should provide a count for each vowel and a total count of vowels. The program
should ensure that the vowels are counted for both upper and lower-case. Test the program on a
series of different input values and verify that the output is correct for those input values.
4) Write a program to read 5 strings (≤ 80 characters each) and display the strings in alphabetical
order. Test the program with a variety of different input strings, including digits, upper-case,
and lower-case characters. Test the program on a series of different input values and verify that
the output is correct for those input values.
90
12 File Operations
File operations allow Fortran programs to read from files and/or write to files. The basic read and write
statements for file operations are the same as previously used with some additional information or
clauses.
Clause Explanation
unit Unit number for subsequent file operations (i.e.,
read, write, etc.). Typically an integer between 10
and 99.
file Name of file to be opened. Can be character literal
or a character variable.
status Status of file. Allowable options “old”, “new”, or
“replace”
“old” → the file must already exist.
“new” → a new file will be created.
“replace” → a new file will be created,
replacing an existing one if necessary.
action Action or open operation. Allowable options are
“read”, “write”, or “readwrite”.
“read” → read data from a file.
“write” → write data to a file.
“readwrite” → simultaneously read data from
and write data to a file.
position Position or place to start. Allowable options are
“rewind” (beginning), “append” (end).
91
Chapter 12 ► File Operations
The write statement is the same as the simple write; however, the unit number must be the number
assigned during the open operation. Normally, the next write will be on the next line. The
advance="no" is optional. If it is included, the next write will be on the same line where the previous
line stopped.
For example to open a file named temp.txt and place the string “Fortran Example” and the numbers 42,
and 3.14159 on separate lines, the following declarations:
integer :: myanswer=42, myopenstatus, mywritestatus
real, parameter :: pi=3.14159
character(15) :: mymessage="Fortran Example"
character(8) :: myfilename="temp.txt"
92
Chapter 12 ◄ File Operations
The read is the same as the simple read; however, the unit number must be the number assigned during
the open operation. If the status variable is set to less than 0, that is an indication that the end of the file
has been reached. For example, if the file numbers.dat exists and has two numbers (on separate lines),
the following declarations,
integer :: num1, num2, myopenstatus, myreadstatus
character(11) :: myfilename="numbers.txt"
12.5 Rewind
An open file can be reset back to the beginning. This might be useful if the file needs to be read twice.
The rewind statement will reset the file read pointer and subsequent reads will start back at the
beginning. The general form of a rewind statement is:
rewind(<unit number>)
Where the unit number was assigned during the initial open. The file must be open when the rewind is
executed for the rewind to work correctly.
12.6 Backspace
When reading from a file, each successive read will return the next line from the file. The computer
keeps track of which lines have been read and will automatically return the next line. It is possible to
read a line and then backspace and re-read the line again with the backspace statement.
The general form of a backspace statement is:
backspace(<unit number>)
Where the unit number was assigned during the initial open. The file must be open when the backspace
is executed for the backspace to work. It should be noted that this operation is not used very often.
93
Chapter 12 ► File Operations
Where the unit number was assigned during the initial open.
For the previous examples,
close(10)
close(12)
12.8 Example
In this example, we will write a Fortran program to read an input file and write a line number and the
original line to an output file.
Once the file is open, a line will be read from the input file, and the line number and the line will be
written to the output file. For this example, we will assume that a line will have 132 or less characters.
94
Chapter 12 ◄ File Operations
This process will continue until there are no more lines in the input file.
! loop
! read line from input file
! if end of file, exit loop
! write line number and line to output file
! close files
program linenumbers
! declare variables
implicit none
integer :: i, rdopst, wropst, rdst
character(30) :: rdfile, wrfile
character(132) :: line
! ----------
! prompt for input file name
do
write (*,'(a)', advance="no") "Input File Name: "
! ----------
! prompt for output file name
do
write (*,'(a)', advance="no") "Output File Name: "
95
Chapter 12 ► File Operations
! ----------
i = 1
do
! read line from input file
read (12, '(a)', iostat=rdst) line
! close files
close(12)
close(14)
The spacing and indentation are not required, but help to make the program more readable.
12.9 Exercises
Below are some quiz questions and project suggestions based on this chapter.
96
Chapter 12 ◄ File Operations
2) What is the range of the valid unit numbers for a file open?
integer :: opnstat
character(20) :: filename="file.txt"
4) Assume the file answers.txt exists, has been successfully opened using unit number 20,
and contains the following data:
"line 1 data1=23 data2 =034 data3 =05123"
What is the read statement required to get data1, data2, and data3 into the integer variables
num1, num2, and num3 respectively?
97
Chapter 12 ► File Operations
( (
x=((radius 1+ radius2) ∗ cos( step)) + offsetposition ∗ cos ( radius1 + radius2) ∗
step
))
radius 2
The step should start at 0.0 and stop at 360.0, stepping by 0.1. All writes should use a formatted
output (not the '*'). Then the program should close the output file and inform the user the
plotting is completed. Test the program on a number of different input values.
3) Write a Fortran program that plays the Chaos Game. To play the Chaos Game, plot 3 points A,
B, C, and an arbitrary initial point X1. Then, generate a random number between 1 and 3
representing A (1), B (2), or C (3). If A comes up, plot the midpoint of the line joining X1 to A.
If B comes up, plot the midpoint of the line joining X1 to B; the case with C is similar. Call this
new point X2. Generate another random number between 1 and 3. Plot the midpoint of the line
joining X2 to either A, B or C depending on the random number. Call this new point X3.
Repeat this process N times. Test the program on a number of different input values.
Refer to Appendix C for more information regarding generating random numbers.
Note, the correct output of this program is shown on the cover page. The image is referred to as
a Serpinski Triangle10.
98
13 Single Dimension Arrays
An array is a collection or set of data. A variable can hold a single value. An array can hold multiple
values. The type (i.e., integer, real, etc.) of each item in the array must be the same. In order to access
specific elements, an index or subscript is used. The index specifies which element or value in the
array is being accessed.
An array is considered a direct access structure since any element can be accessed directly without
accessing any other elements.
The most basic form of an array is a single dimension array. A single dimension array can be thought
of as a single column in a spreadsheet. The column name, like A, is the array name and the row
number is like the index. For example, a spreadsheet column might appear as follows:
A single dimension array is logically the same and might look like:
Index Array Name
1 <value>
2 <value>
...
...
n-1 <value>
n <value>
The array name is chosen by the programmer and thus is not limited to A. The specific syntax requires
an index or subscript to specify which element of the array to access. By default, the first element is at
index=1, the next at index=2, and so forth. This can be changed if needed.
99
Chapter 13 ► Single Dimension Arrays
where type is the data type (integer, real, etc.) of the array. The dimension specifies the extent or size,
and name1, name2, …, nameN are names of one or more arrays being declared.
For example, to declare an array of 1000 integers,
integer, dimension(1000) :: nums1
will create an array, nums1, with space for 1000 integer values.
In this example, the extent is 1000 which means that the array indexes will range from 1 to 1000. The
extent can be changed by specifying the extent as:
smaller-integer : larger-integer
When only one number is specified, the smaller-integer is assumed to be 1. When both numbers are
specified, the array index's will range between the smaller-integer and the larger-integer. For example,
a declaration of:
integer, dimension(-5:5) :: ranges
will create an array, ranges, with indexes between -5 and 5 (inclusive). Using index values not within
the specified range will result in an error. If the compiler option, fcheck=bounds, to verify subscript
bounds is used, this error will be trapped at run-time. However, if the run-time bounds checking is not
turned on, the error may not be obvious and could result in unrelated problems such as other variables
being over-written or even security holes in some cases.
The numbers, enclosed between the “/”s are assigned in order. So, costs(1) is set to 10.0, costs(2) is set
to 15.0, costs(3) is set to 20.0, and costs(4) is set to 25.0.
100
Chapter 13 ◄ Single Dimension Arrays
Additionally, after declaration, it is possible to initialize all elements of an array to a single value with
an assignment statement. For example,
costs = 0.0
reserves the name nums2, but does not reserve any space for values.
The status variable must be an integer variable and will be used by the system to place a status code
indicating the status (success or failure) of the operation. If the status variable is set to 0, the allocation
was successful. If the status variable is set to >0, an error occurred and the allocation was not
successful.
For example, given the declarations,
integer, dimension(:), allocatable :: nums2
integer :: allst
the following allocate statement allocates space for 1000 numbers in array nums2,
allocate(nums2(1000), stat=allst)
The size, 1000 in this example, can be a variable, but it must be an integer. The status variable allst
will be set to 0 if the allocation is successful. However, if the status variable allst is set to a value >0,
an error occurred and the allocation was not successful.
101
Chapter 13 ► Single Dimension Arrays
would declare an array with ten elements. To place a value 121.3 in the first array element,
times(1) = 121.3
The index in these examples is a literal. However, the index can be an integer variable or integer
expression.
For example, given the following declarations,
real, dimension(10) :: temps
integer :: i=5, j
would declare an array with ten elements. To place a value 98.6 in the fifth array element,
temps(i) = 98.6
To access the fifth element, subtract 3.0 and place the result in the sixth element,
temps(i+1) = temps(i) – 3.0
To set all elements of the temps array to 0.0, a loop could be used as follows:
do i = 1, 10
temps(i) = 0.0
end do
102
Chapter 13 ◄ Single Dimension Arrays
To place a value 42.5 in the first array element and 73.5 in the last array element.
expArr(1) = 42.5
expArr(10) = 73.5
However, if an array element is accessed that is outside the declared bounds, it is an error. For
example,
expArr(11) = 99.5
would be an error. These kinds of errors would be difficult to find. However, if the bounds checking is
turned on (as noted in chapter 3), when the program is executed the error will be noted.
To compile with bounds checking turned on, the following compile command should be used:
C:\fortran> gfortran -fcheck=bounds -o hw hw.f95
This command will tell the 'gfortran' compiler to include bounds checking.
In general, using the bounds checking can slow a program down. However, this is not a significant
issue when learning to write programs.
Both forms of the loop will display the same results. If necessary, a step can be used. If the step is
omitted, as in the example, the step is defaulted to 1.
Function Description
MAXVAL(ARR1) Returns the maximum value in array ARR1. Type of value
returned is based on the type of the argument array ARR1.
MINVAL(ARR1) Returns the minimum value in array ARR1. Type of value
returned is based on the type of the argument array ARR1.
SUM(ARR1) Returns the sum of values in array ARR1. Type of value
returned is based on the type of the argument array ARR1.
103
Chapter 13 ► Single Dimension Arrays
will initialize each of the 5 elements in the array numbers to 1.0, 2.0, 3.0, 4.0, and 5.0 respectively.
The implied do-loop may also be used. For example, in the following declaration,
integer, dimension(5) :: numbers = (/ (i, i=1,5) /)
will initialize each of the 5 elements in the array numbers to 1, 2, 3, 4, and 5 respectively.
13.6 Example
In this example we will write a Fortran program to read a series of numbers from a file and compute
some statistical information including minimum, maximum, sum, average, and standard deviation11.
The standard deviation is calculated as follows:
√
n
104
Chapter 13 ◄ Single Dimension Arrays
Then, the program will loop to read the numbers from the file and store them in an array. The program
will check for any read errors (status variable > 0) and for the end of file (status variable < 0).
If a valid number is read, it will be counted and placed in the array.
! loop
! read from the file
! if error on read, terminate program
! if end of file, exit loop
! increment number counter
! place number in array
! end loop
Next, another loop will be used to find the minimum, maximum, and sum of the numbers. To find the
minimum and maximum values, we will assume that the first element in the array is the minimum and
maximum. Then, the program will check each number in the array. If the number from the array is less
than the current minimum value, the current minimum value will be updated to the new value. Same
for the maximum, if the number from the array is more than the current maximum value, the current
maximum value will be updated to the new value.
! initialize min, max, and sum
! loop
! check for new min
! check for new max
! update sum
! end loop
Once the sum is available, the average can be computed. Finally, a loop will be used to calculate the
105
Chapter 13 ► Single Dimension Arrays
Once the summation is completed, the standard deviation can be computed and the final results
displayed. As per the example specifications, the numbers should be displayed 10 per line.
One way to handle this is to display numbers on the same line (with the advance=“no” clause) and
every 10th line display a new line.
! calculate standard deviation
! loop to display numbers, 10 per line
! display results
! end program
program standardDeviation
! declare variables
implicit none
integer :: i, ncount=0, errs=0, opstat, rdstat
real :: num, min, max, sum, average, stdsum, std
real, dimension(5000) :: numbers
character(20) :: filename
! loop
do
106
Chapter 13 ◄ Single Dimension Arrays
! count error
errs = errs + 1
! if >3 errors, terminate program
if (errs > 3) then
write (*,'(a)') "Sorry you are having problems."
write (*,'(a)') "Program terminated."
stop
end if
! end loop
end do
! loop
do
! read file
read (42, *, iostat=rdstat) num
! if error on read, terminate program
if (rdstat>0) stop "Error on read."
! end loop
end do
! loop
do i = 1, ncount
107
Chapter 13 ► Single Dimension Arrays
! update sum
sum = sum + numbers(i)
! end loop
end do
! calculate average
average = sum / real(ncount)
! initialize stdsum
stdsum = 0.0
! loop
do i = 1, ncount
! end loop
end do
! display results
write (*,'(a)') "-------------------------------"
write (*,'(a)') "Results:"
do i = 1, ncount
write (*,'(f8.2,2x)', advance="no") numbers(i)
if (mod(i,10)==0) write (*,*)
end do
The spacing and indentation are not required, but help to make the program more readable.
108
Chapter 13 ◄ Single Dimension Arrays
Setting an element is the same. For example, to set the first element of the array to a simple message,
titles(1) = "Programming is fun!"
13.8 Exercises
Below are some quiz questions and project suggestions based on this chapter.
arr(1) = 10
arr(2) = 15
arr(3) = 20
arr(4) = 25
k = 3
109
Chapter 13 ► Single Dimension Arrays
nums = 0
do
if ( i == 5 ) exit
if ( mod(i,2) == 0) then
nums(i) = 99
else
nums(i) = i
end if
i = i + 1
end do
2) Write a Fortran program to cube a series of integer numbers from a file and cube each number.
The program should also calculate the real average of the original numbers and the real average
of the cubed numbers. Test the program on a series of different input values.
3) Write a Fortran program to generate a series of real values between 1.0 and 100.0 and store the
numbers in an array. Then, the program should compute the norm of a vector (single dimension
array). The formula for norm is as follows:
∣ norm ∣ = √a 2
1 + a 22 + a23 + ... + a2n
Refer to Appendix C for more information regarding generating random numbers. Test the
program on a series of different input values.
110
Chapter 13 ◄ Single Dimension Arrays
4) Write a Fortran program to read a series of numbers from a file, store the numbers in an array,
and then sort the numbers using the following selection sort algorithm:
You will need to convert the above pseudo-code algorithm into Fortran code. Test the program
on a series of different input values.
111
Chapter 13 ► Single Dimension Arrays
112
14 Multidimensional Arrays
A more advanced array is a multidimensional array. A multidimensional array can be thought of as
multiple columns in a spreadsheet. The column name, like A, B, C, etc., are the array columns and the
number is like the row.
For example, a two-dimensional array might look like:
index 1 2
Array Name 1 <value> <value>
2 <value> <value>
3 ... ...
... ...
<value> <value>
n <value> <value>
The specific syntax requires an index or subscript to specify which element of the array to access. The
indexing for a two dimension array is:
index 1 2
Array Name 1 arr(1,1) arr(1,2)
2 arr(2,1) arr(2,2)
3 arr(3,1) arr(3,2)
... ...
... ...
n arr(n,1) arr(n,2)
By default, the first element is at index=1, the next at index=2, and so forth. This default (where the
first number is at index 1) can be changed if needed.
113
Chapter 14 ► Multidimensional Arrays
where type is the data type (integer, real, etc.) of the array. The dimension specifies the size, and name1,
name2, ... , nameN are names of one or more arrays being declared.
For example, to declare a two-dimensional array 100 by 100,
integer, dimension(100,100) :: nums1
will create an array, nums1, with space for a total of 10,000 integer values.
In this example, the extent for each dimension is 100, which means that each of the two dimension's
indexes will range form 1 to 100. Each or both extents can be changed by specifying the extents as:
(smaller-integer:larger-integer, smaller-integer:larger-integer)
When only one number is specified, the smaller-integer is assumed to be 1. When both numbers are
specified, smaller and larger index, the dimension of the array will range between the smaller-integer
and the larger-integer. For example, a declaration of:
integer, dimension(0:9,0:9) :: ranges
will create an array, ranges, with both indexes between 0 and 9 (inclusive). Using index values not
within the specified range will result in an error.
reserves the name nums2, but does not reserve any space for values.
The status variable must be an integer variable and will be used by the system to place a status code
indicating the status (success or failure) of the operation. As before, if the status variable is set to 0, the
114
Chapter 14 ◄ Multidimensional Arrays
allocation was successful. If the status variable is set to >0, an error occurred and the allocation was
not successful.
For example, given the declarations,
integer, dimension(:,:), allocatable :: nums2
integer :: allstat
the following allocate statement allocates space for 10,000 numbers in array nums2,
allocate(nums2(100,100), stat=allstat)
The size, 100 by 100 in this example, can be a parameter or variable, but it must be an integer. The
variable allstat will be set to 0 if the allocation is successful and >0 if the allocation failed.
would declare an array, table1, with a total of 50 elements. To place a value 121.3 in the first row and first
column,
table1(1,1) = 121.3
The index in these examples is a literal. However, the index can be an integer variable or integer
expression. For example, given the following declarations,
real, dimension(10,10) :: tmptable
integer :: i=2, j=3
To access the same element, subtract 3.0 and place the result back into the same location,
tmptable(i,j+1) = tmptable(i,j+1) – 3.0
115
Chapter 14 ► Multidimensional Arrays
To set all elements of the tmptable array to 0.0, a nest loop could be used as follows:
do i = 1, 10
do j = 1, 10
tmptable(i,j) = 0.0
end do
end do
14.3 Example
In this example, we will write a Fortran program that will request a count, generate count (x,y) random
points, and perform a Monte Carlo π estimation based on those points. All x and y values are between
0 and 1. The main routine will get the count and then use a subroutine to generate the random (x,y)
points and a function, to perform the Monte Carlo π estimation. For this example, the count should be
between 100 and 1,000,000.
116
Chapter 14 ◄ Multidimensional Arrays
Finally, the figure we are discussing, a square centered on the origin with an inscribed circle is
symmetric with respect to the quadrants of its Cartesian plane. This works well with the default
random number generations of values between 0 and 1.
! declare variables
! display initial header
! prompt for and obtain count value
! loop
! prompt for count value
! read count value
! if count is correct, exit loop
! display error message
! end loop
! allocate two dimension array
! generate points
! loop count times
! generate x and y values
! place (x,y) values in array at appropriate index
! end loop
! set count of samples inside circle = 0
! loop count times
! if [ sqrt (x(i)**2 + y(i)**2) < 1.0 ]
! increment count of samples inside circle
! end loop
! display results
117
Chapter 14 ► Multidimensional Arrays
program piestimation
! declare variables
implicit none
integer :: count, alstat, i, incount
real :: x, y, pi_est, pt
real, allocatable, dimension(:,:) :: points
! generate_points
call random_seed()
118
Chapter 14 ◄ Multidimensional Arrays
end do
pt = pts(i,1)**2 + pts(i,2)**2
if (sqrt(pt) < 1.0) incount = incount + 1
end do
! display results
write (*,'(a, f8.2)') "Count of points: ", count
write (*,'(a, f8.2)') "Estimated PI value: ", pi_est
The spacing and indentation are not required, but help to make the program more readable.
14.4 Exercises
Below are some quiz questions and project suggestions based on this chapter.
a) (row, column)
119
Chapter 14 ► Multidimensional Arrays
b) (column, row)
c) (row, row)
d) (column, column)
e) user-selectable
do i = 1, 5
do j = 1, 3
mdarr(i,j) = real(i+j)
end do
end do
2) Update the π estimation program to ensure that a valid count value is obtained within three
tries. If there are more than three errors, the program should display an error message and
terminate.
3) Update the π estimation program to display the estimated π value 10 times. In order to perform
this, the count value can be divided by 10 and the current estimated π value displayed.
4) Write a program to statically declare a 100x100 two-dimensional array of real values. The
program should populate the array with random numbers between 0 (inclusive) and 1
(exclusive). Refer to Appendix C for information regarding generating random numbers. The
program should scan the array to find and display the maximum value and the location of that
value (i.e., the row and column where the value was found).
120
Chapter 14 ◄ Multidimensional Arrays
5) Update the find maximum program (from the previous question) to declare the array
dynamically and allow the user to enter the row and column dimensions and ensure that each is
between 10 and 1000. Once entered, the program should allocate the array and find and display
the maximum and minimum values and their locations (row and column).
6) Write a Fortran program to construct an odd-order Magic Square12. The algorithm for
constructing a NxN odd ordered Magic Square is as follows:
● First, place a 1 in the middle of the top row.
● After placing an integer, k, move up one row and one column to the right to place the
next integer, k+1, unless the following occurs:
○ If a move takes you above the top row in the jth column, move to the bottom of the jth
column and place the integer there.
○ If a move takes you outside to the right of the square in the ith row, place the integer
in the ith row at the left side.
○ If a move takes you to an already filled square or if you move out of the square at
the upper right hand corner, place k+1 immediately below k.
Test the program and compare the results to the Wikipedia example.
121
Chapter 14 ► Multidimensional Arrays
122
15 Subprograms
Until now, all of the programs have essentially been single, fairly small programs. However, as we
scale up into larger programs, this methodology will become more difficult. When developing larger
programs, it becomes necessary to break larger programs up into multiple, smaller more manageable
pieces. Then, during program development, it is possible to focus on each subsection or piece
individually and then combine the results into a final complete program. And, for very large projects,
multiple people may work on different parts of the program simultaneously.
Some of the key advantages of developing a program using functions and/or subroutines include:
● Structured development of programs
● Reuse of subprograms
● Isolation of subprograms
Fortran subprograms are the mechanism to break a large program into multiple smaller parts. This
allows for a more comprehensive program design.
program <name>
<declarations>
<program statements>
contains
123
Chapter 15 ► Subprograms
15.3 Arguments
When writing and using Fortran subprograms, it is typically necessary to provide data to a subprogram
and/or to obtain results back from the functions or subroutines. This information, in the form of
variables, is referred to as an argument or arguments. The argument or arguments in the calling routine
are referred to as actual arguments, and the argument or arguments in the function or subroutine are
referred to as formal arguments. The formal arguments take on the values that are passed from the
calling routine.
The only way to transfer values in to or out of a subroutine is through the arguments. A function
typically passes values in through the arguments with a single return value (via the function name). All
other variables are independent and isolated.
124
Chapter 15 ◄ Subprograms
done with the intrinsic functions. When a program uses a subroutine, it is called with a call statement.
When a program uses a function, it is used by name and returns a result which must be assigned
somewhere appropriate (e.g., like a variable).
Calling Routine
...
call example (x, y, z)
...
Subroutine
...
subroutine example (a, b, c)
...
15.6 Functions
A function is a special type of Fortran subprogram that is expected to return a single result or answer.
A function will typically accept some kind of input information and based on that information, return a
result. The two types of Fortran functions are described in the following sections.
125
Chapter 15 ► Subprograms
<body of function>
<name> = expression
return
end function <name>
The <type> is one of the Fortran data types: real, integer, logical, character, or complex. It is possible
to place the type declaration on a separate line from the function statement.
The information, in the form of arguments, is passed from the calling routine to the function. Each of
the passed arguments must be declared and the declaration must include the type and the intent. The
arguments in the calling routine and the function must match and are matched up by position.
An example function to convert a Fahrenheit temperature to Celsius temperature would be as follows:
real function fahr_to_celsius(ftemp)
real, intent(in) :: ftemp
return
end function fahr_to_celsius
Which, given a Fahrenheit temperature, will return the Celsius temperature. The single input argument,
ftemp, is declared to be a real value and “intent(in)”, which means that the value is expected to be
coming into the function and cannot be changed. The final value is returned to the calling routine by
assigning a value to the function name, fahr_to_celsius, in this example.
126
Chapter 15 ◄ Subprograms
15.7 Subroutines
A subroutine is a Fortran subprogram that can accept some kind of input information and based on that
information, return a result or series of results.
The general form of a subroutine is a follows:
subroutine <name> ( <arguments> )
<declarations>
<body of subroutine>
return
end subroutine <name>
The information, in the form of arguments, is passed from the calling routine to the subroutine. Each
of the passed arguments must be declared and the declaration must include the type and the intent. The
arguments in the calling routine and the subroutine must match and are matched up by position.
For example, given the following simple program to find the sum and average of three numbers.
program subExample
implicit none
real :: x1=4.0, y1=5.0, z1=6.0, sum1, ave1
real :: x2=4.0, y2=5.0, z2=6.0, sum2, ave2
sm = a + b + c
av = sm / 3.0
return
end subroutine sumAve
The arguments in the first call (x1, y1, z1, sum1, and ave1) are matched up to the arguments in the
subroutine (a, b, c, sm, and av) by position. That is, the x1 from the call is matched with the a in the
subroutine. The arguments in the second call (x2, y2, z2, sum2, and ave2) are again matched up to the
arguments in the subroutine (a, b, c, sm, and av) by position. While the names of the variables do not
127
Chapter 15 ► Subprograms
need to match, the data types must match. Variables declared in a function or subroutine are not the
same as variables in the calling routine. This is true, even if they are the same name!
15.8 Example
In this example, we will write a Fortran program to simulate the dice game of Twenty-Six13, which is a
single player betting game with 10 dice. The main program will determine how many games to play,
track the count of games won and lost, and display some win/loss statistics. A subroutine will be used
to play the Twenty-Six game. The subroutine will be called as many times as requested.
The subroutine, twenty_six(), will play the dice game Twenty-Six. To play the game, the player rolls
the dice (1 to 6) and this initial roll is used as the “point” number. Then the player throws the ten dice
13 times. The score is the number of times that the point number is thrown. A random number
between 1 and 6 will be used for each dice roll.
The routine will determine the payout based on the point count using the following table:
The subroutine should display the dice (all 10 dice for each of 13 rolls), point count, game result, and
payout. For example, if the point was 6, the subroutine might display the following:
Point: 6
Roll: 1 Dice: 4 6 5 3 3 1 1 3 3 2
Roll: 2 Dice: 1 6 3 3 4 1 4 4 2 6
Roll: 3 Dice: 3 2 6 4 5 3 2 1 5 4
Roll: 4 Dice: 5 6 4 1 4 6 6 2 4 4
Roll: 5 Dice: 4 6 6 4 5 3 6 1 5 5
Roll: 6 Dice: 3 1 4 5 6 5 3 3 3 4
Roll: 7 Dice: 6 6 5 6 1 5 5 6 5 5
Roll: 8 Dice: 4 1 3 4 1 4 4 6 2 5
Roll: 9 Dice: 4 4 2 1 1 4 3 1 5 4
Roll: 10 Dice: 5 6 1 2 4 1 1 2 1 1
Roll: 11 Dice: 2 3 2 4 1 3 3 6 5 1
Roll: 12 Dice: 1 1 6 5 4 5 1 6 6 5
Roll: 13 Dice: 6 4 4 5 3 3 5 3 3 5
Point Count: 22
128
Chapter 15 ◄ Subprograms
For this example, the main will track the games won and lost.
program diceGame
!-----------------------------------------------------------
! Fortran program to simulate a dice game of Twenty-Six
! The main program:
! displays appropriate headers
! obtains and checks number of games to play
! loops to play 'count' number of games times
implicit none
integer, parameter :: initial_bank=100
integer :: num_games, games_won=0, games_lost=0
integer :: i, payout, bank
integer, dimension(13,10) :: dice
real :: win_pct
bank = initial_bank
call random_seed()
do i = 1, num_games
bank = bank - 1
call twentySix (payout)
if (payout > 0) then
129
Chapter 15 ► Subprograms
games_won = games_won + 1
else
games_lost = games_lost + 1
end if
bank = bank + payout
end do
contains
! *********************************************************
! subroutine(s) goes here...
! *********************************************************
Refer to Appendix C for additional information regarding the random number generation and
initialization of the built-in random number generator.
130
Chapter 15 ◄ Subprograms
! *********************************************************
! Subroutine to simulate twenty-six game.
! Randomly select a number from 1 to 6 as the “point” number
! Throw ten dice 13 times
! results go into dice(13,10) array
! Score is the number of times that the point number is
thrown
! determine point
call random_number(x)
point = int(x*6.0) + 1
! roll dice
pnt_cnt = 0
do i = 1, 13
do j = 1, 10
call random_number(x)
dice(i,j) = int(x*6.0) + 1
if (dice(i,j) == point) pnt_cnt = pnt_cnt + 1
end do
end do
! determine payout
select case (pnt_cnt)
case (:10)
payout = 10
case (13,27)
payout = 5
case (26)
payout = 4
case (28)
payout = 6
case (29)
payout = 8
case (30)
payout = 10
case default
payout = 0
131
Chapter 15 ► Subprograms
end select
do i = 1, 13
write (*,'(8x, a, i2, 2x, a, 10(2x, i1),/)', &
advance="no") "Roll: ", i, "Dice: ", &
(dice(i,j), j=1,10)
end do
return
end subroutine twentySix
The spacing and indentation are not required, but help to make the program more readable.
15.9 Exercises
Below are some quiz questions and project suggestions based on this chapter.
3) In the function call, ans = power(x, y), what are x and y are called?
4) In the function heading, integer function power(a, b), what are a and b are called?
132
Chapter 15 ◄ Subprograms
5) In the function, integer function power(a, b), what is the type of the value returned?
7) The subprogram section (where functions and subprograms are defined) is marked by what
keyword?
power = a ** b
return
end function power
program quiz
implicit none
real :: temp=80.0, temp1=50.0, temp2
contains
133
Chapter 15 ► Subprograms
2) Write a main program and an integer Fortran function, gSeries(), to compute the following
geometric series:
n− 1
g = ∑ xn = 1+ x+ x 2 + x3 + ⋯ + x( n−1 )
n= 0
The arguments for the call, in order, are as follows: n (integer value). The function should
return an integer result (of the formula based on the n value). The main should call the function
with several different values.
3) Write a main program and a real function, harmonicMean(), to compute the harmonic mean of
a series of real numbers. The real numbers are pass to the function in an array along with the
count.
N
harmonic mean =
( 1 1
+ + ...+
x1 x 2
1
xN )
The arguments for the call, in order, are as follows; array of numbers (with count real values),
count (integer). The function should return a real result (of the formula). The main should call
the function with several different values.
4) Write a main program and a subroutine, CircleStats(), that, given an array containing a series of
circle diameter's (real values), will compute the area of each circle in a series of circles and
store them into a different array (real values). The subroutine should also compute the real
average of the circle areas. The arguments for the call, in order, are as follows; circle diameter's
array (count real values), circle areas array (count real values), count (integer), areas average
(real). The main program should declare the array and initialize the array with a series of values
for circle areas. The program results should be verified with a calculator.
134
Chapter 15 ◄ Subprograms
5) Write a main program and a subroutine, ReadCoord(), to read an (x, y, z) coordinate from the
user. The subroutine must prompt for and read (x, y, z) and ensure that the x, y, and z values are
between 0 and 100 (inclusive). The values may be prompted for and read together, but the
prompt should leave the cursor on the same line. The subroutine should re-prompt for all three
if the input data is not correct. If the user provides valid data, the (x, y, z) values should be
returned with a logical for valid data set to true. If the user does not provide valid data entry
after three tries, the subroutine should display an error message and a set the logical for valid
data to false. The arguments for the call, in order, are as follows; x value (integer), y value
(integer), z value (integer), and valid data flag (logical value). The main program should call
the subroutine three times and display the results for each call.
6) Write a main program and a subroutine, Stats(), that, given an array containing a series of
numbers (real values), will find and display the following real values; minimum, median,
maximum, sum, and average. The display must use a formatted write(). The real values will
not exceed 100.0 and should display three digits decimal values (i.e., nnn.xxx). The arguments
for the call, in order, are as follows; array of numbers (count real values), count (integer). The
main program should populate the array with random numbers and call the subroutine.
135
Chapter 15 ► Subprograms
136
16 Derived Data Types
A derived data type is a user-defined combination of the intrinsic data types. The derived data types
are a convenient way to combine or group variables about a particular item.
For example, a 'student' might include a name, identification number, final score, and grade. Each of
these pieces of information can be represented with individual variables (as outlined in previous
section) as follows:
character(50) :: name
integer :: id
real :: score
character(2) :: grade
However, for multiple students, multiple sets of variables would be required. This can become
cumbersome and confusing.
By using a derived data type, these separate pieces of information can be more easily grouped together.
The details on defining, declaring and using derived data types are provided in the following sections.
16.1 Definition
Before a derived data type can be used, it must be defined. The definition will establish which pieces
of information will be grouped together. Each piece of information included in the definition is
referred to as a component.
type type_name
<component definitions>
end type type_name
For example, to declare the student type described previously, the following declaration would be
appropriate:
type student
character(50) :: name
integer :: id
real :: score
character(2) :: grade
end type student
The indentation is not required, but does make the definition easier to read. The fields (name, id, score,
grade) are called components. These components together make up the information for a 'student'.
The type definition is required only once at the beginning of the program. Once defined, the type
definition cannot be changed. More specifically, additional components cannot be added unless the
definition is updated and the program is recompiled.
This definition will establish a template as follows:
137
Chapter 16 ► Derived Data Types
student name
id
score
grade
Once defined, the template can be used to declare variables. Each variable declared with this definition
will be created based on the definition which includes these four components.
16.2 Declaration
Once a derived data type is defined, variables using that definition can be declared. The general format
for a declaration is as follows:
type (<type_name>) :: <variable_name(s)>
For example, to declare two students, the following declaration could be used:
type (student) :: student1, student2
This declaration will declare two variables, student1 and student2, each with the set of components
defined in the type definition. The definition can be thought of as the cookie cutter and the declaration
is the cookie. Only after a variable has been declared, can values be set for that variable.
For example, to set all components for the student student1, the following
student1%name = "Joseph"
student1%id = 1234
student1%score = 99.99
student1%grade = "A"
Each component for student1 is set individually. Not every component must be set. Of course, as with
other variables, any component that has not been set cannot be used.
138
Chapter 16 ◄ Derived Data Types
This previous declaration and these assignments will establish a variable as follows:
It is possible to assign all components to another variable of the same derived data type. For example,
to set student2 to be the same as student1, an assignment is used as follows:
student2 = student1
This will copy all components from the variable student1 into the variable student2 (since both
student1 and student2 are of the same derived data type).
139
Chapter 16 ► Derived Data Types
program timeSummation
type time
140
Chapter 16 ◄ Derived Data Types
! declare variables
! includes → time1, time2, and timesum
type(time) :: time1, time2, timesum
! display results
write (*,'(/,a,i2.2,a1,i2.2,a1,i2.2)') "Time One: ", &
time1%hours, ":", time1%minutes, ":", time1%seconds
write (*,'(a,i2.2,a1,i2.2,a1,i2.2)') "Time Two: ", &
time2%hours, ":", time2%minutes, ":", time2%seconds
write (*,'(a,i2.2,a1,i2.2,a1,i2.2,/)') "Time Sum: ", &
timesum%hours, ":", timesum%minutes, ":", &
timesum%seconds
contains
! *******************************************************
! Subroutine to prompt for, read, and check
! a time (hours:minutes:seconds) in 24-hour format.
do
! prompt for time
write (*,'(a)',advance="no") &
"Enter time (hh mm ss): "
141
Chapter 16 ► Derived Data Types
end do
return
end subroutine readtime
! *******************************************************
! Subroutine to add two times.
! Ensures seconds and minutes are within range (0-59)
! Hours may exceed 23
return
end subroutine addtimes
If the program does not work at first, the comments can aid in determining the problem.
142
Chapter 16 ◄ Derived Data Types
ensure they are correct. Once the times are correct, the add times subroutine can be checked. Each of
the time sums can be displayed to help determine where the error might be.
Each element of the array class will be of the type student and include each of the defined components
(name, id, score, grade in this example). For an array of type(student), the layout would be as follows:
class(1) name
id
score
grade
class(2) name
id
score
grade
class(3) name
id
score
grade
... ...
To access elements in the array, an index must be used. After the index, the desired component would
be specified. For example, to set values for the third student, the following statements could be used.
class(3)%name = "Fred"
class(3)%id = 4321
class(3)%score = 75.75
class(3)%grade = "C"
143
Chapter 16 ► Derived Data Types
integer :: id
real :: score
character(1) :: grade
end type student
temp = class(5)
class(5) = class(11)
class(11) = temp
This code fragment will copy all components from the fifth array element (of type student) into a
temporary variable (also of type student). Then, the eleventh array element can be copied into the fifth
array element (thus overwriting all previous values). And, finally, the eleventh array element can be set
to the original values from the fifth array element, which are held in the temporary variable.
A B C D F
A>=90 80 - 89 70 - 79 60 - 69 <=59
When determining the final grade, the program should round up when appropriate. The main will call
a function to calculate and return the average of the scores. Additionally, the main will display the final
average.
144
Chapter 16 ◄ Derived Data Types
The basic steps for the read student information subroutine include:
! subroutine header and appropriate declarations
! loop
! prompt for student name
! read name
! if name is empty, exit loop
! loop
! prompt for student score
! read score
! check score entered
! if [score is between 0.0 and 100.0, inclusive] exit
! display error message
! end loop
! update count of students
! place values in student array
! end loop
When determining the final grade, the nearest integer intrinsic function, nint(), can be used to perform
the appropriate rounding.
The basic steps for the calculate average score function include:
! function header and appropriate declarations
! loop
! sum scores
! end loop
! calculate and return average
For convenience, the steps are written as program comments.
145
Chapter 16 ► Derived Data Types
program classScores
! define data type for student, includes → name, id, grade
implicit none
type student
character(60) :: name
real :: score
character(1) :: grade
end type
! display average
write (*,'(/,a, f5.1)') "Final Class Average: ", average
contains
! *******************************************************
! Subroutine to read student information (name and score).
! A blank name will stop input
! The score must be between 0.0 and 100.0 (inclusive)
do
! prompt for student name and read name
write (*,'(a)',advance="no") "Enter Student Name: "
read (*,'(a60)') tempname
146
Chapter 16 ◄ Derived Data Types
do
! prompt for student score and read score
write (*,'(a)',advance="no") &
"Enter Student Score: "
read (*,*) tempscore
end do
end do
return
end subroutine readStudents
! *******************************************************
! Subroutine to set student grades.
! ≥ 90 → A; 80 - 89 → B; 70 – 79 → C; 60 - 69 → D; ≤ 59 → F
147
Chapter 16 ► Derived Data Types
return
end subroutine setStudentGrades
! *******************************************************
! Function to calculate average score.
! sum scores
do i = 1, count
sum = sum + class(i)%score
end do
return
end function classAverage
If the program does not work at first, the comments can aid in determining the problem.
16.7 Exercises
Below are some quiz questions and project suggestions based on this chapter.
148
Chapter 16 ◄ Derived Data Types
3) Define a derived data type, circle, to store information about a circle. Must include a circle
name (max 20 characters), size (radius – a real value) and the position in 3-dimensional space
(x, y, and z → all integer values).
4) Write the declaration necessary to declare two variables named ring1 and ring2 of type circle
(from previous question).
5) Define a user-defined type, planet, to store information for a planet. Include a name (15
characters), radius (real value), area (real value), and volume (real value). Additionally, write
the declaration necessary to declare two variables named earth and mars of type planet.
6) Define a user-defined type named date for processing dates consisting of a month name (10
characters), month (integer), date of month (integer), and year (integer).
2) Write a Fortran program to read and display information about a set of planetary bodies. The
program should read the information from a file, allow the user to select a display option, and
call the appropriate routine to display that information.
The main program should call a series of subroutines as follows:
● Subroutine readPlanets() to prompt for a file name of the planets file, open the file
(including error checking), and read the file into an array. Three errors are allowed, but
if a fourth error is made, the routine should terminate the program.
● Subroutine calcPlanetArea() to calculate the planet area based on the diameters.
● Function getUserOption() to display a list of options, read the selection option.
● Subroutine displayPlanetMinMax() to display the minimum and maximum based on an
option as follows:
▪ Option (1) → Smallest and Largest Planets (based on area)
▪ Option (2) → Coldest and Hottest Planets (based on average temperature)
▪ Option (3) → Planets with Shortest and Longest Days (based on day length)
● Subroutine printPlanetsSummary() to display the planet name, distance from sun, and
planet size.
149
Chapter 16 ► Derived Data Types
The output should be formatted as appropriate. Test on several sets of input values and verify
that the output is correct for the given input values.
3) Modify the planet program (from previous question) to sort the planets based on the radius. Test
on several sets of input values and verify that the output is correct for the given input values.
4) Type in the time class scores program, compile and execute the program. Test on several sets of
input values.
5) Modify the class scores program to assign grades based on the following scale:
F D C- C C+ B- B B+ A- A A+
0-59 60-70 70-72 73-76 77-79 80-82 83-86 87-89 90-92 93-96 97-100
Test on several sets of input values and verify that the output is correct for the given input.
6) Modify the class scores program to read the name and score file. The program should include
prompting for a file, opening the file, and reading the file contents into the class array. In order
to complete this exercise, create a file containing some random names and scores. Test on
several sets of input values.
150
17 Modules
For larger programs, using a single source file for the entire program becomes more difficult.
Fortunately, large programs can be split into multiple source files, each file can contain a subset of
subroutines and/or functions. There must be a main or primary source file that includes the main
program. The secondary file or files is referred to as a module or modules. Additionally, the modules
can then be more easily used in other, different programs ensuring that the code can be easily re-used.
This saves time and money by not re-writing routines. This section provides a description of the
formatting requirements and an example of how to set-up the modules.
For example, to declare a module named stats that includes a function to find the average of the
numbers in an array, the following module declaration might be used.
module stats
! note, no global variables used in this module
contains
! *************************************************************
! Simple function to find average of len values in an array.
do i = 1, len
sum = sum + array(i)
end do
average = sum / real(len)
end function average
This example assumes the real array contains len number of values up to a maximum of 1000 values.
151
Chapter 17 ► Modules
program average
use stats
implicit none
real, dimension(1000) :: arr
integer :: i, count
real :: ave
! -----
! Initialize array with some values.
count = 0
do i = 1, 20
arr(i) = real(i) + 10.0
count = count + 1
end do
! -----
! Call function to find average and display result.
The use statement is included before the variable declarations. Any number of use statements for
defined modules may be included.
which will read the source file (stats.f95) and create two new files: an object file stats.o and a
module file stats.mod. The name of the object file is based on the name of the source file. The
152
Chapter 17 ◄ Modules
name of the module file is based on the module name. While they are the same name in this example,
that is not a requirement.
The compile command is required for each module.
Once all the modules are compiled and the .o and .mod files are available, the main file can be
compiled. This step reads the .o and .mod files for each module and builds the final executable file.
For example, the command to compile the main file for the previous array average example is:
gfortran -o main main.f95 stats.o
For multiple modules, each of the .o files would be listed. In this example, the stats.mod file is read
by the gfortran compiler. While not explicitly listed, the .mod files are required and used at this
step.
4.0 ∗ π
volume = ∗ radius 3
3.0
The module will contain the functions and subroutine. The first function will compute the sphere
volume. The single step is:
153
Chapter 17 ► Modules
The second function will compute the sphere surface area. The single step is:
program sphere
use sphereRoutines
implicit none
real :: radius, spVolume, spSurfaceArea
! -----
! Display header and read radius
! -----
! Call functions for sphere volume and surface area
spVolume = sphereVolume(radius)
spSurfaceArea = sphereSurfaceArea(radius)
! -----
! Call routine to display formatted results.
The name of the module, sphereRoutines in this example, must be the name of the secondary
source file.
154
Chapter 17 ◄ Modules
module sphereRoutines
implicit none ! needed in every module
! ********************************************************
! Subroutines and functions are included after
! the 'contains'.
contains
! ********************************************************
! Compute the volume of a sphere with given radius.
! sphere volume = [ (4.0 * pi) / 3.0 ] * radius^3
return
end function sphereVolume
! ********************************************************
! Compute the volume of a sphere with given radius.
! sphere volume = 4.0 * pi * radius^2
return
end function sphereSurfaceArea
! ********************************************************
! Simple routine to display results.
155
Chapter 17 ► Modules
return
end subroutine displayResults
! ********************************************************
In a more complex program, multiple module files might be used. The grouping should be based on
the logical relationship of the routines. A more complicated program would require a more
comprehensive design effort.
gfortran -c sphereroutines.f95
gfortran -o modmain modmain.f95 sphereroutine.o
The first will create files sphereroutines.o and sphereroutines.mod. The second will read the
files modmain.f95 and sphereroutines.o then create the executable modmain.exe file.
17.5 Exercises
Below are some quiz questions and project suggestions based on this chapter.
156
Chapter 17 ◄ Modules
3) In the secondary source file, what statements is used to define and name the module?
4) How many main programs are allowed?
5) How many modules are allowed?
6) Is the contains key word needed in a module file (yes or no)?
2) Type in the sphere volume and surface area main program and the sphere volume and surface
area module, compile and execute the program. Test on several sets of input including the
example in the explanation.
3) Update the planets program from the previous chapter, problem #2, and break the program into
a main file and a module file for the functions and subroutines.
157
Chapter 17 ► Modules
158
18 Recursion
The Google search result for recursion, shows Recursion, did you mean recursion?
Recursion is a powerful general-purpose programming technique and is used for some important
applications including search and sorting methods. Recursion is the idea that a function may call itself
(which is the basis for the joke).
Recursion can be very confusing in its simplicity and power. The examples in this section will not be
enough in themselves for the reader to obtain recursive enlightenment. The goal of this section is to
provide an introduction to the concept on recursion. The simple examples here, which are used
introduce recursion, are meant to help demonstrate the form and structure for recursion. More complex
examples (than will be discussed here) should be studied and implemented in order to ensure a
complete appreciation for the power of recursion.
The calling process previously described supports recursion without any changes.
A recursive routine must have a recursive definition that includes:
1. base case, or cases, that provide a simple result (that defines when the recursion should stop).
2. rule, or set of rules, that reduce toward the base case.
This recursive definition is referred to as a recursive relation.
<body of subroutine>
return
end subroutine <name>
Based on this declaration the subroutine can call itself. The routine must ensure that it eventually stops
calling itself. Arguments are passed in the standard way.
The calling routine does not need any special declarations in order to call a recursive routine.
159
Chapter 18 ► Recursion
13
= 6 remainder 1
2
6
= 3 remainder 0
2
3
= 1 remainder 1
2
1
= 0 remainder 1
2
The remainders, always 0 or 1, represent the binary value. However, the resulting remainders are
generated in backwards order. As such, the resulting remainders 1, 0, 1, and 1 in this example must be
reversed for a final value of 11012 (as noted in chapter 2).
This process can be converted into a recursive relation as follows:
{
if n≤1 n
printBinary (n) = if n> 1 printBinary ( n/ 2)
output mod( num , 2)
160
Chapter 18 ◄ Recursion
This definition assumes that the value of n is positive. The recursive relation can be used by directly
converting the algorithm into code.
do
write (*,'(a)', advance="no") &
"Enter Decimal Number (0 - 1,000,000): "
read (*,*) decimalNumber
if (decimalNumber >= 0 .and. &
decimalNumber <= 1000000) exit
call printBinary(decimalNumber)
write (*,'(/)')
contains
! ************************************************************
! Print binary subroutine.
return
end subroutine printBinary
! ************************************************************
end program binary
161
Chapter 18 ► Recursion
The spacing and indentation are not required, but help to make the program more readable. The main
program ensures that the recursive routine is not called in invalid values (i.e., values £ 0).
<body of function>
<variable> = expression
return
end function <name>
162
Chapter 18 ◄ Recursion
The main program will handle the prompting and reading of the n value. This will include error
checking and re-prompting as needed. The recursive function will compute and return the factorial
value. Since the error checking is performed, the recursive function will assume valid input.
For more complex examples, the function itself may need to perform the error checking. As such, a
simple helper function could be used to verify the input value or values before calling the recursive
function.
factorial( n) =
{ 1
n × factorial( n−1)
if n=0
if n≥ 1
This definition assumes that the value of n is positive.
It must be noted that this function could easily be computed with a loop. However, the reason this is
done recursively is to provide a simple example of how a recursive function is developed using a
familiar mathematical function.
program recursionExample
implicit none
integer :: num, numFact
write (*,'(a/)') "Recursion Example"
do
write (*,'(a)', advance="no") "Enter N (1-15): "
read (*,*) num
if (num >= 1 .and. num <= 15) exit
write (*,'(a)') "Error, N out of range."
write (*,'(a)') "Please re-enter."
end do
numFact = fact(num)
163
Chapter 18 ► Recursion
contains
! *************************************************************
! Factorial function
if (n == 1) then
ans = 1
else
ans = n * fact(n-1)
end if
return
end function fact
! *************************************************************
The spacing and indentation are not required, but help to make the program more readable. The main
program ensures that the recursive routine is not called in invalid values (i.e., values £ 0).
164
Chapter 18 ◄ Recursion
main:
f = fact(5)
Step 10
fact:
Step 1 5 * fact(4)
Step 9
fact:
Step 2 4 * fact(3)
Step 8
fact:
Step 3 3 * fact(2)
Step 7
fact:
Step 4 2 * fact(1)
Step 6
fact:
Step 5 return 1
When the initial call to factorial function occurs from main, the main will start into the fact() function
(shown as step 1). Since the argument of 5 is not a base case, the fact() function must call fact() again
with the argument of n-1 or 4 in this example (step 2). And, again, since 4 is not the base case, the
fact() function must call fact() again with the argument of n-1 or 3 in this example (step 3).
This process continues until the argument passed into the fact() function meets the base case which is
when the arguments is equal to 1 (shown as step 5). When this occurs, only then is a return value
provided to the previous call (step 6). This return argument is then used to calculate the previous
multiplication which is 2 times 1 which will return a value to the previous call (as shown in step 7).
This process will continue (steps 8, 9, and 10) until the main has a final answer.
Since the code being executed is the same, each instance of the fact() function is different from any
other instance only in the arguments and any local values (none in this example).
165
Chapter 18 ► Recursion
It should also be noted that the height of the recursion tree is directly associated with the amount of
memory used by the recursive function. For problems where the recursion tree is very large, this can
have a negative impact on overall performance of a recursive routine.
18.6 Exercises
Below are some quiz questions and project suggestions based on this chapter.
2) Type in the factorial main program and recursive function. Test on several data sets and verify
that the program produces the correct results.
{
1 if n=0
fib( n) = 1 if n=1
fib( n−1)+ fib(n−2) if n≥ 2
Create a main program to read the n value from the user and ensure it is between 1 and 40.
Develop recursive function, fib, to recursively compute the Fibonnaci number based on the
provided definition. Note, the recursive Fibonnaci function requires two recursive calls for the
non-base case step.
166
Chapter 18 ◄ Recursion
4) Develop a recursive subroutine to recursively print a star tree. Based on an initial value, n, the
star tree should be displayed. For example, for an n value of 5, the program should output
something similar to the following:
Star Tree:
* * * * *
* * * *
* * *
* *
*
Create a main program to read the n value from the user and ensure it is between 1 and 50.
Develop recursive subroutine, printStars(), to recursively print the start tree as shown. The
subroutine should print one line per call. For successive recursive calls, the n value passed as
an argument should be decremented. The based case would be one (1) star.
5) Write a program using a recursive function to determine the number of possible paths through a
two-dimensional grid. The only allowed moves are one step to the right or one step down. For
example, given a grid as follows:
0 1 2
0 start
1
2
3 end
Moving from the starting location, (0,0) in this example, going to the end location, (3,2) in this
example, can be performed in 10 different ways. Two, of the ten, different ways are shown in
the example above. The function must be recursive.
Create a main program to read the initial grid coordinates and ensure that they are valid
(positive values) and that the end coordinates are greater than the start coordinates. Create a
recursive function, countPaths(), to determine the number of possible paths through a two-
dimensional grid. The function will accept a start coordinate (row,col) and a final end
coordinate (row,col).
167
Chapter 18 ► Recursion
6) The Tower of Hanoi is a mathematical puzzle that consists of three pegs, and a number of disks
of different sizes which can slide onto any peg. The puzzle starts with the disks neatly stacked
in order of size on one peg, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack
to another peg, obeying the following rules:
◦ Only one disk may be moved at a time.
◦ Each move consists of taking the upper disk from
one of the pegs and sliding it onto another peg, on
top of the other disks that may already be present
on that peg.
◦ No disk may be placed on top of a smaller disk.
The following is a recursive definition for the problem:
{
write( move the disc from from to to) if n=1
Create a main program to read and validate the number of disks, n, from the user and ensure it
is between 1 and 10. Develop recursive function, hanoi, to recursively compute a solution to
the Tower of Hanoi problem.
168
19 Character String / Numeric Conversions
Characters string values, such as “123” cannot be used to perform numeric operations such as addition
or multiplication. As such, for more complex programs, there is sometimes the need to convert
between a character string representing a numeric value and an actual real or integer number.
These conversions can be performed using what is referred to as an internal read or an internal write.
Basically, the read or write functions and associated format statements can be used to perform basic
conversions. Instead of reading from an open file, the read and write operations can read and write
directly from and to variables. The specified format provides guidance for the conversion result.
Based on the input, a conversion may not be possible. For example, the character string “3.14” can be
converted into the real value of 3.14. However, the character string “3.1z4” could not be converted
since the 'z' is not a legal numeric value.
If a conversion is not possible, an error would be generated. If not handled, such an error would crash
the program. In order to address and handle any potential errors, the iostat parameter for the read/write
operation is used as previously described in the file operations chapter.
program cvtExample 1
implicit none
integer :: cvtErr
character(4) :: iString = "1234"
character(7) :: rString = "3.14159"
character(7) :: badString = "3.14z59"
integer :: iNum1, iNum2
real :: pi, tau
! ----------
169
Chapter 19 ► Character String / Numeric Conversions
if (cvtErr == 0 ) then
iNum2 = iNum1 * 2
write (*,'(a, i5, /, a, i5, /)') &
"num1 = ", iNum1, "num2 = ", iNum2
else
write (*,'(a, /)') "Error, invalid integer string."
end if
! ----------
! Convert string to a real value.
if (cvtErr == 0 ) then
tau = pi * 2.0
write (*,'(a, f5.3, /, a, f5.3, /)') &
"pi = ", pi, "tau = ", tau
else
write (*,'(a, /)') "Error, invalid real string."
end if
! ----------
! Convert string to a real value.
if (cvtErr == 0 ) then
tau = pi * 2.0
write (*,'(a, f5.3, /, a, f6.3)') &
"pi = ", pi, "tau = ", tau
else
write (*,'(a, /)') "Error, invalid real string."
end if
The specific formats used on the read operations in the example are wider or larger than the expected
number (which is allowed). Should a smaller format be used, it would either truncate the value or
possibly generate a conversion error. To ensure appropriate conversion, the final values should be
verified against the expected result.
An example of the output for this program is as follows:
Example Conversion Program.
num1 = 1234
num2 = 2468
170
Chapter 19 ◄ Character String / Numeric Conversions
pi = 3.142
tau = 6.283
The multiplication by 2 for each of the numeric values was performed only as an example since
multiplication can only be performed on numeric data types (i.e., integer, real, or complex).
program cvtExample2
implicit none
integer :: cvtErr
character(50) :: str1, str2, msg1, msg2
integer :: iNum=2468
real :: pi = 3.14, tau
! ----------
! Convert integer value to a string.
if (cvtErr == 0 ) then
msg1 = "My age is " // str1
write (*,'(a, a)') &
"Message 1 = ", msg1
else
! ----------
! Convert real value to a string.
tau = pi * 2.0
171
Chapter 19 ► Character String / Numeric Conversions
if (cvtErr == 0 ) then
msg2 = "The value of TAU is " // str2
write (*,'(a, a, /)') &
"Message 2 = ", msg2
else
write (*,'(a, /)') "Error, invalid conversion."
end if
Once the numeric values are converted into strings, the character functions and character operations
can be used as needed.
19.3 Exercises
Below are some quiz questions and project suggestions based on this chapter.
172
Chapter 19 ◄ Character String / Numeric Conversions
2) Update the program from the previous question to read a series of character strings from the
user, attempt conversion for each character string to a real value. If invalid, the user should be
re-prompted. If valid, the sum of the values should be maintained. When the user enters a 0 ,
the program should stop reading numbers, display the final sum, and terminate.
3) Type in the numeric values to character string values conversion example program. Update the
values of the real and integer values with different numbers and verify that the program
produces the correct results.
4) Develop a program to read a series of integer values, sum the values, and convert the final sum
into a character string. The string should be concatenated with the string “The sum is ” and
displayed to the terminal using a single character string variable.
5) Write a program to prompt the user for an integer number between 100 and 999, re-prompting
until a valid number is provided. When a valid number is provided, create a file name in the
form of “file<number>.txt”, open/create the file, and write all numbers from 1 to the number,
one per line, and close the file. For example, if 42 is entered, the file file42.txt should be
created and contain the numbers 1, 2, 3, …, 42 (one per line).
173
Chapter 19 ► Character String / Numeric Conversions
174
20 System Services
The term system services generally refers to asking the operating system for information.
The read, write, and file operations (open, read, write, close) are common system services and have
already been addressed in a previous chapter.
Other system services include obtaining the date and/or time from the operating system and obtaining
the command line arguments (if any). The term command line arguments is used to refer to
information entered on the command line after the program name. This allows the user to provide
some information to the program before it starts (or as the program is started), which might save time
as compared to prompting for and interactively reading the information at run-time.
While there are many system services, only these basic ones are presented for reference. These system
services may be useful when working on more complex problems. Additionally, the calls and usage for
other system services is very similar to how these are performed.
As noted, each option must provide a location of where to place the results of the specified size and
date type. The options are comma separated, similar to the read and write calls noted in a previous
chapter. At least one argument must be included in the call.
The zone, or time zone, option will provide the time difference between local time and Coordinated
Universal Time (UTC16). The character string will provide a result in hours:minutes format and the integer
values will be in minutes only. However, the minutes can be easily converted to hours.
175
Chapter 20 ► System Services
The options and associated values returned as more fully described in the following table.
Option Data Type Description
Each argument is optional, but at least one argument must be included. Multiple arguments are
allowed.
! Example program to obtain the date and time from the system.
program timeDateExample
! ----------
! Declarations.
implicit none
176
Chapter 20 ◄ System Services
! ----------
! Display simple header.
! ----------
! Get date, time, and zone from system as characters.
! Display to screen for reference.
call date_and_time(date=today)
write (*,'(/a, a)') "Today is: ", today
! ----------
! Get all date values from the system as integers.
! Display to screen for reference.
call date_and_time(values=valuesArr)
While this program does not really use the time or date values for anything meaningful, it does provide
177
Chapter 20 ► System Services
an example of how the information is obtained for use in other, more complex programs. The output of
this example program is shown as follows:
Values Array:
Date, Year: 2013
Date, Month: 12
Date, Day: 12
Time, Hour: 15
Time, Minutes: 40
Time, Seconds: 32
Time, Millseconds: 491
The UTC for Las Vegas, Nevada is indeed, -8 hours as shown. The results for the UTC will be based
on the actual geographic location of where the system executing the program is located.
For the gfortran compiler, there is no required order for the command line arguments. However, a
valid output file name must follow the '-o' argument.
178
Chapter 20 ◄ System Services
The error handling for command line arguments is typically handled differently. Many programs check
the command line arguments, and if incorrect for any reason, display an error message and terminate
the program. This is what the gfortran compiler does when invalid or incorrect arguments are
provided.
It would be possible to create a program that could verify arguments, and if incorrect, display an error
message and then request correct input from the user. The handling of the command line arguments
processing is entirely the responsibility of the program and not the operating system.
Which will return the count in the variable myCount (as shown above). The count will be zero if no
arguments are entered.
179
Chapter 20 ► System Services
The first two arguments are required and the final two arguments are optional.
program argsExample
implicit none
integer :: argCount, allocStatus, rdErr, i, iNum
real :: rNum
character(len=80), dimension(:), allocatable :: args
! ----------
! Get command line argument count from system.
argCount = command_argument_count()
if (argCount == 0) then
write (*,'(a)') "No command line arguments provided."
stop
end if
! ----------
! Allocate an array to hold the arguments.
allocate(args(argCount), stat=allocStatus)
180
Chapter 20 ◄ System Services
! ----------
! Get each argument, one at a time, from system.
do i = 1, argCount
call get_command_argument(number=i,value=args(i))
end do
! ----------
! Display arguments to screen.
if (argCount == 0) then
write (*,'(a)') "No command line arguments provided."
else
if (argCount == 1) then
write (*,'(a, i1, a)') "There was ", &
argCount, " command line argument."
else
write (*,'(a, i2, a)') "There were ", &
argCount, " command line arguments."
end if
write (*,*)
end if
! ----------
! Convert a string to a numeric value using an internal read.
181
Chapter 20 ► System Services
write (*,*)
An example of the output for this program with valid command line arguments provided is shown
below. The executable name of the example program is 'args'.
c:\fortran>
Another example of the output for this program with invalid command line arguments provided is
shown as follows:
c:\fortran>
Note, the order for the valid and invalid arguments was chosen arbitrarily.
20.3 Exercises
Below are some quiz questions and project suggestions based on this chapter.
182
Chapter 20 ◄ System Services
2) Type in the get command line arguments example program. Execute the program using a
variety of different expected and unexpected arguments.
3) Develop a program that reads command line arguments for a title and time (hours and minutes).
Calculate and display the difference between the current time and the time from the command
line. If the command line arguments are incomplete or incorrect, an error message should be
displayed and the program, terminated. The program should use 24-hour format. One possible
approach to determining the time difference would be to convert each time into minutes (from
hours and minutes), compute the difference, and convert the difference in minutes back to hours
183
Chapter 20 ► System Services
and minutes. The final output should display the title, the system time, the entered time, and the
time difference. All times should be displayed in hours:minutes format.
4) Write a program to get the date from the system and display a formatted date. The formatted
date should be: <day of week>, <month name> <day>, <year>. For example, 12/2/2013 should
be displayed as Monday, December 2, 2013. Each string should include only the appropriate
spacing. Specifically, there should be no extra spaces between the words or numbers (including
the date value, 2 in the example).
To calculate the day on which a particular date falls, the following algorithm may be used.
Note, all variables are integers and the divisions are integer divisions.
14 − month
a =
12
y = year − a
m = month + 12 × a − 2
dayNum =
[ day + y +
y
4
−
y
+
y
100 400 (
+ 31 ×
m
12 ) ] mod 7
Where the month, day, and year variables are the integer date values (12, 2, and 2013 in the
previous example). The final value of dayNum is 0 for a Sunday, 1 for a Monday, 2 for a
Tuesday, and so forth with the maximum value of 6 for Saturday.
5) Update the program from the previous question to write the formatted date to a file. The file
name should be created based on the current date in the following format
“file<MMDDYY>.txt” For example, for a date of 12/02/2013, the file should be named
file120213.txt and contain the character string Monday, December 2, 2013.
6) Write a program to obtain the current date and attempt to open a file based on the date in the
following format, “file<MMDDYY>.txt”. For example, for a date of 12/02/2013, the file
should be named file120213.txt. If the file exists, the contents should be displayed to the
screen. If the file does not exist, an appropriate error message should be displayed.
184
21 Appendix A – ASCII Table
This table lists the American Standard Code for Information Interchange (ASCII) characters or symbols
and their decimal numbers.
185
Chapter 21 ► Appendix A – ASCII Table
186
22 Appendix B – Start-Up Instructions
The following provides some specific instructions for getting started. These instructions are
specifically geared for using a MacOS or Windows based PCs. This includes all versions of Windows
from Windows XP, Windows Vista, Windows 7, Windows 8, and Windows 10.
The basic process is very similar to Linux (which is not covered here).
This page provides general information regarding the Fortran compiler development effort, project
objectives, and current status.
More specific information, and the Windows compiler binaries, can be found on the gFortran Wiki
page, which is located at:
http://gcc.gnu.org/wiki/GFortran
This page contains links to the Gfortran binaries. On this page, click on the link labeled:
Binaries for Windows, Linux, and MacOS
Which will display the page for the GNUBinaries for various platforms, including Windows, MacOS,
and Linux. Click on the appropriate link Windows, MacOS, GNU/Linux.
187
Chapter 22 ► Appendix B – Start-Up Instructions
After downloading, install the compiler. The installation can be accomplished by double-clicking on
the downloaded file. As with all Windows installs, it will require System Administrator privileges.
Once the installation has been completed, the downloaded installation file can be deleted.
Once the Command Prompt is open, the device and directory for the working files can be set.
188
Chapter 22 ◄ Appendix B – Start-Up Instructions
At this point, typing dir (for directory) will provide a list of files in the directory. While the format
will appear different, the files are the same as shown in the My Computer listing.
The “no input files” message means that the installation was completed successfully. It is not
necessary to set the device or directory in order to perform this verification.
However, if the following message is displayed,
C:\cs117> gfortran
'gfortran' is not recognized as an internal or external command,
operable program or batch file.
it means that the Fortran compiler is not installed. The installation issue must be addressed before
continuing. Once the installation is completed successfully, the compilation steps detailed in Chapter 3
can be completed.
22.3.4 Compilation
Once the Fortran compiler is installed, programs can be compiled. Open the “Command Prompt”, and
set the device and directory as appropriate.
189
Chapter 22 ► Appendix B – Start-Up Instructions
At this point the program can be compiled, using “gfortran. The optional “-o” qualifier is used to set
the name of the output file. To execute, you can type the name of the executable (that was specified
with the “-o”).
To compile the example program, the following command would be entered:
C:\cs117> gfortran -o hw hw.f95
This command will tell the 'gfortran' compiler to read the file hw.f95 and, if there are no errors, create
an executable file named hw.exe. If there is an error, the compiler will generate an error message,
sometimes cryptic, and provide a line number. Such errors are usually the result of mistyping one of
the instructions. Any errors must be resolved before continuing.
22.3.5 Executing
To execute or run a program, type the name of the executable file. For example, to execute or run the
hw.exe program:
C:\cs117> hw
Hello World
C:\cs117>
Which will execute the example program and display the “Hello World” message to the screen.
22.3.6 Example
A more complete example is as follows:
It is not necessary to type the extension (i.e., “.exe”) portion of the file name.
190
Chapter 22 ◄ Appendix B – Start-Up Instructions
The screen background may be black depending on the default configuration settings. Once the
Terminal is open, the directory for the working files can be set as shown in the following section.
The prompt will change to show the new directory name (second line). At this point, typing ls (for
directory) will provide a list of files in the directory. While the format will appear different, the files
are the same as shown in the Finder listing.
191
Chapter 22 ► Appendix B – Start-Up Instructions
The “no input files” message means that the installation was completed successfully.
However, if the following message is displayed,
eds-iMac:cs117 ed$ gfortran
-bash: gfortran: command not found
it means that the Fortran compiler is not installed. The installation issue must be addressed before
continuing.
If the following message is displayed,
eds-iMac:cs117 ed$ gfortran -o hw hw.f95
xcode-select: note: no developer tools were found at
'/Applications/Xcode.app', requesting install. Choose an option
in the dialog to download the command line developer tools.
it means that the Fortran compiler is installed, but Xcode is not installed. Xcode must be successfully
installed in order to continue. Once the Fortran and Xcode installations are completed successfully, the
compilation steps detailed in Chapter 3 can be performed.
22.4.4 Compilation
Once the Fortran compiler and Xcode are installed, programs can be compiled. Open the Terminal
window and change directory as appropriate.
At this point the program can be compiled, using “gfortran. The optional “-o” qualifier is used to set
the name of the output file. To execute, you can use the name of the executable (that was specified
with the “-o”).
To compile the example program, the following command would be entered:
eds-iMac:cs117 ed$ gfortran -o hw hw.f95
This command will tell the 'gfortran' compiler to read the file hw.f95 and, if there are no errors, create
an executable file named hw (no extension). If there is an error, the compiler will generate an error
message, sometimes cryptic, and provide a line number. Such errors are usually the result of mistyping
one or more of the instructions. Any errors must be resolved before continuing.
192
Chapter 22 ◄ Appendix B – Start-Up Instructions
22.4.5 Executing
To execute or run a program, type “./” and the name of the executable file. For example, to execute or
run the hw program:
eds-iMac:cs117 ed$ ./hw
Hello World
eds-iMac:cs117 ed$
Which will execute the example program and display the “Hello World” message to the screen.
22.4.6 Example
A more complete example is as follows:
193
Chapter 22 ► Appendix B – Start-Up Instructions
194
23 Appendix C – Random Number Generation
Generating random numbers is a common requirement for many problems. The following provides a
summary of utilizing the built-in Fortran random number generator routines.
23.1 Initialization
The first step in generating random numbers is to initialize the Fortran random number generator,
random_seed(). The most basic initialization is performed as follows:
call random_seed()
This will initialize the random number generator with a default seed. As such, each execution will re-
generate the same series of random numbers for each execution. While this may not appear very
random, since successive executions generate the same series of random numbers, the testing is more
repeatable.
The random number between 0.0 and 1.0 such that 0.0 ≤ random number < 1.0.
In order to obtain a larger number, it can be multiplied by an appropriate scale. For example, to
simulating the roll of a dice, a random integer number between 1 and 6 would be required. The
following code would obtain the random number and then scale it and convert to integer as required.
call random_number(x)
die = int(x*6.0) + 1
Since the 0.0 is a possible value and 1.0 is not ( 0.0 ≤ random number < 1.0) 1 is added to ensure that 0
cannot be assigned to the variable die. Further, since .999 is the largest possible value (since 1.0 is
not), and .999 * 6 will generate 6 (5.9 truncated to 5 with 1 added).
195
Chapter 23 ► Appendix C – Random Number Generation
23.3 Example
A simple example program to generate 100 random integer numbers, each between 1 and 100, is as
follows:
program rand
implicit none
integer, parameter :: rcount=100
integer :: i
integer, dimension(rcount) :: nums
real :: x
call random_seed()
do i = 1, rcount
call random_number(x)
nums(i) = int(x*100.0) + 1
end do
The call to random_seed() must be performed before the call to random_number(). Additionally, the
call to random_seed() can only be performed once.
The output of this example program is shown below:
Random Numbers:
100 57 97 75 37 49 8 1 35 35
22 14 91 39 45 67 2 66 65 33
86 41 21 97 60 68 46 34 11 76
61 72 90 66 16 62 98 100 26 56
66 56 98 91 66 73 41 93 15 68
77 34 12 62 83 95 74 50 38 43
56 100 100 75 96 10 74 76 95 71
82 56 7 49 60 14 59 52 89 31
67 67 51 27 8 11 55 38 2 80
63 78 96 12 32 60 5 12 22 11
196
Chapter 23 ◄ Appendix C – Random Number Generation
23.4 Example
In order to generate different random number for successive executions, the seed must be initialized
with a different set of seed values each time.
The following example simulates the roll of two dice, which requires two random integer numbers,
each between 1 and 6.
program diceRoll
implicit none
integer :: m, die1, die2, pair
real :: x
integer :: i, n, clock
integer, dimension(:), allocatable :: seed
character(10) :: nickname
call random_seed(size = n)
allocate(seed(n))
call system_clock(count=clock)
seed = clock + 37 * (/(i-1, i=1, n)/)
call random_seed(put = seed)
deallocate(seed)
call random_number(x)
die1 = int(x*6.0) + 1
call random_number(x)
die2 = int(x*6.0) + 1
Will generate different values each execution. For example, three executions of the example program
are shown below:
C:\fortran> dice
Dice 1: 5
Dice 2: 4
Dice Sum 9
C:\fortran> dice
Dice 1: 2
Dice 2: 4
Dice Sum 6
197
Chapter 23 ► Appendix C – Random Number Generation
C:\fortran> dice
Dice 1: 1
Dice 2: 6
Dice Sum 7
C:\fortran>
198
24 Appendix D – Intrinsic Functions
The following is a partial listing of the Fortran 95/2003/2008 intrinsic functions. Only the most
common intrinsic functions are included in this section. A complete list can be found on-line at the
GNU Fortran documentation web page.
Function Description
INT(A) Returns the integer value of real argument A, truncating
(real part) towards zero.
NINT(X) Return the nearest integer value (with appropriate
rounding up or down) of the real argument X.
REAL(A) Returns the real value of integer argument A.
Function Description
ABS(A) Returns the integer absolute value of integer argument A.
MOD(R1,R2) Return the integer remainder of integer argument R1
divided by integer argument R2.
199
Chapter 24 ► Appendix D – Intrinsic Functions
Function Description
ABS(A) Returns the real absolute value of real argument A.
ACOS(W) Returns the real inverse cosine of real argument W in
radians.
ASIN(W) Returns the real inverse sine of real argument W in radians.
ATAN(X) Returns the real inverse tangent of real argument X in
radians.
COS(W) Returns the real cosine of real argument W in radians.
LOG(W) Returns the real natural logarithm of real argument W. Real
argument W must be positive.
MOD(R1,R2) Return the real remainder of real argument R1 divided by
real argument R2.
SIN(W) Returns the real sine of real argument W in radians.
SQRT(W) Returns the real square root of real argument W. Real
argument W must be positive.
TAN(X) Returns the real tangent of real argument X in radians.
Function Description
ACHAR(I) Returns the character represented by integer argument I
based on the ASCII table (Appendix A). Integer argument I
must be between 1 and 127.
IACHAR(C) Returns the integer value of the character argument C
represented by ASCII table (Appendix A).
LEN(STR) Returns the integer value representing the length of string
argument STR.
LEN_TRIM(STR) Returns the integer value representing the length of string
argument STR excluding any trailing spaces.
LGE(STR1,STR2) Returns the logical true, if STR1 ≥ STR2 and false
otherwise.
LGT(STR1,STR2) Returns the logical true, if STR1 > STR2 and false
otherwise.
200
Chapter 24 ◄ Appendix D – Intrinsic Functions
Function Description
AIMAG(Z) Returns the real value of the imaginary part of the complex
argument Z.
CMPLX(X,Y) Returns the complex value with real argument X and the
real part and real argument Y as the imaginary part.
REAL(A) Returns the real value of the real part of the complex
argument Z.
Function Description
MAXLOC(A1) Returns the integer location or index of the maximum value
in array A1.
MAXVAL(A1) Returns the maximum value in array A1. Type of value
returned is based on the type of the argument array A1.
MINLOC(A1) Returns the integer location or index of the minimum value
in array A1.
MINVAL(A1) Returns the minimum value in array A1. Type of value
returned is based on the type of the argument array A1.
SUM(A1) Returns the sum of values in array A1. Type of value
returned is based on the type of the argument array A1.
201
Chapter 24 ► Appendix D – Intrinsic Functions
Function Description
COMMAND_ARGUMEN Returns the number of command line arguments.
T_COUNT()
GET_COMMAND_ARG Returns the command line arguments, if any.
UMNENT(NUMBER, • NUMBER, integer argument of the number to
VALUE, LENGTH, return. Must be between 1 and
STATUS) COMMAND_ARGUMENT_COUNT().
• VALUE, character(*), Nth argument
• LENGTH, integer, length of argument returned in
VALUE
• STATUS, integer, status, 0=success and -1=VALUE
character array is too small for argument, other
values=retrieval failed
CPU_TIME(TIME) Returns the amount of CPU time expended on the current
program in seconds. TIME is return as a real value.
DATE_AND_TIME Return the date and time.
(DATE, • DATE(), character(8), string in the form
TIME,ZONE,VALUES) YYYYMMDD, where YYYY is year, MM is
month, and DD is date.
• TIME(), character(10), string in the form
HHMMSS.SSS where HH is hour, MM is minute,
SS is second, and SSS is millisecond.
• ZONE(), character(5), string in the form of
±HHMM, where HHMM is the time difference
between local time and Coordination Universal
Time.
• VALUES(), integer array where
◦ VALUES(1) → year
◦ VALUES(2) → month (1-12)
◦ VALUES(3) → date (1-31)
◦ VALUES(4) → time zone difference (minutes)
◦ VALUES(5) → hour (0-23)
◦ VALUES(6) → minutes
◦ VALUES(7) → seconds (0-59)
◦ VALUES(8) → milleseconds (0-999)
Each argument is optional, but at least one argument must
be included.
202
25 Appendix E – Visualization with GNUplot
The Fortran language does not have any built-in graphics capabilities. To support some basic data
visualization a plotting application, GNUplot, can be used. GNUplot is a free, open source plotting
program that can plot data files and display user-defined functions.
This appendix provides a very brief summary of some of the basic GNUplot functions as applied to
plotting data from simple programs in this text. An general example program to plot a simple function
is provided for reference.
To ensure that GNUplot is installed correctly, for Windows machine, you can enter command prompt
and type,
wgnuplot
which will start GNUplot by opening a new window. To exit, type exit at the prompt.
Complete documentation, tutorials, and examples are available at that site. Additionally, there are
many other web sites dedicated to GNUplot.
203
Chapter 25 ► Appendix E – Visualization with GNUplot
25.2.1 Header
The header will provides some guidelines on how the output should look, including title (if any), axises
(if any), labels (if any), and plotting color(s). Additionally, comments can be included with a “#”
character. Comments are useful to provide information about the contents of the plot file or nature of
the data being plotted. A typical header might be as follows:
25.2.2 Footer
The footer is used to formally tell GNUplot there are no more points. Additionally, the “pause”
directive can be used to ensure that any plots displayed from the command line are left on the screen.
A typical footer might be as follows:
end
pause -1
which will start GNUplot and instruct GNUplot to read the file “file.plt”. The file name can be
anything and the file extension is not required to be “.plt”.
If the header or footer commands are incorrect or the data points are invalid, nothing will be displayed.
To investigate, the file can be opened with a text editor.
25.4 Example
This section provides an example program that plots a simple function.
y = sin( x) ∗ ( 1−cos ( x)
3.0 )
The program, data file, and final output are presented for reference.
204
Chapter 25 ◄ Appendix E – Visualization with GNUplot
program plotExample
implicit none
real, dimension(200) :: x, y
integer :: i, opnstat
! Write header
write (12, '(a)') "# Example Plot File"
write (12, '(a)') "set title ""Example Plot Function"" "
write (12,'(a,a)') "plot ""-"" notitle with dots ",
"linewidth 2 linecolor 2"
close(12)
The data file name can be changed or read from the user.
205
Chapter 25 ► Appendix E – Visualization with GNUplot
4.900000 -1.043852
4.950000 -1.048801
5.000000 -1.050716
end
pause -1
The output file can be edited with a standard text editor. This will allow checking the data file for
possible errors if it does not display correctly.
On Windows machines, the plot can be printed by right clicking on the blue bar (on top). This will
display a menu, with “Print” as one of the options.
206
26 Appendix F – Quiz Question Answers
This appendix provides answers for the quiz questions in each chapter.
207
Chapter 26 ► Appendix F – Quiz Question Answers
4) An integer variable can be converted to a real with the real conversion function. For example,
intVar = int(realVar)
Note, in this example precision may be lost since the fractional part is truncated (not rounded).
5) The two logical constants are .true. and .false. which must include the leading and trailing
periods.
6) Some intrinsic functions are real(), int(), nint(), cos(), sin(), mod(), tan(), and sqrt(). There
are more as listed in Appendix D.
7) The statements are as follows:
x1 = (pi / 6.0) * (3.0 * a**2 + 3.0 * b**2 + c**2)
x2 = -(2.0 * a / c) * cos(b) * sin(b)
x3 = (-b + sqrt(b**2 – 4.0 * a * c)) / (2.0 * a)
208
Chapter 26 ◄ Appendix F – Quiz Question Answers
209
Chapter 26 ► Appendix F – Quiz Question Answers
210
Chapter 26 ◄ Appendix F – Quiz Question Answers
next iteration of the loop is started (from the beginning of the loop).
4) There may be an unlimited number of cycle statements. Typically, there is only one.
5) If there are multiple cycle statements, only the first executed cycle statement will be executed.
6) The output is as follows:
The SUM is: 15
8) The statements are valid, however since the initial value of i is greater than the stop value, no
statements in the loop will be executed.
9) The statements are valid, however since the initial value of i is greater than the stop value, no
statements in the loop will be executed.
10) There is no specified limit.
11) When nesting IF statements, the nested IF statement must be completely nested within the loop.
211
Chapter 26 ► Appendix F – Quiz Question Answers
2) The results are .false., .true., .false., .false., .true., .false., .true. where the leading and trailing
periods are required.
3) The value for astr1 = “abc”, the value for astr2 = “456”, the value for astr3 = “12345678910”,
and the value for astr4 = “DEF123bc”.
4) The integer value can be obtained by using the IACHAR() function.
5) The character can be obtained from the integer value by using the ACHAR() function.
212
Chapter 26 ◄ Appendix F – Quiz Question Answers
213
Chapter 26 ► Appendix F – Quiz Question Answers
214
Chapter 26 ◄ Appendix F – Quiz Question Answers
b) out
c) inout
12) The term side-effect is when a function changes one or more of its input arguments. In general,
this is considered poor practice and should be avoided.
today%monthname = "December"
today%month = 12
today%date = 25
today%year = 2013
215
Chapter 26 ► Appendix F – Quiz Question Answers
newyear%monthname = "January"
newyear%month = 1
newyear%date = 1
newyear%year = 2011
216
Chapter 26 ◄ Appendix F – Quiz Question Answers
7) A complete recursion tree for the recursive Fibonnaci function with an input of 4 is as follows:
main:
fib(4)
step 16
step 1
fib:
fib(3) +
fib(2)
step 2 step 10
step 15
step 5 fib:
fib: fib: fib:
fib(1) +
return 1 return 1 return 0
fib(0)
step 4 step 7
step 6 step 7
fib: fib:
return 1 return 0
217
Chapter 26 ► Appendix F – Quiz Question Answers
4) The statement to convert the integer variable iNum=234 into a character string sNum is as
follows:
write (sNum, '()', iostat=cvtErr) iNum
7) If there are no arguments entered on the command line, the get_command_argument() system
service call will return a 0.
8) The statement is as follows:
call get_command_argument(number=3, value=arg3, &
length=arg3length, status=arg3stat)
218
27 Appendix G – Fortran 95/2003/2008 Keywords
In programming, a keyword is a word or identifier that has a special Fortran 95/2003/2008 meaning.
Keywords are reserved in that they cannot be used for anything else such variable names.
The Type as listed in the table refers to the following:
● statement → implies a keyword that starts a statement, usually one line unless there is a
continuation "&"
● construct → implies multiple lines, usually ending with "end …"
● attribute → implies it is used in a statement to further clarify or specify additional
information.
For reference, below is a partial list of keywords or reserved words. For a complete list of keywords,
refer to the on-line GNU Fortran 95/2003/2008 documentation.
219
Chapter 27 ► Appendix G – Fortran 95/2003/2008 Keywords
220
Chapter 27 ◄ Appendix G – Fortran 95/2003/2008 Keywords
221
Chapter 27 ► Appendix G – Fortran 95/2003/2008 Keywords
222
Index
223
Chapter ► Index
224
Chapter ◄ Index
225