You are invited to Log in or Register a free Frihost Account!

Fortran Tutorials(77)

Well i wrote this on a completely boring day those who r intrested can take the pain of reading. Please post anything bout the coding problems.thnx. Smile

Fortran 77

Terminology and Background

The name "Fortran" stands for FORmula TRANslation. The particular version I will be talking about is Fortran 77. 77 is probably the most popular version of Fortran. There are newer versions but they never became very popular because better languages such as c++ and java came out. Fortran is a compiled language so you will need a fortran compiler. A Fortran compiler is a special computer program that translates, or "com- piles", programs written in the Fortran source language into machine instructions (in binary code) that the computer hardware can read and execute.

Variable Names

Variable names consist of 1-6 characters consisting of the letters a-z and digits 0-9. The first character must be a letter. It is not case sensitive. It actually requires that variable names be all upper case but most compilers allow lowercase and then just convert it to uppercase.

Types and Declarations

The variable types are integer, real, double precision, complex, logical, character. You can declare a variable by stating the type then following it with variable names separated by commas. Exp: integer int1, int2 .Variables should only declared once. Declaring variable is optional though. If Fortran runs into an undeclared variable it uses a set of implicit rules to determine its type. It sets it as an integer if variable starts with the letters i-n and as a real for any others. An integer type consists of 4 bytes. Whereas as real and double precision are floating point numbers consisting of 4 and 8 bytes respectively. logical is just like a bool in c++. It can hold .TRUE. or .FALSE. .


Constants can be represented in numerous ways. Some examples of integers are 1,0, -100,32767, +15. Some example of real numbers are 1.0, -0.25,2.0E6, 3.333E-1. The E notation means that you multiply the first number by 10 raised to the second number. A double precision number uses a D instead of the E. There are also 2 logical constants .TRUE. and .FALSE. Character constants are contained within apostrophes. An example is 'hello world'. If you want to have an apostrophe in your string then put 2 apostrophes where you want it like this 'It''s a nice day'.


Fortran uses all the common mathematical symbols, + - * / . It uses ** for exponents. It uses standard operator precedence. An expression consists of an operand operator such as x + y.

Assignment has the form variable_name = expression. It first evaluates the right side then assigns it to the left. An example is temp = x + y.

Type Conversion

When you use different data types in the same expression either you have to tell the compiler which types to use or the compiler will judge for itself. In the case where you have a real called x and you add 1 to it the compiler would convert 1 to a real then add it. You would not have to do any type conversion. There are 5 functions available to convert data types. They are int, real, dble, ichar, char. For instance lets say you have 2 real variables x and y and want to multiply them as doubles and put them in a double precision variable called z. Here is how you would do it. z = dble(x) * dble(y).

Logical Expressions

Fortran doesn't use the normal logical expressions you would see in math class(fortran 90 does). It instead uses two character strings to represent the operators. Here is a list of all the expressions.

.LT. less than
.LE. less than or equal to
.GT. greater than
.GE. greater than or equal to
.EQ. equal to
.NE. not equal to

You can use these expression to compare variable and constants inside of if statements and other control structures.

Conditional Statement

If statements can be used to evaluate expressions and do different things based on the result. If you know how to write them in c++ you wont have any problems here. An if statement is set up like this.

if(logical expression) then
elseif(logical expression) then

The elseif and else part is optional. You only need to use them if you want to do something when the expression is false. If it is true it will do the statements after the then and skip over the rest. Here is a real example.

if(x .GE. y) then
write(*,*) 'x is positive and x >= y'
write(*,*) 'x is positive but x < y'
elseif(x .LT. 0) then
write(*.*) 'x is negative'

One thing to remember to do is to put endif at the end. That signifies the end of the if statement.

Fortran has three types of loops, do, while, and until. The do loop is similiar to a for loop in c++. It loops through the code the amount of times you specify. Here is an example.

integer i, n, sum
do 10 i=1, n
sum = sum + I
write(*,*) 'i=',I
write(*,*) 'sum=',sum
10 continue

Basically what this does is add up the numbers 1 to 20. The do loop is setup like this. First the keyword do then the label of the loop is 10. So when the code gets to a 10 continue it will jump back up to this place. Next is the starting value which was set to 1. Then after the comma is the ending value which is n. n was set to 20 a few lines back. So it is going from 1 to 20 and when it reaches 20 it breaks from the loop.

