Fortran - University of jb/math190/ IN FORTRAN There are two main types of Fortran in common use: Fortran 77 and Fortran 90. The latter is an extension of the former, so that a Fortran 77
Post on 05-Mar-2018
PROGRAMMING IN FORTRAN
There are two main types of Fortran in common use: Fortran 77 andFortran 90. The latter is an extension of the former, so that a Fortran 77program will run on Fortran 90. We will be using the Gnu version of For-tran 77.
These notes are rather cryptic, but they do contain good examples.
1. The Environment
In order to run Fortran in the math lab, first click on the icon labelledFortran. This will give you a command prompt in your H: drive.
You will need to use an editor to create your program. The standardDOS editor works well. Type edit filename.f to start editing a file with thiseditor. The name of a Fortran program must end in .f or .for. Fortran iscase-insensitive, so capital letters are not distinguished from lower case ones.
Surely the most peculiar feature of Fortran 77 is its line structure, whichis a carryover from the days of punch cards. A punch card had 80 columns,and so does a line of Fortran code. A c in column 1 indicates a comment.Columns 25 are reserved for line numbers (usually blank). Column 6 isused only to indicate a continuation of a line too long to fit on one card.Columns 772 contain the instructions of the program. Columns 7380 arefor data only, and are ignored by the compiler. (This form is no longerrequired in Fortran 90, though it is sometimes used.)
Let us go through the steps of running a short program. First we edit inthe program, say hello.f.
program helloprint *, Hello, world!end
Exit the editor, saving the file. You can then compile the program by typingg77 hello.f. Compiling the program makes an executable program whichis by default called a.exe. The executable program is executed by typingjust the letter a. (In UNIX, the default name is a.out, and the executioncommand is a.out*.)
If you want to give the executable file a different name, compile the pro-gram with the form g77 hello.f -o greeting to make an executable file calledgreeting.exe, which is run by typing greeting. The executable file can becalled anything that is not the name of another file.
Date: September 1, 2005.
2 PROGRAMMING IN FORTRAN
Control-C interrupts the execution of a program, which is sometimesnecessary. You can print your fortran program using Notepad; the standardprint option doesnt work in our lab.
2. Variables and Operations
We now look at some Fortran program statements and discuss how vari-ables and functions are represented.
Comments are indicated by a c in column 1. Alternately, an excla-mation point (!) is used to indicate a comment; it may occur anywhere in aline, indicating that the rest of the line is a comment.
Types of variables. Fortran has integer, real, double precision andcomplex variables. The default type of a variable starting with i through nis integer, and otherwise the default type is real. It is normal programmingpractice to declare the type of all variables, with exceptions being made forshort programs and integer loop counters.
The types of variables are declared as in the following examples.
real a,b,cinteger max, counter
This makes a, b, c real variables and max, counter integer variables. Analternate form includes two colons:
real :: a,b,cinteger :: max, counter
Type declarations can also be used to dimension an array. The commands
real vec(20)integer mat(0:10, 0:10)
make a real vector vec(i) with subscripts 1 to 20 (so 1 is the default lowerbound), and an integer array mat(i, j) with subscripts 0 to 10. Likewise,
double precision sam(-5:5)
makes a double precision vector sam(i) with subscripts -5 to 5.The implicit statement makes all variables starting with given letters of
the same type. For example, the default types are equivalent to
implicit integer (i-n)implicit real (a-h,o-z)
In particular, the command implicit integer (a-z) is useful for mathematicalprograms involving only integer variables. Otherwise, the implicit commandis best avoided.
Assignment The equal sign = gives the variable on the left hand sidethe value of the number or expression on the right hand side, as in x = 1.
READ The simple (unformatted) read statement allows the user to typein values for the variables. Sample:
read *, a,b,c
PROGRAMMING IN FORTRAN 3
You would then enter the values of a, b, c separated by returns. The asteriskin both read and print statements means to use the default format for inputor output.
To input a vector, you can use the implicit loop form:read *, (dog(i),i=1,5)
PRINT The PRINT statement, which prints the variables or expressionsfollowing it to the screen, has a similar form:
print *, To be or not to be?print *, x = , xprint *, a,b,cprint *, (dog(i),i=1,5)
Note that either single or double quotes may be used for strings. Later wewill see more complicated forms of the READ and WRITE statements.
STOP and END The stop statement stops execution of the program.The end marks the end of the main program or a subroutine.
Mathematical operations. Fortran has the following standard opera-tions. The trig functions use radians.
(1) x + y for addition.(2) x y for subtraction.(3) x y for multiplication.(4) x/y for division.(5) x y for exponentiation.(6) sin(x) for sine.(7) cos(x) for cosine.(8) tan(x) for tangent.(9) atan(x) for arctangent.
(10) sqrt(x) for square root.(11) abs(x) for absolute value.(12) exp(x) for ex.(13) log(x) for the natural logarithm (base e).(14) mod(x, n) for x mod n.
Warning: If m and n are integers, then m/n will be truncated to its integerpart. Thus 1/6 will be evaluated as 0, and 7/6 becomes 1. This is a usefulfeature in advanced programming, but is also a common source of errors.For constants, it can be avoided by using decimal points, e.g., 1./6.. Forvariables, it can be avoided by using another variable name, e.g., realm = m,assuming that there was some reason not to declare m to be real in the firstplace.
Array declarations in Fortran go at the beginning of the program, beforeany executable statement. Vectors and arrays can be declared using eitherdimension or a type declaration, as in these examples.
4 PROGRAMMING IN FORTRAN
dimension ke(10)real dog(10,10)
The second form, indicating the variable type, is preferred. Note that in theabove example the vector ke(j) would be of integer type.
Because vectors and arrays are declared at the beginning, they must begiven a fixed size, e.g., ke(10) rather than ke(n). There is a way aroundthis, but it is a little complicated.
Finally, in Fortran the default lower limit is 1 (rather than 0). A colon isused to indicate a range of subscripts, as in:
real cow(0:100, 0:100)integer bat(-5:5)
4. DO Loops
A loop begins with a do statement, and ends with either end do or aprescribed statement number (replacing NEXT). The following examplesillustrate the usage.
sum=0do i=1,10sum=sum + i**2end doprint *, sum
The same program could be written as follows, using line numbers.sum=0do 5 i=1,10sum=sum + i**2
5 continueprint *, sum
As a matter of form, loops of the second form should end with a continuestatement, a non-executed statement which identifies the end of the loop.
If you only wanted say the even terms, then you could replace the secondline by
do 5 i=2,10,2where the last number indicates the step size. The step size can be positiveor negative.
You can use variables for the limits on the loop counter, as indo 5 i=min, max
Finally, loops can be nested. Different loops can end on the same continuestatement.
do i=1,10do j=1,10a(i,j)=i+jend doend do
PROGRAMMING IN FORTRAN 5
ordo 5 i=1,10do 5 j=1,10a(i,j)=i+j
5. Logical expressions
A logical expression is a relation between variables which can have a valueof TRUE or FALSE. These are used with IF...THEN and DO...WHILE todecide whether to execute certain steps of the program. In Fortran, logicalexpressions and operators are indicated by periods on both sides. The basicrelations and their meanings are:
.lt. means less than
.gt. means greater than
.le. means less than or equal to
.ge. means greater than or equal to
.eq. means equals
.ne. means not equal to
.or. means or
.and. means and
.not. means notWe will use some of these expressions in the next section.
6. DO WHILE....
DO WHILE.... loops in Fortran are another way to perform iterations,with the logical condition replacing the counter. The form is illustrated inthe following two examples, which give a rough way to approximate
x=1do while (x**2.lt.10)x=x+.01end do
c x**2 will be greater than 10or
x=1do 5 while (x**2.lt.10)x=x+.01
7. User-Defined Functions
Fortran has two ways in which you can define functions. If the functionhas a simple expression, then you can just insert a line at the top of theprogram, before any executable statement. For more complicated functions,you should use a function subroutine. The function subroutine is a separate
6 PROGRAMMING IN FORTRAN
section of the program, but is normally edited in the same window as themain program. In the following example, the function f(x) is defined theformer way, and g(x) the latter.
program tatef(x)=x**2print *, What is a?read *,aprint *, f(a) = , f(a)print *, g(a) = , g(a)end
The first end statement ends the main program, the second ends the func-tion. With most Fortran 77 compilers (but not the one on uhunix2), thefirst end could be end program or end program tate, while the second couldbe end function or end function g(x).
Functions can use local or global variables, but the global variables mustbe indicated as common.
program powerscommon nprint *, What is x?read *, xprint *, What is n?read *, nprint *, x**n = , h(x)end
function h(x)common nh=x**nreturnend
Of course, a simpler way would have been to use a function of two variables,h(x, n). In passing or sharing vectors or arrays, just use the array name,e.g., common vec.
This allows you to perform certain steps only when a logical expressionis TRUE. There are two forms of the IF statement, the one-line form andthe multiline form. A one-line IF statement does not contain the keyword
PROGRAMMING IN FORTRAN 7
THEN, while the multiline form does. ELSE is an allowable option. Thefollowing examples illustrate the usage.
Example 1:read *, xif (sin(x).lt.0) print *, Try again!
Example 2:read *, xif (sin(x).ge.0) then
y=sqrt(sin(x))print *, sqrt(sin x) = , y
end ifExample 3:
read *, xif (sin(x).ge.0) then
y=sqrt(sin(x))print *, sqrt(sin x) = , y
elseprint *, Try again!
9. Labels and GOTO
The GOTO (line number) command allows you to skip around in theprogram. They should be used sparingly, but can be useful, especially inconjunction with IF statement. For example, the command
if (z.gt.5) goto 200skips to the line labeled 200 if z > 5.
Subroutines (discussed later) are often a better option than GOTO.
10. WRITE and FORMAT Statements
We use the write command with a format statement in Fortran to controlthe output. While these can get complicated, the most commonly usedoptions are simple and easy to use. A typical write statement is
write (*,200) x,y,zThe first position inside the parentheses tells the computer where to write;the * indicates the terminal. If you wanted to write to a file, you would usethe number assigned to that file (see below). The second position gives theline number of the format statement to be used. In this case, the formatstatement might be something like
200 format(3f10.4)This would indicate three numbers with at most 10 places (counting the signand the decimal point), with 4 places after the decimal. The x, y and z areof course the variables to be printed.
8 PROGRAMMING IN FORTRAN
The most common field descriptors used in format statements are thefollowing.
(1) iw denotes an integer of length at most w, e.g., i4 for an inte-ger between -999 and 9999. 20i4 denotes the places for 20 suchintegers.
(2) fw.d denotes a real number in decimal form of length at most w withd places to the right of the decimal, e.g., f9.4 for -132.4552.
(3) ew.d denotes a real number in exponential form of length at most wwith d places to the right of the decimal, e.g., e9.4 for 0.1234E+2.Note that w d + 5 is required.
(4) Dw.d denotes a double precision number in exponential form oflength at most w with d places to the right of the decimal.
(5) wx denotes that w spaces are to be skipped (left blank), e.g., 4x.Strings (in quotes) may be placed between the field descriptors, separatedby commas.
Here are some examples.write (*,20) n,x,y
20 format(2x,i4,2f10.4)write (*,30) f(x)
30 format(The function value is ,f12.5)To print an integer matrix, we might use the following.
do 50 i=1,nwrite (*,40) (m(i,j),j=1,n)
40 format(20i4)50 continue
In order to write to a file, you must first open the file and assign it a unitnumber. For example, the following command opens the file dog.out andassigns it the unit number 7.
open(unit=7,file=dog.out)To write to the file, we would refer to its number in the first entry of thewrite command:
write (7,10) f(x)10 format(2x,y = ,f12.5)
The file may be closed with the command close (unitnumber), e.g., close(7).
Subroutines in Fortran work just like independent subprograms, with theproperties already noted under user-defined functions: it is not necessaryto declare them, they must contain the line return before end, and usingcommon for global variables.
The following example illustrates a simple subroutine.program calculator
PROGRAMMING IN FORTRAN 9
print *, What are x and y?read *, x, ycall add(x,y,z)print *, The sum is , zend
The return command may also be used to return to the main program fromsomewhere in the middle of the subroutine.
Assignment 8. Write a fortran program to sort a list of numbers usinga bubble sort.
Assignment 9. Write a program that will compute ba f(x) dx for a con-
tinuous function f(x), with accuracy 104. Format the answer accordingly.