![]() |
![]() | |||||
|
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
|
Introduction and Overview FORTRAN is a general-purpose high-level programming language, designed for efficient mathematical computations and finds its primary uses in scientific and engineering applications. In fact, the name FORTRAN is an acronym for FORmula TRANslation. FORTRAN was the first high-level programming language to see wide usage. FORTRAN is an example of an imperative or procedural language. Learning ObjectivesThe purpose of this lesson is to introduce you to the basic structure and syntax of FORTRAN 77 programs. At the end of this lesson, you should be able to:
History and Language StandardsFORTRAN was developed in 1957 at IBM for execution on the IBM 704 computer (a batch processing and programming environment). There have been many versions of FORTRAN over the years. By convention, a FORTRAN version is denoted by the last two digits of the year the standard was proposed. The first standard of the language was adopted in 1966, thus we have:
Programmers should be aware that most FORTRAN 77 compilers allow a superset of FORTRAN 77, i.e., they allow non-standard extensions. In this course we will focus on standard ANSI FORTRAN 77.
Why Study FORTRAN?FORTRAN is still among the more popular high-level programming languages used in scientific and engineering applications. Because of this fact, it is important for engineering and engineering technology graduates to be able to read and modify FORTRAN programs. Periodically, someone will predict that FORTRAN will fade in popularity and soon be of historical interest only. However, up to this point in time, these predictions have not proven accurate. FORTRAN is the most enduring computer programming language in history. One of the main reasons FORTRAN has survived and will survive is software inertia. Once a company has spent many man-years and perhaps millions of dollars on a software product, it is unlikely to try to translate the software to a different language. Reliable software translation is a very difficult task.PortabilityA major advantage FORTRAN has is that it is standardized by ANSI1 and ISO2. Consequently, if your program is written in ANSI FORTRAN 77 then it will run on any computer that has a FORTRAN 77 compiler. Thus, FORTRAN programs are portable across machine platforms.Documentation of the various FORTRAN Standards is available on the Web.
FORTRAN 77 BasicsA FORTRAN program is just a sequence of valid statements. The statements must follow a certain syntax to be a valid. We start by looking at a simple example:
C234567890123456789012345678901234567890...
c This program reads a real
c number R from the keyboard,
c calculates and prints the
c area of a circle with radius R.
program circle
real R,area
print *,'Enter radius R in inches:'
read(*,*) R
area=3.14159*R**2
write(*,*) 'Area = ',area,' sq.in.'
stop
end
Examine the program and note the following characteristics.
Lines that begin with the letter "C" in column 1 are comments
and are ignored by the compiler. The purpose of comments is
to document the program and make it more readable for humans.
Originally, all FORTRAN programs had to be written in all upper-case
letters. Most programmers now write FORTRAN programs is lower-case
since it is considered more readable.
Try it! Connect to the class server, use pico to create a program file for circle.for, compile and run the above program. Program OrganizationA FORTRAN program generally consists of a main program (or driver) and possibly several subprograms (or procedures or subroutines). For now we will assume all the statements are in the main program; subprograms will be treated later. The structure of a main program is:
C234567890123456789012345678901234567890...
program name
declarations
statements
stop
end
On this page, words that are shown in italics
should not be taken as literal text, but rather as a generic description.
The stop statement is optional and may seem superfluous
since the program will stop when it reaches the end anyways,
but it is recommended to always terminate a program with the
stop statement to emphasize that the execution flow stops there.
Column Position SignificanceFORTRAN 77 is a fixed-field format language. The source code fields are defined by column position as follows:
Col: Use
1: Blank, or a "c" or "*" for comments
2-5: Statement label (optional)
6: Continuation of previous line (optional)
7-72: Statements
73-80: Sequence number (optional, rarely used)
Most statements in a FORTRAN 77 program begin with 6 blanks and end before
column 72, i.e., only the statement field is used. Note that FORTRAN 90
allows free format.
CommentsAs mentioned above, a line that begins with the letter "C" or an asterisk "*" in the first column is a comment. Comments may appear anywhere in the program. Well-written comments are crucial to program documentation and readibility. You may also encounter FORTRAN programs that use the exclamation mark (!) for comments. This is not standard in FORTRAN 77, but is allowed in FORTRAN 90. In FORTRAN 90, the exclamation mark may appear anywhere on a line (except in positions 2-6).Long StatementsOccasionly, a FORTRAN statement does not fit into one single line. Programmers can break a statement into two or more lines, and use the continuation mark in column 6. For example:
C234567890123456789012345678901234567890...
integer a, b, c, d, e, f
real r, area
C These statements span two physical lines
area = 3.14159265358979
+ * r * r
print *,'A=' ,a,' B=',b,' C=',c,
+ ' D=',d,' E=',e,' F=',f
Any character can be used as a continuation character.
However, it is considered good programming style to use either the
plus sign, an ampersand (&), or numbers (e.g., 2 for the second line,
3 for the third, etc.). Your instructor recommends the first approach,
that is, use of the plus sign.
Blank SpacesBlank (or whitespace) characters are ignored in FORTRAN 77. If you remove all whitespace in a FORTRAN 77 program, the program is still syntactilly correct but is then nearly unreadable for humans.The following are the same statement in FORTRAN:
C234567890123456789012345678901234567890...
do 20 i = 1,20
do20i=1,20
d o 2 0 i = 1 , 2 0
Exercises
Variable NamesVariable names in FORTRAN consist of 1-6 characters (31 in FORTRAN 90) chosen from the letters a-z and the digits 0-9 (FORTRAN 90 also allows the underscore character). The first character must be a letter. Older FORTRAN compilers required programs to be typed in all uppercase. However, FORTRAN 77 is case insensitive, i.e., it does not distinguish between upper and lowercase characters.Data Types and DeclarationsEvery variable should be defined in a declaration statement near the beginning of your program. This establishes the data type of the variable. The most common declarations are:
integer list of variables
real list of variables
double precision list of variables
complex list of variables
logical list of variables
character list of variables
The list of variables should consist of variable names separated
by commas. Each variable should be declared exactly once.
If a variable is undeclared, FORTRAN 77 uses a set of implicit
rules to establish the type. This means all variables starting
with the letters i-n are integers and all others are real.
You may see older FORTRAN programs which rely on these implicit rules
rather than explicit declarations. This practice is not recommended.
The probability of errors in your program increases dramatically when
you do not explicitly declare the variables used in your program.
It is also recommended by your instructor that you provide an initial value for each of the declared variables. The following program segment illustrates this recommendation.
C234567890123456789012345678901234567890...
program exmpl
integer b,h,d
real area,volume
b=0
h=0
d=0
area=0.
volume=0.
When you explicitly declare and initialize variables, you avoid problems
associated with type mismatch and random values.
Integers and Floating Point VariablesFORTRAN 77 has only one data type for integer variables. Integers are usually stored as 32-bits (4-bytes). This means that all integer variables can take on values in the range [-maxint,maxint] where maxint is approximately 2,100,000,000. Can you figure out how to use the program below as a starting point to determine the exact value of the maximum integer value (maxint) allowed on the class server?
C234567890123456789012345678901234567890...
integer i
i = 2100000000
1 print *,i
i = i + 1000
if (i .lt. 0) then
stop
end if
go to 1
end
FORTRAN 77 has two different data types for floating point variables,
called real and double precision. While real
is often sufficient, some numerical calculations need very high precision
and double precision should be used. Usually
a real is a 4 byte variable and the double precision is 8 bytes,
but this is machine dependent. Some non-standard FORTRAN versions
use the syntax real*8 to denote 8 byte floating point variables.
The parameter statementSome constants appear many times in a program. In this case, it is desirable to define them once at the beginning of the program. The parameter statement can be used for this purpose. Use of the parameter statement can make programs more readable by, in effect, giving meaningful names to constants. For example, the area of a circle program could be written as follows:
C234567890123456789012345678901234567890...
C This program reads a real
c number R from the keyboard,
C calculates and prints the
c area of a circle with radius R.
program circle
real pi,R,area
parameter (pi=3.14159)
print *, 'Enter radius R in inches:'
read(*,*) R
area=pi*R**2
write(*,*) 'Area = ',area,' sq. in.'
stop
end
The syntax of the parameter statement is
parameter (name=constant, ... , name=constant)The rules for the parameter statement are:
Exercises
C234567890123456789012345678901234567890...
program circle.for
double R
print 'Enter radius R in inches:'
read(*,*) R
area=3.14159*R^2
write(*,*) 'Area = ', area, ' sq. in.'
end
ConstantsThe simplest form of an expression is a constant. There are six types of constants, corresponding to the six FORTRAN data types. Here are examples of integer constants:
1
0
-100
32767
+15
Real constants will include a fractional part:
1.0625
1.
-0.55
1.0E6
6.6666E-1
The exponential notation (or E-notation) indicates the power of ten that
the constant is to be multiplied by, e.g., E3 is equivalent to 10 raised
to the third power. Exponential notation is easily recognized by
the letter "E" embedded in the constant.
Thus, from the examples above 1.0E6 is a 1 followed by six zeros
(1,000,000) or one million, while 6.6666E-1 is approximately two-thirds.
For constants that are larger than the largest real number allowed, or that require a higher precision, double precision should be used. The notation for double precision numbers is the same as for real constants except the letter "E" is replaced by the letter "D". Here are some examples of double precision constants:
2.0D-1
1D99
25.4D5
Here 2.0D-1 is a double precision one-fifth, while 1D99 is a one followed
by 99 zeros.
The next type is complex number constants. This is designated by a pair of constants (integer or real), separated by a comma and enclosed in parantheses. Examples are:
(2, -3)
(1., 9.9E-1)
The first number denotes the real part and the second the imaginary part.
The fifth type is logical constants. These can only have one of two values:
.TRUE.
.FALSE.
Note that the dots (or periods) enclosing the letters are required.
The last type is character constants. These are most often used as an array of characters, called a string. These consist of an arbitrary sequence of characters enclosed in apostrophes (single quotes):
'ABC'
'Anything goes!'
'It is a nice day'
Strings and character constants are case sensitive.
A problem arises if you want to have an apostrophe in the string itself.
In this case, you should double the apostrophe:
'It''s a nice day'
ExpressionsThe simplest expressions are of the form
operand operator operand
and an example is
x + y
The result of an expression is itself an operand, hence we can nest
expressions together like
x + 2 * y
This raises the question of precedence: Does the last expression mean
x + (2*y) or (x+2)*y? The precedence of arithmetic
operators in FORTRAN 77 are (from highest to lowest):
** {exponentiation}
*,/ {multiplication, division}
+,- {addition, subtraction}
All these operators are calculated left-to-right, except the
exponentiation operator **, which has right-to-left precedence.
If you want to change the default evaluation order, you can
use parentheses.
The above operators are all binary operators. there is also the unary operator - for negation, which takes precedence over the others. Hence an expression like -x+y means what you would expect. Extreme caution must be taken when using the division operator, which has a quite different meaning for integers and reals. If the operands are both integers, an integer division is performed, otherwise a real arithmetic division is performed. For example, 3/2 equals 1, while 3./2. equals 1.5.
Assignment StatementsThe assignment statement has the following form:
variable_name = expression
The interpretation is as follows:
Evaluate the expression on the right-hand side of the assignment operator
(the equal symbol) and assign the resulting value to the variable on the
left-hand side. The expression on the right-hand side may contain other
variables, but their values will remain unchanged.
For example,
C234567890123456789012345678901234567890...
area = pi * r**2
does not change the value of pi or r, only the value of
the variable area.
Type Conversion & CoercionWhen different data types occur in the same expression, type conversion has to take place, either explicitly (by the programmer) or implicitly (by coercion). FORTRAN will do some type conversion by coercion, e.g.,
C234567890123456789012345678901234567890...
real x
x = x + 1
will convert the integer one to the real number one,
and has the desired effect of incrementing x by one.
However, in more complicated expressions, it is good programming
practice to force the necessary type conversions explicitly.
For numbers, the following functions are available:
int
real
dble
ichar
char
The first three have the obvious meaning. The ichar function takes
a character and converts it to an integer, while the char function does
exactly the opposite.
The following example illustrates how to multiply two real variables x and y using double precision and then store the result as a double precision variable, w:
C234567890123456789012345678901234567890...
w = dble(x)*dble(y)
Note that this is different from
C234567890123456789012345678901234567890...
w = dble(x*y)
Exercises
Logical ExpressionsLogical expressions can only have the value .TRUE. or .FALSE.. A logical expression can be formed by comparing arithmetic expressions using the following relational operators:operator meaning .LT. less than .LE. less than or equal to .GT. greater than .GE. greater than or equal to .EQ. equal to .NE. not equal toSo you cannot use symbols like < or = for comparison in FORTRAN 77, but you have to use the correct two-letter abbreviation enclosed by dots! (Such symbols are allowed in FORTRAN 90, though.) Logical expressions can be combined by the logical operators .AND. .OR. .NOT. which have the obvious meaning. Logical variables and assignmentTruth values can be stored in logical variables. The assignment is analagous to the arithmetic assignment. Example:
C234567890123456789012345678901234567890...
logical a, b
a = .TRUE.
b = a .AND. 3 .LT. 5/2
The order of precedence is important, as the last example shows.
The rule is that arithmetic expressions are evaluated first,
then relational operators, and finally logical operators.
Hence b will be assigned .FALSE. in the example above.
Logical variables are seldom used in FORTRAN. But logical expressions
are frequently used in conditional statements like the if
statement.
Exercises
Format statementsSo far we have only showed free format input/output. This uses a set of default rules for how to output values of different types (integers, reals, characters, etc.). Often the programmer wants to specify some particular input or output format, e.g., how many decimals in real numbers. For this purpose FORTRAN 77 has the format statement. The same format statements are used for both input and output.Syntax
write(*, label) list-of-variables
label format format-code
A simple example demonstrates how this works. Say you have an
integer variable you want to print in a field 4 characters wide and
a real number you want to print in fixed point notation with 3 decimal places.
write(*, 900) i, x
900 format (I4,F8.3)
The format label 900 is chosen somewhat arbitrarily, but it is common practice
to number format statements with higher numbers than the control flow labels.
After the keyword format follows the format codes enclosed in
parenthesis. The code I4 stands for an integer with width four, while
F8.3 means that the number should be printed using fixed point notation
with field width 8 and 3 decimal places.
The format statement may be located anywhere within the program unit. There are two programming styles: Either the form, at statement follows directly after the read/write statement, or all the format statements are grouped together at the end of the (sub-)program.
Common format codesThe most common format code letters are:A - text string D - double precision numbers, exponent notation E - real numbers, exponent notation F - real numbers, fixed point format I - integer X - horizontal skip (space) / - vertical skip (newline)The format code F (and similarly D, E) has the general form Fw.d where w is an integer constant denoting the field width and d is an integer constant denoting the number of significant digits. For integers only the field width is specified, so the syntax is Iw. Similarly, character strings can be specified as Aw but the field width is often dropped. If a number or string does not fill up the entire field width, spaces will be added. Usually the text will be adjusted to the right, but the exact rules vary among the different format codes. For horizontal spacing, the nX code is often used. This means n horizontal spaces. If n is omitted, n=1 is assumed. For vertical spacing (newlines), use the code /. Each slash corresponds to one newline. Note that each read or write statement by default ends with a newline (here FORTRAN differs from C).
Some examplesThis piece of FORTRAN code
C234567890123456789012345678901234567890...
x = 0.025
write(*,100) 'x=', x
100 format (A,F)
write(*,110) 'x=', x
110 format (A,F5.3)
write(*,120) 'x=', x
120 format (A,E)
write(*,130) 'x=', x
130 format (A,E8.1)
produces the following output when we run it:
x= 0.0250000 x=0.025 x= 0.2500000E-01 x= 0.3E-01Note how blanks are automatically padded on the left and that the default field width for real numbers is usually 14. We see that FORTRAN 77 follows the rounding rule that digits 0-4 are rounded downwards while 5-9 is rounded upwards. In this example each write statement used a different format statement. But it is perfectly fine to use the same format statement from many different write statements. In fact, this is one of the main advantages of using format statements. This feature is handy when you print tables for instance, and want each row to have the same format.
Format strings in read/write statementsInstead of specifying the format code in a separate format statement, one can give the format code in the read/write statement directly. For example, the statement
C234567890123456789012345678901234567890...
write(*,'(A,F8.3)') 'The answer is x=',x
is equivalent to
C234567890123456789012345678901234567890...
write (*,990) 'The answer is x = ', x
990 format (A, F8.3)
Sometimes text strings are given in the format statements, e.g.
the following version is also equivalent:
C234567890123456789012345678901234567890...
write (*,999) x
999 format ('The answer is x = ', F8.3)
Repeat CountsOften a format statement involves repetition, for exampleC234567890123456789012345678901234567890... 950 format (2X, I3, 2X, I3, 2X, I3, 2X, I3)There is a shorthand notation for this: C234567890123456789012345678901234567890... 950 format (4(2X, I3))
Exercises
Footnotes:
| |||||
| |
| Added to the Web: September 1, 1999. Last updated: October 2, 1999. Web page design by Dan Solarek. |
![]() http://cset.sp.utoledo.edu/cset4250/ |