A while loop continues to loop until the logical expression is false. The syntax is like this.

while (logical expr) do

The loop will do the statements until the logical expression is false.

Until loops are very similiar. It's exactly like the while loop except the logical expression is evaluated after the statements are executed. If it is true it goes back up to begining of the until loop. Here is an example.

until(logical expr)


Many scientific computations use vectors and matrices. The data type Fortran uses for representing such objects is the array. A one-dimensional array corresponds to a vector, while a two-dimensional array corresponds to a matrix. To fully understand how this works in Fortran 77, you will have to know not only the syntax for usage, but also how these objects are stored in memory in Fortran 77. One-dimensional arrays The simplest array is the one-dimensional array, which is just a linear sequence of elements stored consecutively in memory. For example, the declaration real a(20) declares a as a real array of length 20. That is, a consists of 20 real numbers stored contiguously in memory. By convention, Fortran arrays are indexed from 1 and up. Thus the first number in the array is denoted by a(1) and the last by a(20). However, you may define an arbitrary index range for your arrays using the following syntax: real b(0:19), weird(-162:237) Here, b is exactly similar to a from the previous example, except the index runs from 0 through 19. weird is an array of length 237-(-162)+1 = 400. The type of an array element can be any of the basic data types. Examples:
integer i(10)
logical aa(0:1)
double precision x(100)

Each element of an array can be thought of as a separate variable. You reference the i'th element of array a by a(i). Here is a code segment that stores the 10 first square numbers in the array sq:
integer i, sq(10)

do 100 i = 1, 10
sq(i) = i**2
100 continue

A common bug in Fortran is that the program tries to access array elements that are out of bounds or undefined. This is the responsibility of the programmer, and the Fortran compiler will not detect any such bugs! Two-dimensional arrays Matrices are very important in linear algebra. Matrices are usually represented by two-dimensional arrays. For example, the declaration real A(3,5) defines a two-dimensional array of 3*5=15 real numbers. It is useful to think of the first index as the row index, and the second as the column index. Hence we get the graphical picture:
(1,1) (1,2) (1,3) (1,4) (1,5)
(2,1) (2,2) (2,3) (2,4) (2,5)
(3,1) (3,2) (3,3) (3,4) (3,5)

Two-dimensional arrays may also have indices in an arbitrary defined range. The general syntax for declarations is:
name (low_index1 : hi_index1, low_index2 : hi_index2)
The total size of the array is then
size = (hi_index1-low_index1+1)*(hi_index2-low_index2+1)
It is quite common in Fortran to declare arrays that are larger than the matrix we want to store. (This is because Fortran does not have dynamic storage allocation.) This is perfectly legal. Example:

real A(3,5)
integer i,j
c We will only use the upper 3 by 3 part of this array.
do 20 j = 1, 3
do 10 i = 1, 3
a(i,j) = real(i)/real(j)
10 continue
20 continue

The elements in the submatrix A(1:3,4:5) are undefined. Do not assume these elements are initialized to zero by the compiler (some compilers will do this, but not all). Storage format for 2-dimensional arrays Fortran stores higher dimensional arrays as a contiguos linear sequence of elements. It is important to know that 2-dimensional arrays are stored by column. So in the above example, array element (1,2) will follow element (3,1). Then follows the rest of the second column, thereafter the third column, and so on. Consider again the example where we only use the upper 3 by 3 submatrix of the 3 by 5 array A(3,5). The 9 interesting elements will then be stored in the first nine memory locations, while the last six are not used. This works out neatly because the leading dimension is the same for both the array and the matrix we store in the array. However, frequently the leading dimension of the array will be larger than the first dimension of the matrix. Then the matrix will not be stored contiguously in memory, even if the array is contiguous. For example, suppose the declaration was A(5,3) instead. Then there would be two "unused" memory cells between the end of one column and the beginning of the next column (again we are assuming the matrix is 3 by 3). This may seem complicated, but actually it is quite simple when you get used to it. If you are in doubt, it can be useful to look at how the address of an array element is computed. Each array will have some memory address assigned to the beginning of the array, that is element (1,1). The address of element (i,j) is then given by
addr[A(i,j)] = addr[A(1,1)] + (j-1)*lda + (i-1)
where lda is the leading (i.e. column) dimension of A. Note that lda is in general different from the actual matrix dimension. Many Fortran errors are caused by this, so it is very important you understand the distinction! Multi-dimensional arrays Fortran 77 allows arrays of up to seven dimensions. The syntax and storage format are analogous to the two-dimensional case, so we will not spend time on this. The dimension statement There is an alternate way to declare arrays in Fortran 77.

