Com 221
Com 221
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.
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.
1
WHAT IS A PROGRAM
A computer program is a series of instructions which enables the computer to perform a
designated task. As this text will demonstrate, a computer must be told what to do in
precise, step-by-step detail.
These steps might include obtaining data, arithmetic operations (addition, subtraction,
multiplication, division, etc.), data storage, and information output. The computer will
perform these tasks as instructed, even if they don't always make sense. Consequently, it
is the programmer who must develop a solution to the problem.
OPERATING SYSTEM
The Operating System, or OS, is an interface between the user and the hardware (CPU,
memory, screen, disk drive, etc.). The OS is responsible for the management of the
hardware, coordination of activities, and the sharing of the resources of the computer
that acts as a host for computing applications run on the machine. The common
operating systems include various versions of Windows, MAC OS X, and UNIX/Linux.
Programs written in Fortran will work on these operating systems.
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.
ARCHITECTURE OVERVIEW
The basic components of a computer include a Central Processing Unit (CPU), Primary
Storage or Random Access Memory (RAM), Secondary Storage, and Input/Output
devices (i.e., screen, keyboard, and mouse), and an interconnection referred to as BUS.
The secondary storage may be a Solid-State Drive (SSD), disk drive, or other type of
secondary storage media.
2
A very basic diagram of a computer architecture is as follows
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.
3
Program Formats
Fortran 95/2003/2008 programs must be written and formatted in a specific manner.
The following sections summarize the basic program elements followed by a simple
example.
Program Statement
A Fortran 95/2003/2008 program is started with a program statement, 'program <name>',
and ended with an end program statement, 'end program <name>'. Refer to the example
first program to see an example of these statements. The program name for <name> is
chosen by the program author and would typically reflect something related to what the
program does.
The name used may not be used again for other program elements (such as variables
described in the next chapter). The program name must start with a letter, followed by
letters, numbers, or an underscore (“_”) and may not be longer than 32 characters.
Capital letters are treated the same way as lower-case letters. Refer to the sample
program in the following sections for an example
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.
4
SIMPLE OUTPUT
A program can display a simple message to the screen by using the write statement. For
example:
write (*,*) "Hello World"
Will display the message Hello World to the screen. Additional information regarding
the write
statement and outputting information is provided in later chapters.
3.2.4 Example – First Program
The following trivial program illustrates the initial formatting requirements.
! Simple Example Program
program first
write (*,*) "Hello World."
end program first
In this example, the program is named 'first'. This file, provided as input to the
compiler, is typically referred to as the source file.
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.
5
Variables must be declared at the start of the program.
Variable Names
Each variable must be named. The variable name is how variables, which are memory
locations, are referred to by the program. A variable name must start with a letter,
followed by letters, numbers, or an underscore (“_”) and may not be longer than 32
characters. Capital letters are treated the same way as lower-case letters, (i.e., “AAA” is
the same variable as “aaa”).
For example, some valid variable names are as follows:
x
today
next_month
summation10
Some invalid examples include:
1today
this_is_a_variable_name_with_way_way_too_many_characters_in_it
next@month
next month
today!
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.
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).
6
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.
DATA TYPES
Fortran, like many other high level programming languages, supports several different
data types to make data manipulation easier. The most frequently used data types are
integer and floating-point.
Other data types are complex numbers, characters and logical data.
In a Fortran statement, data can appear either as a literal (e.g., an actual value such as
3.14159, 16, -5.4e-4) or as a variable name which identifies a location in memory to
store the data.
The five basic Fortran 95/2003/2008 data types are as follows:
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.
Integer
7
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.
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.
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.
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.
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.
8
DECLARATIONS
Fortran variables must be declared before executable statements.This
section provides an introduction to how variables are declared.
I. Declaring Variables
Declaring variables formally defines the data type of each variable and sets aside a
memory location.
This is performed by a type declaration statement in the form of:
<type> :: <list of variable names>
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
Additional examples include:
integer :: today, tomorrow, yesterday
real :: ans2
complex :: z
logical :: answer
character :: myletter
The declarations can be entered in any order.
Additional information regarding character variables is provided in chapter 11.
II. Variable Ranges
The computer has a predefined amount of space that can be used for each variable. This
directly impacts the size, or range, of the number that can be represented.
9
For example, an integer value can range between −2,147,483,648 and +2,147,483,647.
Fortunately, this is large enough for most purposes.
The range for real values is more complex. The range is approximately ±1.7×10±38
supporting about 7 digits of precision.
TYPE CHECKING
The variable type declaration is enforced by the compiler. For example, if a variable is
declared as an integer, only an integer value (a whole number) is allowed to be assigned
to that variable. Attempting to assign a value of 1.75 to an integer variable could cause
problems related to loss of precision. This restriction is related to the fact that the
internal representations for various types are very different and not directly compatible.
The compiler can sometimes recognize a type mismatch and implicitly (automatically)
perform a conversion. If this is done automatically, it is not always clear and could lead
to errors. As such, it is generally considered poor programming practice.
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.
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
Additional examples include:
integer :: todaysday=15, tomorrow=16, yesterday=14
real :: ave = 5.5
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.
10
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.
III. 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.
11
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"
write (*,*) "Greeting: ", msg
end program example1
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.
IV. 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.
12
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.
V. 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.
VI. 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.
13
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.
a) Integer Literals
The following are some examples of integer constants:
1
0
-100
32767
+42
An integer must be a whole number (with no fractional component).
b) Real Literals
The following are some examples of real constants:
1.0
-0.25
3.14159
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.
c) E-Notation
14
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.
The following are some real constants using e-notation:
2.75E5
3.3333E-1
Hence, 2.75E5 is 2.75×105 or 275,000 and 3.333E-1 is 3.333×10−1 or 0.3333 or
approximately one third.
d) Complex Literals
A complex constant is designated by a pair of constants (integer or real), separated by a
comma and
enclosed in parentheses. Examples are:
(3.2, -4.1)
(1.0, 9.9E-1)
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.
e) Character Literals
A character constant is either a single character or a set of characters, called a string. A
character is a single character enclosed in quotes. A string consists of an arbitrary
sequence of characters also enclosed in quotes. Some examples include:
"X"
"Hello World"
"Goodbye cruel world!"
"Have a nice day"
Character and string constants (enclosed with quotes) are case sensitive. So, character
“X” (upper-case) is not the same as “x” (lower-case).
15
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.
Logical Constants
The fifth type is the logical constant. These can only have one of two values:
.true.
.false.
The dots enclosing the true and false are required.
ARITHMETIC OPERATIONS
This section summarizes the basic arithmetic operations.
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
and to set it equal to 2.71828183, it would be:
answer1 = 2.71828183
The value for answer1 can be changed as often as needed. However, it can only hold
one value at a time.
16
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
and calculate the sum,
mysum = number1 + number2
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.
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
and calculate the difference,
ans = value1 – value2
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.
Multiplication
The Fortran multiplication operation is specified with an asterisk (*). For example, to
declare the variables, ans, value1, value2, and value3,
17
real :: ans, value1=4.5, value2=2.0, value3=1.5
and calculate the product,
ans = value1 * value2
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.
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
and calculate the quotient,
ans = value1 / value2
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.
ans = value1 / value2 / value3
which will set the variable ans to 2.0. Additionally, it will over-write the previous value
of 4.0.
18
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
! Display initial header
write (*,*) "Velocity Calculation Program"
write (*,*)
! Calculate the velocity
velocity = acceleration * time
write (*,*) "Velocity = ", velocity
end program findvelocity
INPUT – READ
To obtain information from the user, a read statement is used. For example, to declare
the variables num1, num2,
integer :: ans1, ans2
then read a value for ans1 from the user,
read (*,*) ans1
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.
21
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
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:
Enter date (month, day, and year)
10 17 2009
Enter date (month, day, and year)
10
17
2009
Enter date (month, day, and year)
10 17 2009
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.
22
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 initial header and blank line
write (*,*) "Circle Area Calculation Program"
write (*,*)
! Prompt for and read the radius
write (*,*) "Enter Circle Radius"
read (*,*) radius
! Calculate the circle area
area = pi * radius**2
! Display result
write (*,*) "Circle Area: ", area
23
end program circle
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.
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.
Understand the Problem
Before attempting to create a solution, it is important to understand the problem.
Ensuring a complete understanding of the problem can help reduce errors. The first step
is to understand what input is required and what information the program is expected to
produce.
Create the Algorithm
The algorithm is the name for the ordered sequence of steps involved in solving the
problem. That sounds good, but it is a fancy way of saying that an algorithm is just a
24
step-by-step procedure to solve a problem. Once the program is understood, the steps
can be developed to solve that specific problem.
There can be multiple correct solutions to a given problem.
The process for creating an algorithm can be different for different people. In general,
some time should be devoted to thinking about a possible solution. This may involve
working on some possible solution on a scratch piece of paper. Once a possible solution
is selected, that solution can be developed into an algorithm. The algorithm can be
written down, reviewed, and refined. This algorithm is the outline of the program.
For this problem, the variables and constants must be declared, the applicable headers
and prompts displayed, and the values for L and α read from the user. The degree
entered by the user should be converted to radians8, which is required by the sin
function. The formula to convert degrees to radians is as follows:
radians = degrees ∗ pi/180
Then the period can be calculated based on the provided formula and the results
displayed.
Formalizing this, the following steps can be developed and written down as follows:
! 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.
Implement the Program
25
Based on the algorithm, the following program can be created.
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
real, parameter :: gravity=980.0, pi=3.14159
! display initial header
write (*,*) "Pendulum Period Calculation Program"
write (*,*)
! prompt for and read the length and angle values
write (*,*) "Enter Length and Angle values:"
read (*,*) length, angle
! convert degrees to radians
alpha = angle * pi / 180.0
! calculate the period
pperiod = 2.0 * pi * sqrt(length/gravity) * &
( 1.0 + 1.0/4.0 * sin(alpha/2.0)**2 )
! display the results
write (*,*) "The period is:", pperiod
end program period
26
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.
Test/Debug the Program
Once the program is written, testing should be performed to ensure that the program
works. The testing will be based on the specific parameters of the program. In this
example, each of the three possible values for the discriminant should be tested.
ERROR TERMINOLOGY
In case the program does not work, it helps to understand some basic terminology about
where or what the error might be.
1. Compiler Error
Compiler errors are generated when the program is compiled. This means that the
compiler does not understand the instructions. The compiler will provide a list of errors
with the line number of each error. It is recommended to address the errors from the top
down. Resolving an error at the top can clear multiple errors further down.
Typical compiler errors include misspelling a statement and/or omitting a variable
declaration. For example, if the correct Fortran statement “write (*,*)” is entered
incorrectly as “wrote (*,*)”, an error will be generated.
In this case, the compiler error displayed will appear as follows:
c:\mydir> gfortran -o period period.f95
period.f95:13.1:
wrote (*,*)
1
Error: Unclassifiable statement at (1)
27
2. Run-time Error
A run-time error is something that causes the program to crash. For example, if a
number is requested and a letter is entered, it will cause a run-time error.
3. Logic Error
A logic error is when the program executes, but does not produce the correct result. For
example, coding a provided formula incorrectly or attempting to compute the average of
a series of numbers before calculating the sum would be considered a logic error.
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.
CONDITIONAL EXPRESSIONS
The first step is to compare two values. Values may be literals, variables, or
expressions. These values are compared with a relational operator and are referred to as
operands. Relational operators are used between variables or operands of matching
types. That is real to real, integer to integer, logical to logical, and character/string to
character/string.
The basic relational operators are:
28
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
it might be useful to know if the current value of gameLives is greater than 0.
In this case, the conditional expression would be,
(gamelives > 0)
Which will result in a true or false result based on the value of the variable gameLives.
LOGICAL OPERATORS
Logical operators are used between two logical variables or two conditional expressions.
They are:
29
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.
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
30
different forms of the basic IF statement. Each of the forms is explained in the
following sections.
IF THEN Statement
The IF statement, using the conditional expression, is how programs make decisions.
The general format for an IF statement is as follows:
if ( <conditional expression> ) then
<fortran statement(s)>
end if
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 statement
might be;
if ( gameLives == 0 ) then
write (*,*) "Game Over."
write (*,*) "Please try again."
end if
which will display the message “Game Over.” and “Please try again.” on the next line if
the value of gameLives is equal to 0.
IF THEN ELSE Statement
The IF THEN ELSE statement expands the basic IF statement to also allow a series of
statements to be performed if the conditional expression evaluates to false.
The general format for an IF THEN ELSE statement is as follows:
if ( <conditional expression> ) then
<fortran statement(s)>
else
<fortran statement(s)>
end if
31
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 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.
32
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.
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.
Counter Controlled Looping
A counter controlled loop repeats a series of one or more Fortran statements a set
number of times.
The general format of the counting loop is:
do count_variable = start, stop, step
33
<fortran statement(s)>
end do
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.
35
conditional statement to allow exiting a loop based on a specific condition. The exit
statement can be used in a counter controlled loop or a conditionally controlled loop.
For example, given the following declarations,
integer :: i
the following loop,
do i = 1, 10
if (i == 5) exit
write (*,*) i
end do
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
the following loop,
do i = 1, 10
if (i == 5) cycle
write (*,*) i
end do
will display the numbers from 1 to 4 and 6 to 10.
36
THANK YOU GURUS
37