The statements

real A, x
dimension x(50)
dimension A(10,20)
are equivalent to
real A(10,20), x(50)

This dimension statement is considered old-fashioned style today.


If an application requires a function that is not included in the intrinsic functions, Fortran allows us to write our own functions. The general form for a statement function is:

function name (argument list) = expression

The following rules apply to the use of statement functions:
1. The statement function is defined at the beginning of the program, preceding any executable statements.
2. The definition of the statement function contains the name of the function, followed by its arguments in parentheses, on the left-hand side of an equal sign; the expression for computing the function value is on the right side.
3. The function name should be included in a type statement; otherwise, implicit typing will determine the function type (real or integer).

A function subprogram, which is a program itself, is separate from the main program. It begins with a nonexecutable statement that identifies the function with a name and an argument list. The general form for a function statement is:

FUNCTION name (argument list)

Because the function is separate from the main program, it must end with an END statement, and must also have a RETURN statement, which returns control to the statement in the main program that referenced the function. Let's consider the following program:


c This is a program to average and assign a grade.

Real Test1, Test2, Test3, Ave,Avg

Character * 1 grade

Print*, 'Input the grades for Test 1, Test 2, and Test3.'


Avg = Ave(Test1,Test2,Test3)

Write (*,100) Avg

100 Format (1X, 'The average is ',F4.1)

Write (*,200)Grade(Avg)

200 Format(1X,'The corresponding grade is ',A1)



Real Function Ave (X, Y, Z)

c This function will calculate the average of three test


Real X, Y, Z

Ave = (X + Y + Z) / 3.0



Character Function Grade(Av)

c This function will assign a letter grade to the average.

If ( Av .GE. 90.0) then

Grade = 'A'

Elseif (Av . GE. 80.0) then

Grade = 'B'

Elseif (Av. GE. 70.0) then

Grade = 'C'

Elseif (Av. GE. 65.0) then

Grade = 'D'


Grade = 'F'




The following rules must be observed in writing function subprograms.
The function arguments referenced in the main program are the actual arguments. They must match in type, number, and order the dummy arguments used in the function statement. If one of the arguments is an array, its dimensions must be specified in the main program and the function subprogram. The value to be returned to the main program is stored in the function name using an assignment statement. The function subprogram must have a return command in order for control to be returned to the main program. A function can reference other functions but it cannot reference itself. A function subprogram is usually placed immediately after the main program. The name of the function should appear in a type statement in the main program as well as in the function statement itself.

File I/O

So far we have assumed that the input/output has been to the standard input or the standard output. It is also possible to read or write from files which are stored on some external storage device, typically a disk (hard disk, floppy) or a tape. In Fortran each file is associated with a unit number, an integer between 1 and 99. Some unit numbers are reserved: 5 is standard input, 6 is standard output. Opening and closing a file Before you can use a file you have to open it. The command is open (list-of-specifiers) where the most common specifiers are:
[UNIT=] u
ERR= err
FILE= fname
FORM= frm
RECL= rl

The unit number u is a number in the range 9-99 that denotes this file (the programmer may chose any number but he/she has to make sure it is unique). ios is the I/O status identifier and should be an integer variable. Upon return, ios is zero if the stement was successful and returns a non-zero value otherwise. err is a label which the program will jump to if there is an error. fname is a character string denoting the file name. sta is a character string that has to be either NEW, OLD or SCRATCH. It shows the prior status of the file. A scrath file is a file that is created and deleted when the file is closed (or the program ends). acc must be either SEQUENTIAL or DIRECT. The default is SEQUENTIAL. frm must be either FORMATTED or UNFORMATTED. The default is UNFORMATTED. rl specifies the length of each record in a direct-acccess file. For more details on these specifiers, see a good Fortran 77 book. After a file has been opened, you can access it by read and write statements. When you are done with the file, it should be closed by the statement

close ([UNIT=]u[,IOSTAT=ios,ERR=err,STATUS=sta])

where, as usual, the parameters in brackets are optional. Read and write revisited The only necessary change from our previous simplified read/write statements, is that the unit number must be specified. But frequently one wants to add more specifiers. Here is how:

read ([UNIT=]u, [FMT=]fmt, IOSTAT=ios, ERR=err, END=s)

write([UNIT=]u, [FMT=]fmt, IOSTAT=ios, ERR=err, END=s)
where most of the specifiers have been described above. The END=s specifier defines which statement label the program jumps to if it reaches end-of-file.

You are given a data file with xyz coordinates for a bunch of points. The number of points is given on the first line. The file name of the data file is points.dat. The format for each coordinate is known to be F10.4. Here is a short program that reads the data into 3 arrays x,y,z:
program inpdat
c This program reads n points from a data file and stores them in
c 3 arrays x, y, z.
integer nmax, u
parameter (nmax=1000, u=20)
real x(nmax), y(nmax), z(nmax)

c Open the data file
open (u, FILE='points.dat', STATUS='OLD')

c Read the number of points
read(u,*) n
if (n.GT.nmax) then
write(*,*) 'Error: n = ', n, 'is larger than nmax =', nmax
goto 9999

c Loop over the data points
do 10 i= 1, n
read(u,100) x(i), y(i), z(i)
10 enddo
100 format (3(F10.4))

c Close the file
close (u)

c Now we should process the data somehow...
c (missing part)

9999 stop

First off fortran is very anal about formating. You can't start a line in the first column unless it is a comment beginning with c. You have to tab over for each line of code. Knowing this you should be able to compile your program without all the headaches.
This help file covers in detail the basics of using Fortran on UNIX; this is an expanded version of the "help f77 intro" and "help f77 options". To learn about UNIX, read "Communicating with UNIX" and "Edit: a Tutorial" (see "help f77 printed_doc"). This tutorial assumes that you know (or are learning) the Fortran language. If you already know the basics, see "help f77 intro" and "help f77 options" which cover more information but with less explanation. An Example:
Here is how to write, compile, and execute a simple Fortran pro- gram. Use the editor to create a file called 'hello.f' that con- tains the three lines:
print 100
100 format('hello, world.')

To start statements on or after column 7, you can either use spaces or a tab character (control-I). After exiting the editor, when you have the shell prompt again, type the command:
f77 hello.f
This invokes 'f77', the UNIX Fortran compiler. If you entered the file correctly, the system will respond with:
Loading a.out ...

If there are other messages, check that you entered the file 'hello.f' correctly. (Also, on some systems, the last line, "Loading a.out ..." may not appear). Two new files will have been created in your directory: 'hello.o', and 'a.out'. Type:
to list your files and verify that 'hello.o' and 'a.out' have been created. To run the program, type:
Your program will respond by printing the message "hello, world."
The files you create containing Fortran statements are known as "source files" since they provide source for the compiler to act upon. The file 'hello.f' was the source file in the example above. Fortran source files for f77 must have names that end in the two characters '.f'.

The command "f77 hello.f" in the example above invoked the f77 compiler on the source file. If the compiler detects any errors in the source file it will print messages to that effect. If it finds no errors (as in this case), the compiler creates an "ob- ject file", 'hello.o'. The object file contains machine readable instructions corresponding to the Fortran instructions in the source file. It is not human readable. (You could see this by typing "cat hello.o", but it is generally a bad idea to use "cat" to look at an object file as it sometimes "hangs" the terminal).

The compiler automatically invokes another special program called the "loader". The loader combines together object files for the main program, any subroutines or functions it might call, and various run-time support routines to form what is called the "ex- ecutable file". The executable file is created with the name 'a.out'. As you discovered above, one executes an executable file just as one executes any other UNIX command: just type its name.

The 'hello' in the file name 'hello.f' is sometimes called the root part of the file name. The '.f' is called the extension. Object files created by f77 have names with the same root part as the source file name but with a '.o' extension. The default name for the executable file is 'a.out'.

A More General Example:

A Fortran source file may contain subroutines along with the main program. Alternatively, subroutines may be put into files separate from the main program. This is useful when a subroutine might be called by any one of several different programs - it al- lows you to maintain only one copy, saving computer time and mo- ney as you need to recompile only those subprograms that change.

Suppose that your main program is in the file 'main.f' and that it calls subroutines in the files 'sub1.f', 'sub2.f', and 'sub3.f'. To compile and load these you would type:

f77 main.f sub1.f sub2.f sub3.f

This command would compile each of the four source files; that is, for each one it would report any errors or create an object file if there were no errors. Next, the UNIX loader would be in- voked by the f77 command to create a single executable file named 'a.out'. Execute this file by typing its name.

If you change a source file, you must recompile it and reload everything to create a new executable file that incorporates the changes. On the other hand, if a source file has not been changed since the last time you compiled it, you can keep the corresponding object file and use it over and over again. To do so, just replace the name of the source file in the f77 command with the name of the object file. In this example, suppose that you have just edited the files 'sub1.f' and 'sub2.f' but 'main.f' and 'sub3.f' are unchanged since the previous compilation. Then you need to recompile 'sub1.f' and 'sub2.f' but not the other two source files. To recompile and reload you would type:

f77 main.o sub1.f sub2.f sub3.o

This is preferable to the previous command where all four files mentioned were source files, since it avoids unnecessary recompi- lation of 'main.f' and 'sub3.f'.


There are many options for the f77 command, for a complete list, see "man 1 f77", the f77 manual page.
To compile only and not load, use the -c option. For example type,

f77 -c prog.f

to create 'prog.o' but not 'a.out'. Later, you could then create the a.out directly from the .o file:

f77 prog.o

The -C options directs the compiler to generate code to check that subscript references are legal:

f77 -C prog.f

The -g option directs the compiler and loader to save enough in- formation so that the source level debugger, dbx, can be used if the program does not work:

f77 -g prog.f

While the -C option is only specified to the compiler, the -g op- tion must be specified to both the compiler and loader; thus the equivalent commands for separately compiling and loading with -g are:

f77 -g -c prog.f
f77 -g prog.o

The -o option directs the loader to put the executable file in a file other than 'a.out', e.g. to have the executable file put in 'myprog', type:

f77 prog.f -o myprog

The -o option and file name may appear anywhere in the f77 com- mand. The -l option specifies system libraries; e.g. to specify that you need subroutines from the f77 graphics interface li- brary, type:

f77 prog.f -lf77plot

Note that the name of the library, 'f77plot', follows immediately after the -l without a space. This is in contrast to the -o op- tion, which has a space between the -o and the file name. Also, libraries must be listed in the f77 command after the source and object file names.
Many options may be requested simultaneously, e.g.:

f77 -C -g prog.f sub1.f sub2.o -lf77plot -o myprog


When developing a program, it's easiest to keep each subroutine in a separate file. Because you'll be modifying each one fre- quently, but probably not all at the same time, this strategy holds down unnecessary recompilations. Name each file after the subroutine it contains (or the most important subroutine if it contains several).
If you have a file containing several subprograms, you can split each into a separate file by using the "fsplit" command:

fsplit prog.f

See "man 1 fsplit" and "help f77 style" for more details.
To conserve disk space, delete files when finished with them. Keep object and executable files around if you'll be using them for a while - compilation costs money and imposes a heavy load on the system and unnecessary recompilation should be avoided when- ever possible. However, delete any object files or executable files that are not likely to be needed again.
For additional information on f77, refer to "help f77".

----- Cyb0t
[edit] Post reopened.
well friend its sorted out. noobie4life our moderator has again opened the post. firstly he called me a liar. now the matter seemed 2 be solved. you may post in your comments. thnx 2 all. Very Happy

Related topics
photoshop tutorials gonzo likes
Free Tutorials
Some Photoshop tutorials
[PHOTOSHOP] video tutorials..
Awesome Flash Tutorials (
10 photoshop effect tutorials
Flash MX 2004 Tutorials
The Design Dump - Articles and Tutorials - Forum
C# tutorials
Programming Help & Support Guidelines
Photoshop Tutorials
HTML Tutorials
Programming links, info, and tutorials
Reply to topic    Frihost Forum Index -> Miscellaneous -> Tutorials

© 2005-2011 Frihost, forums powered by phpBB.