56
An Introduction to An Introduction to Fortran Fortran Lecture 1 Lecture 1

An Introduction to Fortran Lecture 1

  • Upload
    ucc-gh

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

An Introduction to An Introduction to FortranFortranLecture 1 Lecture 1

IntroductionIntroduction• FortranFortran ( (ForFormula mula ttranranslator) is a scientific slator) is a scientific programming language which began life in programming language which began life in the late 1950s. The language was designed the late 1950s. The language was designed to help scientists and engineers perform to help scientists and engineers perform complex computational tasks. Basically it complex computational tasks. Basically it was a way of getting a computer to operate was a way of getting a computer to operate on mathematical formulae and equations in on mathematical formulae and equations in various fields, like meteorology, and various fields, like meteorology, and produce ‘answers’ to practical problems.produce ‘answers’ to practical problems.

• It has evolved over the ensuing decades to It has evolved over the ensuing decades to become the leading scientific language. become the leading scientific language. Much of the world’s library of scientific Much of the world’s library of scientific programs is in Fortran although this will programs is in Fortran although this will change with the increasing popularity of change with the increasing popularity of C, which is suitable for any programming C, which is suitable for any programming task, not just for science. task, not just for science.

A simple exampleA simple example

•We will consider a simple We will consider a simple Fortran program to illustrate Fortran program to illustrate the basic concepts involved.the basic concepts involved.

Basic structure of the Basic structure of the programprogram •Here is a very simple Fortran Here is a very simple Fortran program. It consists of a set of program. It consists of a set of statementsstatements that start with the that start with the programprogram statement and finish with statement and finish with the the endend statement. This set of statement. This set of statements, or the Fortran statements, or the Fortran source source codecode, is saved in a , is saved in a text filetext file e.g. e.g. first.ffirst.f . To avoid compilation . To avoid compilation ‘hassles’ it is a good idea to use ‘hassles’ it is a good idea to use the extension the extension .f.f for your source for your source code files. Also, save as ‘text-code files. Also, save as ‘text-only’, not as a Word document.only’, not as a Word document.

111---------------------------------------------------------777123456789012---------------------------------------------------------012 program firstcc * Declaration section implicit none ! Need to declare all variables real x,ycc * Executable section write(*,*)'My first program' write(*,*)'Enter a number: ' read(*,*)x y= x**2 +4*x -12c * Free format outputc In Mardling, print is used instead of writec i.e. write(*,*) == print *, write(*,*)'x=',x,' y= ',yc * User-specified formatted output write(*,10)x,y10 format('x=',F8.4,2X,'y=',F9.5) end

• Each statement begins in Each statement begins in column 7column 7 and ends no and ends no greater than greater than column 72column 72 (the ruler just before the (the ruler just before the example is to make this clear – this ruler does example is to make this clear – this ruler does notnot appear in the source code file). There are a appear in the source code file). There are a couple of exceptions to this.couple of exceptions to this.

• Firstly, if you have a long statement you place Firstly, if you have a long statement you place a character in a character in column 6column 6 of the next line (often a of the next line (often a ++ or or **) and continue the rest of the statement.) and continue the rest of the statement.

• Secondly, you may need to use Secondly, you may need to use statement numbersstatement numbers associated with the associated with the gotogoto and and formatformat statements. statements. These numbers may go anywhere in These numbers may go anywhere in columns 1-5columns 1-5. . They are actually labels of your choice and have They are actually labels of your choice and have not connection with the line number in the source not connection with the line number in the source code file. code file.

• Thirdly, you may put Thirdly, you may put commentscomments anywhere in your anywhere in your program. These have the character program. These have the character cc in column 1 in column 1 followed by any text. You may also use an followed by any text. You may also use an exclamation mark (exclamation mark (!!) after a statement – an in-) after a statement – an in-line comment.line comment.

• The program comprises two sections: The program comprises two sections: declarationdeclaration and and executableexecutable..

• The The declarationdeclaration section consists of section consists of statements that statements that definedefine variables and variables and parameters used in your program. These parameters used in your program. These immediately follow the immediately follow the programprogram statement (this just has the name of statement (this just has the name of your program) and come before all your program) and come before all executable statements.executable statements.

• The The executableexecutable section consists of section consists of statements that actually statements that actually dodo somethingsomething

e.g. the e.g. the readread statement reads in data statement reads in data from the keyboard or a data file. The from the keyboard or a data file. The executable statement: executable statement: y= x**2 +4*x -12y= x**2 +4*x -12 computes the variable y from the value computes the variable y from the value of x.of x.

• Finally, we have the Finally, we have the endend statement. statement.

• We may also regard the executable We may also regard the executable section as comprising three generic section as comprising three generic blocks: blocks: inputinput, , processingprocessing and and outputoutput..

• The The inputinput block is the block is the read read statement – this allows us to input statement – this allows us to input data into the program.data into the program.

• The statement: The statement: y= x**2 +4*x -12y= x**2 +4*x -12 is is the the processingprocessing block. Here we perform block. Here we perform operations on (process) x to get y.operations on (process) x to get y.

• Finally, the Finally, the writewrite statements statements constitute the constitute the outputoutput block – we block – we need to view our results, in this need to view our results, in this case the value of y.case the value of y.

What does this example program do?What does this example program do? • Well, it prints a couple of informative messages on Well, it prints a couple of informative messages on the computer screen (the computer screen (writewrite) and waits for you to ) and waits for you to enter a real (floating point) number (enter a real (floating point) number (readread) e.g. ) e.g. 2.5 (note that if you enter 2 it is interpreted as 2.5 (note that if you enter 2 it is interpreted as 2.0). The statement: 2.0). The statement: read(*,*) x read(*,*) x means read from means read from the keyboard and the number will be interpreted the keyboard and the number will be interpreted from its declaration i.e. real. This number is from its declaration i.e. real. This number is assignedassigned to the variable x to the variable x

• Then the statement: Then the statement: y= x**2 +4*x -12y= x**2 +4*x -12 computes the computes the variable y – in this case, y would be 4.25. variable y – in this case, y would be 4.25. Finally, the values of x and y are written on the Finally, the values of x and y are written on the screen (screen (writewrite). ).

• For illustration, this is done in For illustration, this is done in free formatfree format and then and then by a by a user-defineduser-defined format. The first approach involving format. The first approach involving write(*,*) is convenient - this means write to the write(*,*) is convenient - this means write to the screen in a default way - while the second approach screen in a default way - while the second approach using the two statements using the two statements write(*,10)x,ywrite(*,10)x,y and and 10 10 formatformat allows greater control over the written allows greater control over the written output. Note that the connecting statement number output. Note that the connecting statement number or label (or label (1010) for the second approach.) for the second approach.

Compiling the programCompiling the program• To compile this program we need a To compile this program we need a Fortran Fortran

compilercompiler. This is a piece of software . This is a piece of software which reads the Fortran source code file which reads the Fortran source code file (first.f) and turns it into an (first.f) and turns it into an executable program (software) which runs executable program (software) which runs on your computer. The executable program on your computer. The executable program is often called an is often called an executableexecutable or a or a binarybinary. . There is a public domain Fortran 77 There is a public domain Fortran 77 compiler called compiler called g77g77. Traditionally, the . Traditionally, the compiler is called compiler is called f77f77 but on some but on some machines (especially the Suns) there is machines (especially the Suns) there is a proprietary Fortran compiler (f77) as a proprietary Fortran compiler (f77) as well as the ‘free’ one (g77). In well as the ‘free’ one (g77). In general, f77 may have some different general, f77 may have some different options to g77. Note: On the Linux PCs options to g77. Note: On the Linux PCs and Windows XP, g77 is usually aliased and Windows XP, g77 is usually aliased to f77 so the names actually refer to to f77 so the names actually refer to the same compiler. the same compiler.

• Hence to compile our example on Hence to compile our example on any computer system:any computer system:g77 –o first first.fg77 –o first first.f

• The option –o allows us to specify The option –o allows us to specify the output name of the executable. the output name of the executable. By default i.e. without the –o By default i.e. without the –o option, it is called option, it is called a.outa.out (or (or a.exe on Windows PCs).a.exe on Windows PCs).

• The compiler produces one or more binary The compiler produces one or more binary objectsobjects with the extension with the extension .o.o corresponding to your corresponding to your source code In our case, there is one called source code In our case, there is one called first.o but it is not retained unless the –c first.o but it is not retained unless the –c option of the g77 compiler is used. option of the g77 compiler is used. When the When the program is compiled some pre-packaged routines program is compiled some pre-packaged routines which are stored as which are stored as librarieslibraries are are linkedlinked with the with the compiler binary output (objects) from your compiler binary output (objects) from your source code to create an source code to create an executableexecutable..

• To show the creation of the object, the above To show the creation of the object, the above compilation could be performed in two steps:compilation could be performed in two steps:g77 –c first.fg77 –c first.f (this creates the binary object (this creates the binary object first.o)first.o)g77 –o first first.og77 –o first first.o(this links the object to (this links the object to the system libraries to create the executable)the system libraries to create the executable)

• An extension of this approach is used An extension of this approach is used in in makefilesmakefiles involving the involving the makemake command. command.

• Some simple examples of these are Some simple examples of these are intrinsicintrinsic (inbuilt) functions e.g. (inbuilt) functions e.g. sin(x)sin(x). Depending on the complexity of . Depending on the complexity of your program, a host of libraries may your program, a host of libraries may be required. For instance, to be required. For instance, to incorporate NCAR Graphics into your incorporate NCAR Graphics into your Fortran program (like conmap7) the Fortran program (like conmap7) the NCAR Graphics libraries need to be NCAR Graphics libraries need to be available to the compiler so that the available to the compiler so that the graphics routines are linked with your graphics routines are linked with your code.code.

•The executable will only run on The executable will only run on your your currentcurrent operating system operating system e.g. an executable compiled on e.g. an executable compiled on a Linux PC will a Linux PC will notnot run on a run on a Windows XP PC or an iMac. Windows XP PC or an iMac. However, in principle you can However, in principle you can transfertransfer the source code the source code (first.f) to other machines and (first.f) to other machines and compile it there – and it compile it there – and it should work! This is the real should work! This is the real power of programming.power of programming.

Running the programRunning the program • To run the executable, just type in the To run the executable, just type in the name: first . On the screen you will see name: first . On the screen you will see the messages:the messages:

My first programMy first program Enter a number:Enter a number: followed by a prompt. Enter a number followed by a prompt. Enter a number from the keyboard e.g. 2.5. Then some more from the keyboard e.g. 2.5. Then some more output text is written to the screen:output text is written to the screen:

x= 2.5 y= 4.25 x= 2.5 y= 4.25 x= 2.5000 y= 4.25000x= 2.5000 y= 4.25000• The above is the screen output on a PC The above is the screen output on a PC running Windows 2000. The program was running Windows 2000. The program was compiled with g77 under the Cygwin Linux compiled with g77 under the Cygwin Linux emulation software. emulation software.

• The first line uses The first line uses free formatfree format and is and is chosen by the compiler. The second line chosen by the compiler. The second line is specified by the user in the is specified by the user in the formatformat statement. Firstly, we write the text: x= statement. Firstly, we write the text: x= on the screen. The value of the variable on the screen. The value of the variable x is written in a field of 8 columns with x is written in a field of 8 columns with 4 decimal places (4 decimal places (F8.4F8.4), followed by a ), followed by a white space of 2 columns (white space of 2 columns (2X2X). Finally, ). Finally, we write the text: y= and the value of we write the text: y= and the value of the variable y in a field of 9 columns the variable y in a field of 9 columns with 5 decimal places (with 5 decimal places (F9.5F9.5). In both ). In both fields fields FF denotes floating point (real) denotes floating point (real) numbers corresponding to the declaration numbers corresponding to the declaration of x and y as real variables. of x and y as real variables.

Some remarks on the Some remarks on the exampleexample

• Although the above program is quite simple Although the above program is quite simple it nevertheless illustrates the basics of it nevertheless illustrates the basics of Fortran programming (in fact, any Fortran programming (in fact, any programming language). Extensions of the programming language). Extensions of the example might include reading from a data example might include reading from a data file, doing some processing e.g. computing file, doing some processing e.g. computing the mean or a Fourier transform, and the mean or a Fourier transform, and outputting to another data file. outputting to another data file.

• The input and output files may have a The input and output files may have a special format, perhaps even special format, perhaps even binarybinary i.e. i.e. not viewable as text. Much of our weather not viewable as text. Much of our weather data is in binary formats – usually they data is in binary formats – usually they result in smaller files and are read more result in smaller files and are read more quickly than text files if there is a lot quickly than text files if there is a lot of data.of data.

Fortran 90 (1)Fortran 90 (1)• Fortran 90 is designed for high Fortran 90 is designed for high performance scientific computingperformance scientific computing

• It can treat arrays (vectors and It can treat arrays (vectors and matrices) by their symbolic formmatrices) by their symbolic forme.g. Y = A * Be.g. Y = A * Brather than by a set of do loops to rather than by a set of do loops to operate on the individual elementsoperate on the individual elementse.g. y(i) = a(i,j) * b(j) e.g. y(i) = a(i,j) * b(j)

• A lot of concepts from C are A lot of concepts from C are implementedimplemented

• It is free format – you don’t need It is free format – you don’t need to start in column 7!to start in column 7!

Fortran 90 (2)Fortran 90 (2)• ExampleExample

! EXAMPLE 1! EXAMPLE 1!!real,dimension(10)::a=(/(i,i=1,10)/)real,dimension(10)::a=(/(i,i=1,10)/)real,dimension(10)::b,creal,dimension(10)::b,cinteger iinteger ib=a +1.b=a +1. ! Vector addition! Vector additionc=a*sin(b) c=a*sin(b) ! Vector operation! Vector operationprint *, cprint *, c ! Same as write(*,*)c ! Same as write(*,*)c

do i=1,10do i=1,10 write(*,*)i,a(i),b(i),c(i)write(*,*)i,a(i),b(i),c(i)enddoenddoendend

Fortran 90 (3)Fortran 90 (3)

•On the Linux machines you may On the Linux machines you may compile this program with pgf90compile this program with pgf90e.g. e.g. pgf90 –o example pgf90 –o example example.f90example.f90

•On the Solaris machines use f90On the Solaris machines use f90e.g. e.g. f90 –o example example.f90f90 –o example example.f90

Some basic Fortran conceptsSome basic Fortran concepts

1. Program source file (.f file)1. Program source file (.f file)

For historical reasons dating back to the days For historical reasons dating back to the days of punched cards the standard Fortran statement of punched cards the standard Fortran statement record or line is 72 columns (characters) wide:record or line is 72 columns (characters) wide:------------------…--------------------------…--------1 5671 567 72 72↑↑ ← ← Statement (code) in columns. 7-72 →Statement (code) in columns. 7-72 → ColumnColumn

Long statements (exceeding column 72) can be Long statements (exceeding column 72) can be continued on the next line by putting a continued on the next line by putting a character in column 6 (often a *). Statement character in column 6 (often a *). Statement labels e.g. on format statements are from 1-labels e.g. on format statements are from 1-99999 in columns 1-5 (any justification). 99999 in columns 1-5 (any justification). Comments have a c in column 1. You can also Comments have a c in column 1. You can also use ! at the end of a statementuse ! at the end of a statemente.g. e.g. 100□□□format(‘x= ‘,F8.2)□□!A comment100□□□format(‘x= ‘,F8.2)□□!A comment (□ is a blank (□ is a blank space)space)

Code from other source files can be Code from other source files can be incorporated with the include statement incorporated with the include statement e.g.e.g.

include ‘extracode.f’include ‘extracode.f’

When the f77 or g77 command is used When the f77 or g77 command is used then the code in the file extracode.f then the code in the file extracode.f will be ‘pasted’ into the current file will be ‘pasted’ into the current file at the include statement. We use this at the include statement. We use this approach in Lab Session notes example 11 approach in Lab Session notes example 11 (c) (corr3.f).(c) (corr3.f).

2. Assignment of variables2. Assignment of variablesAs a general rule you will have the As a general rule you will have the statement:statement:

implicit noneimplicit none

as the second line of your program. as the second line of your program. This means that you must explicitly This means that you must explicitly declare all variables in the same way declare all variables in the same way as the C programming language. Without as the C programming language. Without this statement it is assumed that this statement it is assumed that variables beginning with I-N are variables beginning with I-N are integers e.g. icount and A-H and O-Z integers e.g. icount and A-H and O-Z are real e.g. radius.are real e.g. radius.

The The == sign is interpreted as sign is interpreted as ‘assigned ‘assigned to’.to’. Each variable or array element e.g. Each variable or array element e.g. x, p(3) has a memory location allocated x, p(3) has a memory location allocated to it. Assuming that x is declared as to it. Assuming that x is declared as real then the statement x = 2 stores the real then the statement x = 2 stores the real number 2.0 in the memory location real number 2.0 in the memory location allocated (or reserved for) the variable allocated (or reserved for) the variable x. If we have the two statements:x. If we have the two statements:

x = 2x = 2x = x + 5.7x = x + 5.7

then the second statement takes the then the second statement takes the current value of x (2.0), adds 5.7 to x current value of x (2.0), adds 5.7 to x to get 7.7 and then to get 7.7 and then overwritesoverwrites the memory the memory location for x with the new value i.e. location for x with the new value i.e. after the second statement x is now 7.7.after the second statement x is now 7.7.

3. Format descriptors3. Format descriptorsIn the ‘old days’ numbers had to be right-In the ‘old days’ numbers had to be right-justified for read. This doesn’t seem to apply justified for read. This doesn’t seem to apply anymore. In the following the field width w anymore. In the following the field width w includes the decimal point and +/– . d is the includes the decimal point and +/– . d is the number of decimal places. Note that for write number of decimal places. Note that for write numbers are output as right-justified and text as numbers are output as right-justified and text as left-justified.left-justified.Real or floating point numbersReal or floating point numbers

→ → d ←d ←Fw.dFw.d ----•------•-- e.g.e.g. F7.2F7.2

← ← w →w →

e.g. a = 104.5627 will be output as □104.56 (note rounding to fit e.g. a = 104.5627 will be output as □104.56 (note rounding to fit format;format; □ □ represents a space)represents a space)

Exponential representation of floating point numbersExponential representation of floating point numbers ← ← d →d →Ew.dEw.d ±0•------E±xy±0•------E±xy e.g.e.g. E13.6 E13.6

← ← w →w →

This always begins with a decimal part less than one.This always begins with a decimal part less than one.e.g. a = 104.5627 will be output as □0.104563E+03 e.g. a = 104.5627 will be output as □0.104563E+03 (note rounding to fit format)(note rounding to fit format)

IntegersIntegersIwIw ------------e.ge.g.. I6 I6

← ← w →w →

e.g. j = 4 will be output as □□□□□4e.g. j = 4 will be output as □□□□□4

Character or text variablesCharacter or text variablesAwAw ------------e.g.e.g. A6 A6

← ← w →w →

Character variables are written left-justifiedCharacter variables are written left-justifiede.g. label= ‘date‘e.g. label= ‘date‘With the above format (A6) this will appear as:With the above format (A6) this will appear as:date□□date□□ (□ is a blank space)(□ is a blank space)

4. Input4. InputRead a real number from the keyboard and assign to real Read a real number from the keyboard and assign to real variable x.variable x.

real xreal x read(*,*)xread(*,*)xkeyboard ↑ ↑ free formatkeyboard ↑ ↑ free format

Note: Note: read(*,*)read(*,*) == == read(read(55,*),*) i.e. unit i.e. unit 55 is reserved for the is reserved for the keyboardkeyboard..

Read an integer from the keyboard into variable i.Read an integer from the keyboard into variable i.

integer iinteger iread(*,*)iread(*,*)i

Read in 5 real numbers from the keyboard into array a.Read in 5 real numbers from the keyboard into array a.

integer iinteger ireal a(5)real a(5)read(*,*)(a(i),i=1,5)read(*,*)(a(i),i=1,5) ← implied DO loop← implied DO loopThe last line is equivalent to: The last line is equivalent to: read(*,*)a(1),a(2),a(3),a(4),a(5)read(*,*)a(1),a(2),a(3),a(4),a(5)

Input/output from a fileInput/output from a fileTo access a disk file for reading (input) or writing To access a disk file for reading (input) or writing

(output) we use the (output) we use the openopen statement e.g. statement e.g. open (1,file=‘test.dat’,format=‘formatted’)open (1,file=‘test.dat’,format=‘formatted’) open (1,file=‘test.dat’)open (1,file=‘test.dat’)For a For a texttext (readable) file omit the (readable) file omit the formatformat keyword. keyword.To read from the file use something like: To read from the file use something like: read(1,*)xread(1,*)xTo write to the file use something like: To write to the file use something like: write(1,*)xwrite(1,*)x

Note: The number 1 refers to a Note: The number 1 refers to a unit numberunit number in the in the range 1-99. However there are two range 1-99. However there are two special special (reserved) (reserved) unit numbers: unit numbers: 55,,66..

read(*,*) == read(read(*,*) == read(55,*),*) i.e. unit i.e. unit 55 is reserved for the is reserved for the keyboardkeyboard..

write(*,*) == write(write(*,*) == write(66,*),*) i.e. unit i.e. unit 66 is reserved for is reserved for the the screenscreen..

To avoid portability issues do To avoid portability issues do notnot use these special units use these special units to open files.to open files.

In many cases we read data from a file and we’re not sure how many In many cases we read data from a file and we’re not sure how many numbers numbers there will be in the file. We make use of the read there will be in the file. We make use of the read endend keyword. keyword. For simplicity we will assume that the file press.dat contains a For simplicity we will assume that the file press.dat contains a column of numbers e.g.column of numbers e.g.

1021.11021.11000.31000.31001.71001.7…… integer i,ninteger i,n real p(100)real p(100) open (1,file=’press.dat’)open (1,file=’press.dat’) ← Unit 1 is assigned to the file ← Unit 1 is assigned to the file press.datpress.dat

(a kind of short name or handle)(a kind of short name or handle) do i=1,100do i=1,100

read(1,*,end=9)p(i)read(1,*,end=9)p(i) enddoenddo 9 continue9 continue ← Go to here if we encounter the end of the file ← Go to here if we encounter the end of the file (end=9)(end=9) n= i –1n= i –1 ← Last value of i corresponds to the end of the ← Last value of i corresponds to the end of the file (one greater)file (one greater) write(*,*)’n=’,nwrite(*,*)’n=’,n

We can now process the We can now process the arrayarray of numbers p(i) i=1 … n . of numbers p(i) i=1 … n .

In the last example it was assumed that we were reading in In the last example it was assumed that we were reading in a single column of numbers.a single column of numbers.Imagine that the file press.dat contains the following:Imagine that the file press.dat contains the following:Data□□□□□PressureData□□□□□Pressure ← □ denotes a blank space← □ denotes a blank space850601□□□1021.1850601□□□1021.1850602□□□1000.3850602□□□1000.3850603□□□1001.7850603□□□1001.7↑↑Column 1Column 1To read in the second column of numbers into array p:To read in the second column of numbers into array p: character line*80character line*80 ← A variable to hold 80 characters← A variable to hold 80 characters integer i,ninteger i,n real p(100)real p(100) open (1,file=’press.dat’) open (1,file=’press.dat’) read(1,*)line or read(1,’(A)’)lineread(1,*)line or read(1,’(A)’)line do i=1,100 do i=1,100 read(1,’(9x,F6.1)’,end=9)p(i)read(1,’(9x,F6.1)’,end=9)p(i) ← Formatted read ← Formatted read statementstatement enddoenddo9 continue 9 continue n= i –1 n= i –1 write(*,*)’n=’,nwrite(*,*)’n=’,n

We can also use a format statement:We can also use a format statement:

read(1,200,end=9)p(i)read(1,200,end=9)p(i) ← Use the format statement with label 200← Use the format statement with label 200200 format(9x,F6.1)200 format(9x,F6.1)

which is equivalent to:which is equivalent to:

read(1,’(9x,F6.1)’,end=9)p(i)read(1,’(9x,F6.1)’,end=9)p(i)

To read in the line of text as two column labels and both columns of data:To read in the line of text as two column labels and both columns of data: character label1*4, label2*8character label1*4, label2*8 ← Variables to hold column labels of 4 and 8 ← Variables to hold column labels of 4 and 8

characterscharacters integer i,ninteger i,n real p(100)real p(100) integer date(100)integer date(100) ← Array to hold integer date ← Array to hold integer date open (1,file=’press.dat’) open (1,file=’press.dat’) read(1,210)label1,label2read(1,210)label1,label2210 format(A4,5x,A8)210 format(A4,5x,A8) ← Format for labels ← Format for labels do i=1,100 do i=1,100 read(1,’(I6,3x,F6.1)’,end=9)date(i),p(i)read(1,’(I6,3x,F6.1)’,end=9)date(i),p(i) ← Formatted read statement to read ← Formatted read statement to read

date(i) date(i) and p(i) and p(i) enddoenddo 9 continue 9 continue n= i –1 n= i –1 write(*,*)’n=’,nwrite(*,*)’n=’,n

If we are only reading numerical values e.g. three columns of numbers, then If we are only reading numerical values e.g. three columns of numbers, then usually the simplest approach usually the simplest approach

would be something like:would be something like: read(1,*)x(i),y(i),z(i)read(1,*)x(i),y(i),z(i)

5. Output5. OutputGenerally write is just the opposite of read.Generally write is just the opposite of read.Write a real number x to the screen.Write a real number x to the screen. real xreal x write(*,*)xwrite(*,*)x screen ↑ ↑ free formatscreen ↑ ↑ free format

Note: write(*,*) == write(Note: write(*,*) == write(66,*) i.e. unit ,*) i.e. unit 66 is is reserved for the reserved for the screenscreen..

In the primer: In the primer: write(*,*)xwrite(*,*)x is equivalent to is equivalent to print *,xprint *,xYou can use a format statement and include some You can use a format statement and include some output text:output text: write(*,100)xwrite(*,100)x100 format(’The answer is ’,F8.2)100 format(’The answer is ’,F8.2)

is equivalent tois equivalent towrite(*,’(’’The answer is ’’,F8.2)’)xwrite(*,’(’’The answer is ’’,F8.2)’)x ← Note ← Note

repeated quotesrepeated quotes

6. Internal read and write6. Internal read and writeThis involves reading from or writing to a This involves reading from or writing to a charactercharacter

variable that is variable that is treated as a ‘pretend’ file. For instance:treated as a ‘pretend’ file. For instance:

integer ninteger ncharacter*80 optargcharacter*80 optarg ← or← or character optarg*80character optarg*80read(optarg,*)nread(optarg,*)n

The integer variable n is read from the character The integer variable n is read from the character variable optarg as if it variable optarg as if it

were a line of text in a file. Similarly for a real were a line of text in a file. Similarly for a real variable we can have:variable we can have:

read(optarg,*)xread(optarg,*)x

We can also use a format e.g. We can also use a format e.g. read(optarg,’(2x,F6.1)’)xread(optarg,’(2x,F6.1)’)xSimilarly we can write to a character variable:Similarly we can write to a character variable:

write(optarg,*)xwrite(optarg,*)xwrite(optarg,’(2x,F6.1)’)xwrite(optarg,’(2x,F6.1)’)x

7. Logical variables7. Logical variablesSee the primer and reference. These are declared as See the primer and reference. These are declared as logicallogical type type

e.g.e.g.

logical lexistlogical lexist

A logical variable is either true (1) or false (0).A logical variable is either true (1) or false (0). Usually we use an if statement with a logical expression Usually we use an if statement with a logical expression

involving our involving our variables e.g.variables e.g.

if (x.eq.5) thenif (x.eq.5) then ← Is x=5? If so then go to the ← Is x=5? If so then go to the thenthen section otherwise section otherwise go to the go to the elseelse section section

y = 2y = 2 ← If x=5 then go here and set y=2← If x=5 then go here and set y=2elseelse y = -4y = -4 ← If x is not 5 then go here and set y=-4← If x is not 5 then go here and set y=-4endifendifwrite(*,*)’x= ’,x,’ y= ’,ywrite(*,*)’x= ’,x,’ y= ’,y

If the expression in (…) is true the then section is executed If the expression in (…) is true the then section is executed otherwise otherwise

we jump to the else section. we jump to the else section.

Sometimes we code the above as:Sometimes we code the above as:

logical istruelogical istrueistrue= (x.eq.5)istrue= (x.eq.5) ← ← This will be either true (1) or This will be either true (1) or

false (0)false (0)if(istrue)thenif(istrue)then ← If x is 5 then istrue will be 1 and ← If x is 5 then istrue will be 1 and

we we go to the then section go to the then section……endifendif

write(*,*)’istrue=’,istrue,’ x= ’,x,’ y= ’,ywrite(*,*)’istrue=’,istrue,’ x= ’,x,’ y= ’,y

Note: If you write out a logical variable you will Note: If you write out a logical variable you will see T for see T for

true (1) and F for false (0) on most systems.true (1) and F for false (0) on most systems.You can also set a logical variable to true or false You can also set a logical variable to true or false

e.g.e.g.exists= .true.exists= .true.

8. Mixed mode arithmetic8. Mixed mode arithmeticAn expression that involves a combination of real and An expression that involves a combination of real and

integer variables integer variables will give a real value, as long as the output variable is will give a real value, as long as the output variable is

real.real.real x,yreal x,yinteger i,jinteger i,jy= x/iy= x/i ← y is real ← y is realj= x/ij= x/i ← j is an integer i.e. integer truncation of x/i ← j is an integer i.e. integer truncation of x/i

Hence if i= 4 and x= 11. then y= 2.75 and j= 2 i.e. 2.75 Hence if i= 4 and x= 11. then y= 2.75 and j= 2 i.e. 2.75 is truncated to 2.is truncated to 2.

An expression involving integers only will be the integer An expression involving integers only will be the integer truncation.truncation.integer i,j,kinteger i,j,kreal yreal yk= i/jk= i/j← k is an integer i.e. integer truncation of i/j← k is an integer i.e. integer truncation of i/jy= i/jy= i/j← ← y is the real conversion of the integer truncationy is the real conversion of the integer truncation

Hence if i= 7 and j= 2 then k= 3 (integer truncation 7/2= Hence if i= 7 and j= 2 then k= 3 (integer truncation 7/2= 3).3).

Note that y= 3. i.e. the integer 3 is converted to real Note that y= 3. i.e. the integer 3 is converted to real (3.0).(3.0).

9. do loops9. do loops These are covered in the primer and reference but a few These are covered in the primer and reference but a few comments will be made.comments will be made.do loops are convenient for summations used to compute do loops are convenient for summations used to compute the mean and other statistics. Consider the mean of the the mean and other statistics. Consider the mean of the sample sample xx11, , xx22, …, , …, xxnn : :

The summation is The summation is xx11+ + xx22++ …+ …+ xxnn . If we identify an . If we identify an arrayarray x of size n with the sample then the summation isx of size n with the sample then the summation is x(1) + x(2) + …+x(n).x(1) + x(2) + …+x(n).Alternatively the summation can be expressed as a set Alternatively the summation can be expressed as a set

of of successivesuccessive accumulations: accumulations: s1 = x(1)s1 = x(1) s2 = x(1) + x(2) = s1 + x(2)s2 = x(1) + x(2) = s1 + x(2) s3 = x(1) + x(2) + x(3) = s2 + x(3)s3 = x(1) + x(2) + x(3) = s2 + x(3)……

We can use a We can use a do loopdo loop to represent these to represent these accumulations:accumulations:

xbar = 0.xbar = 0. ← ← Initialise xbar i.e. start with a sum of zeroInitialise xbar i.e. start with a sum of zero

do i=1,ndo i=1,n xbar = xbar + x(i)xbar = xbar + x(i) ← ← Add x(i) to previous sum to get Add x(i) to previous sum to get

current sumcurrent sum

enddoenddo xbar = xbar / nxbar = xbar / n ← ← Get the mean by dividing the sum by nGet the mean by dividing the sum by n

In older code the form:In older code the form:

do 200 i=1,ndo 200 i=1,n … …200 continue200 continue

is often seen.is often seen.Note: do loops are often indented for clarity.Note: do loops are often indented for clarity.

A useful variation is the A useful variation is the do whiledo while loop. In this loop. In this case the case the

logical conditionlogical condition that must be true for the loop to be that must be true for the loop to be processed is given as part of the do while statement processed is given as part of the do while statement e.g.e.g.

n= 10n= 10 i= 1i= 1 y= 2.y= 2. do while (i.le.n.and.y.gt.0)do while (i.le.n.and.y.gt.0) ← ← Logical conditionLogical condition

y= y +sin(x(i))y= y +sin(x(i)) ← ← sinsin is a Fortran is a Fortran intrinsicintrinsic (built-in) function (built-in) function

i= i +1 i= i +1 ← ← i is modifiedi is modified

enddoenddoNote that Note that bothboth aspects of this particular condition aspects of this particular condition must be must be

true for the operations within the loop to be true for the operations within the loop to be processed.processed.

A pair of ‘nested’ DO loops is useful for A pair of ‘nested’ DO loops is useful for processing 2D array processing 2D array

elements:elements:

do j=1,nlatdo j=1,nlat do i=1,nlondo i=1,nlon y(i,j)= z(i,j)* a + by(i,j)= z(i,j)* a + b enddoenddo enddoenddo

Here i might correspond to longitude and j to Here i might correspond to longitude and j to latitude.latitude.

Note: the Note: the array elementarray element y(i,j) may be treated as a y(i,j) may be treated as a simple simple

variablevariable in computations. in computations.

There is a special form of the do loop which There is a special form of the do loop which is used only with the read and write is used only with the read and write statements – it is called an statements – it is called an implied do loopimplied do loop e.g.e.g.

n= 3n= 3 read(1,*)(x(i),i=1,n)read(1,*)(x(i),i=1,n)The list in () is expanded i.e. it is The list in () is expanded i.e. it is equivalent to equivalent to

listing the array elements x(i) explicitly listing the array elements x(i) explicitly i.e.i.e.

read(1,*)x(1),x(2),x(3)read(1,*)x(1),x(2),x(3)For large n e.g. n=10000, the implied do loop For large n e.g. n=10000, the implied do loop form form

is obviously very useful.is obviously very useful.

10. Binary (unformatted) files10. Binary (unformatted) filesThe files encountered in the primer and reference are The files encountered in the primer and reference are formatted files that are appropriate for formatted files that are appropriate for texttext data. We open data. We open such files with a statement like:such files with a statement like: open (1,file=’press.dat’)open (1,file=’press.dat’) read (1,*)xread (1,*)xMuch of the output from GCMs and related reanalysis Much of the output from GCMs and related reanalysis projects e.g. NCEP is in a projects e.g. NCEP is in a binarybinary form i.e. not readable to form i.e. not readable to the naked eye. Such files are opened and read in a the naked eye. Such files are opened and read in a

different way. different way. Assume we have a binary version of press.dat called Assume we have a binary version of press.dat called

pressb.dat:pressb.dat: open (1,file=’pressb.dat’,format=’unformatted’)open (1,file=’pressb.dat’,format=’unformatted’) read (1)xread (1)xIn the open statement we need the extra keyword format set In the open statement we need the extra keyword format set

to to ’’unformatted’ that means binary in Fortran. Also in the unformatted’ that means binary in Fortran. Also in the

read read statement we just have the unit number without any formatstatement we just have the unit number without any format

11. Functions11. Functions

These are a special kind of variable. There is no These are a special kind of variable. There is no need to declare need to declare intrinsic (built-in) functionsintrinsic (built-in) functions e.g. e.g. sinsin

but you need to declare your own e.g. but you need to declare your own e.g. probstprobst in in the correlation examples. A function returns a the correlation examples. A function returns a value that is normally assigned to a variable value that is normally assigned to a variable e.g.e.g.

real x,yreal x,y y = sin(x)y = sin(x)Here the value of x is Here the value of x is inputinput to the intrinsic to the intrinsic function function

sin which sin which returnsreturns the value sin(x), the value sin(x), assignedassigned to the to the variable y.variable y.

12. Subroutines12. Subroutines

These don’t require declaration. There is an These don’t require declaration. There is an associationassociation between the variables in the between the variables in the calling routine and the subroutine. calling routine and the subroutine. Variables Variables

must must matchmatch in terms of type e.g. real, and in terms of type e.g. real, and array size but they can have different array size but they can have different names. For instance:names. For instance:

program test2program test2integer ninteger nreal x(100)real x(100)real meanxreal meanxcall calcmean (n,x,meanx)call calcmean (n,x,meanx)…… ↓ ↓ ↓↓ ↓ ↓endendsubroutine calcmean (n,y,ybar)subroutine calcmean (n,y,ybar)integer ninteger nreal y(n)real y(n)real ybarreal ybar……returnreturnendend

The subroutine takes the array x of size n i.e. x(1), x(2), … The subroutine takes the array x of size n i.e. x(1), x(2), … x(n), x(n),

computes the mean ybar and passes this back with the name meanx computes the mean ybar and passes this back with the name meanx in in

the calling routine. Note that n and y are also passed back so the calling routine. Note that n and y are also passed back so if they if they

are modified in the subroutine then they will be modified in the calling programare modified in the subroutine then they will be modified in the calling program after the call statement. Usually we label subroutine arguments after the call statement. Usually we label subroutine arguments

that are that are notnot modified as modified as inputsinputs and those that are as and those that are as outputsoutputs..

13. Command-line arguments: getarg, 13. Command-line arguments: getarg, iargciargcThese are useful intrinsic (built-in) routines to simply input and These are useful intrinsic (built-in) routines to simply input and

output. Note that output. Note that getarggetarg is a subroutine and is a subroutine and iargciargc is a function. is a function.Imagine we have a program called jason1. By using the above routines Imagine we have a program called jason1. By using the above routines we can read filenames and other arguments from the command line. In we can read filenames and other arguments from the command line. In

our our case we want to give an input file (argument 1) and an output file case we want to give an input file (argument 1) and an output file

(argument 2)(argument 2)

e.g. e.g. jason1 press.dat mean.datjason1 press.dat mean.dat ↑ ↑Argument 1Argument 1 ↑ ↑Argument 2Argument 2

A program fragment to do this is:A program fragment to do this is:

character optarg*80, infile*80, outfile*80character optarg*80, infile*80, outfile*80integer narginteger nargnarg= iargc()narg= iargc() ← ← This will be 2 in the above example i.e. 2 argumentsThis will be 2 in the above example i.e. 2 argumentswrite(*,*)’No. of arguments: ’,nargwrite(*,*)’No. of arguments: ’,nargcall getarg (1,optarg)call getarg (1,optarg) ← ← Get first argument from command line and put into optargGet first argument from command line and put into optarg ↑ ↑Argument 1Argument 1infile= optarginfile= optarg ← This variable holds the name of the input file ← This variable holds the name of the input filecall getarg (2,optarg)call getarg (2,optarg) ← ← Get second argument from command line and put into optargGet second argument from command line and put into optarg ↑ ↑Argument 2Argument 2

outfile= optargoutfile= optarg ← ← This variable holds the name of the output fileThis variable holds the name of the output fileopen(1,file=infile)open(1,file=infile) ← ← Open the input fileOpen the input file

open(2,file=outfile)open(2,file=outfile) ← ← Open the output fileOpen the output file

We can also read We can also read numericalnumerical arguments from the arguments from the command linecommand line

e.g. e.g. jason1 press.dat mean.dat 24.5jason1 press.dat mean.dat 24.5 ↑ ↑Argument 1Argument 1 ↑ ↑Argument 2Argument 2 ↑↑Argument 3Argument 3

Argument 3 can be read by adding:Argument 3 can be read by adding:real xreal x……call getarg (3,optarg)call getarg (3,optarg) ← ← Get third argument from command line and put Get third argument from command line and put

into optarginto optarg

↑ ↑Argument 3Argument 3

read(optarg,*)xread(optarg,*)x ← ← Do an internal read from optarg i.e. read x from Do an internal read from optarg i.e. read x from optargoptarg

write(*,*)’x= ’,xwrite(*,*)’x= ’,x

This approach is very useful for handling a large set This approach is very useful for handling a large set of of

input filesinput filese.g. e.g. jason1 press.9601?? mean.datjason1 press.9601?? mean.datUnder UNIX or Linux the argument Under UNIX or Linux the argument press.9601??press.9601?? is is expandedexpanded into a into a setset of filenames which differ in the of filenames which differ in the last last

two characters. Note that at least one of these files two characters. Note that at least one of these files must must

exist. Assume that the files are called exist. Assume that the files are called press.960101, press.960101, press.960102, press.960103, …, press.960107press.960102, press.960103, …, press.960107 i.e. i.e. daily daily

pressure files for Jan 1 1996 to Jan 7 1996. Then the pressure files for Jan 1 1996 to Jan 7 1996. Then the command line will be expanded as if the individual command line will be expanded as if the individual files files

were given i.e. as if we had specified:were given i.e. as if we had specified:jason1 press.960101 press.960102 … press.960107 mean.datjason1 press.960101 press.960102 … press.960107 mean.dat ↑↑Argument 1Argument 1 ↑↑Argument 2Argument 2 ↑ ↑Argument 7Argument 7 ↑Argument 8↑Argument 8

14. Common blocks14. Common blocks Basically a common block is a shared area of memory accessible by Basically a common block is a shared area of memory accessible by a program and its subprograms (subroutines and functions). In a program and its subprograms (subroutines and functions). In order to share the variables contained in this memory area, a order to share the variables contained in this memory area, a common block is declared in the subprograms. common block is declared in the subprograms. For instance:For instance: program prog1program prog1 real x(5),n,qreal x(5),n,q common /myblock1/ n,x,qcommon /myblock1/ n,x,qC * Read in array x(i),i=1,n – code omittedC * Read in array x(i),i=1,n – code omitted … … call sub1call sub1 write(*,*)’q=‘,qwrite(*,*)’q=‘,q endend subroutine sub1subroutine sub1 real x(5),n,qreal x(5),n,q common /myblock1/ n,x,qcommon /myblock1/ n,x,q q= 0.q= 0. do i=1,n do i=1,n q= q + cos(x(i))q= q + cos(x(i)) enddoenddo returnreturn endendSubroutine sub1 uses array x of length n to compute q. All of this Subroutine sub1 uses array x of length n to compute q. All of this information is transferred via the common block myblock1. On information is transferred via the common block myblock1. On return to the main program prog1 we have access to the computed return to the main program prog1 we have access to the computed value of q. Common blocks are mainly used when memory requirements value of q. Common blocks are mainly used when memory requirements are large (more of an issue in the past).are large (more of an issue in the past).

15. Makefiles15. MakefilesA A makefilemakefile is a useful approach for handling the compilation of is a useful approach for handling the compilation of large projects e.g. a GCM. large projects e.g. a GCM. Or you might have a fairly simple program that needs some Or you might have a fairly simple program that needs some special library e.g. NetCDF. special library e.g. NetCDF. All of the required information for compilation can be stored All of the required information for compilation can be stored in the makefile – the default name is called in the makefile – the default name is called MakefileMakefile. . The file includes variables for the Fortran compiler and its The file includes variables for the Fortran compiler and its flags (options) – flags (options) – FCFC and and FFLAGSFFLAGS respectively. The actual respectively. The actual compilation is carried out by the UNIX command compilation is carried out by the UNIX command makemake. In the . In the example below the program tnc2mpl is compiled by:example below the program tnc2mpl is compiled by: make tnc2mplmake tnc2mpl

This calls the file Makefile and looks for the This calls the file Makefile and looks for the sectionsection beginning beginning with:with: tnc2mpl:tnc2mpl: (note the (note the colon colon at the end).at the end).

Similarly:Similarly: make cleanmake cleangoes to the section beginning with:goes to the section beginning with: clean:clean:and removes the Fortran .o files as well as the executable and removes the Fortran .o files as well as the executable (tnc2mpl)(tnc2mpl)

Note: Note: make allmake all will go to the section will go to the section all:all: which sends control to the section for tn2cmpl. which sends control to the section for tn2cmpl.Also lines beginning with # are comments.Also lines beginning with # are comments.

Special note: The source file has a Special note: The source file has a .F.F extension, not .f. This means that it probably contains extension, not .f. This means that it probably contains special special compiler directivescompiler directives

that begin with a that begin with a ##. In this case: . In this case: #include "netcdf.inc“#include "netcdf.inc“ appears in tnc2mpl.F. Therefore the .F appears in tnc2mpl.F. Therefore the .F file will be file will be

subject to ‘pre-processing’ .subject to ‘pre-processing’ .

There are a lot of ‘rules’ used by the make command and things can get rather complicated. In There are a lot of ‘rules’ used by the make command and things can get rather complicated. In addition make often addition make often

works in conjunction with an associated command called works in conjunction with an associated command called makedependmakedepend. This is often used to compile . This is often used to compile software for use software for use

on multiple platforms e.g. Linux, Microsoft Windows. Often the on multiple platforms e.g. Linux, Microsoft Windows. Often the LIBDIRLIBDIR variable (location of variable (location of libraries) will appear in libraries) will appear in

conjunction with the conjunction with the LIBSLIBS (library names) variable e.g. (library names) variable e.g. LIBDIR = -L/home/dcn/lib -L/usr/local/libLIBDIR = -L/home/dcn/lib -L/usr/local/lib LIBS = -lnetcdf -lanalysis -lfftLIBS = -lnetcdf -lanalysis -lfftThe notation The notation –lfft–lfft refers to a library called refers to a library called liblibfftfft.a.a..

See also example 11 (d) (corr4.f) in the Lab Session notes.See also example 11 (d) (corr4.f) in the Lab Session notes.

############################################### Makefile for tnc2mpl# Makefile for tnc2mpl### Linux version: No MUGCM functionality; NetCDF for output# Linux version: No MUGCM functionality; NetCDF for output### make [all|tnc2mpl|clean|new]# make [all|tnc2mpl|clean|new]### NOTE: File dummy.h is a dummy header file to prevent a make error# NOTE: File dummy.h is a dummy header file to prevent a make error# if header files are not used# if header files are not used##############################################

# Note: f77 == g77 on Linux# Note: f77 == g77 on Linux FC = f77FC = f77

# Location of Linux NetCDF library# Location of Linux NetCDF library LIBS = /work18/kevin/netcdf-3.5.1/netcdf-3.5.1/lib/libnetcdf.aLIBS = /work18/kevin/netcdf-3.5.1/netcdf-3.5.1/lib/libnetcdf.a

# BINDIR = bin/# BINDIR = bin/

# g77 flags# g77 flags# FFLAGS = -O3 -Wimplicit -ffortran-bounds-check -finit-local-zero# FFLAGS = -O3 -Wimplicit -ffortran-bounds-check -finit-local-zero# NOTE: Omit -ffortran-bounds-check as this causes a character subset error# NOTE: Omit -ffortran-bounds-check as this causes a character subset error FFLAGS = -O3 -Wimplicit -finit-local-zeroFFLAGS = -O3 -Wimplicit -finit-local-zero

CPPDEFS =CPPDEFS =

OBJS = tnc2mpl.o getopt.oOBJS = tnc2mpl.o getopt.o

OUTPUT = tnc2mplOUTPUT = tnc2mpl

all:all: make tnc2mplmake tnc2mpl

tnc2mpl: $(OBJS)tnc2mpl: $(OBJS) $(FC) -o $(OUTPUT) $(FFLAGS) $(OBJS) $(LIBDIR) $(LIBS)$(FC) -o $(OUTPUT) $(FFLAGS) $(OBJS) $(LIBDIR) $(LIBS)# cp ${OUTPUT} ${BINDIR}# cp ${OUTPUT} ${BINDIR}

clean:clean: rm -f $(OUTPUT) $(OBJS)rm -f $(OUTPUT) $(OBJS)new:new: make cleanmake clean make tnc2mplmake tnc2mpl############################################# default suffix rules# default suffix rules##.f.o:.f.o: $(FC) $(FFLAGS) -c $*.f$(FC) $(FFLAGS) -c $*.f.F.o:.F.o: $(FC) $(CPPDEF) $(FFLAGS) -c $*.F $(INCDIR)$(FC) $(CPPDEF) $(FFLAGS) -c $*.F $(INCDIR)

############################################# dependncies# dependncies##

$(OBJS): *.h$(OBJS): *.h$(OBJS): Makefile$(OBJS): Makefile

############################################# END# END

The source files present in the project are:The source files present in the project are:

dummy.h getopt.f Makefile dummy.h getopt.f Makefile netcdf.inc tnc2mpl.Fnetcdf.inc tnc2mpl.F

After: After: make tnc2cmplmake tnc2cmpl

The files present are:The files present are:

dummy.h getopt.f dummy.h getopt.f getopt.ogetopt.o Makefile Makefile netcdf.inc netcdf.inc tnc2mpltnc2mpl tnc2mpl.F tnc2mpl.F tnc2mpl.otnc2mpl.o

There are now Fortran .o files and the There are now Fortran .o files and the executable tnc2mpl.executable tnc2mpl.

16. Error messages16. Error messagesIn general, Sun f77 compilation and runtime messages are often cryptic. The In general, Sun f77 compilation and runtime messages are often cryptic. The messages from g77 tend to be clearer. The following are some common errors messages from g77 tend to be clearer. The following are some common errors encountered using Sun f77. They have a similar expression using g77.encountered using Sun f77. They have a similar expression using g77.

list io: [-1] end of filelist io: [-1] end of filelogical unit 1, named ‘press.dat’logical unit 1, named ‘press.dat’part of last data 11.0 ^J |part of last data 11.0 ^J |AbortAbortThis occurs if you try to read past the end of a file i.e. the program This occurs if you try to read past the end of a file i.e. the program

expects more data expects more data than is given in the file.than is given in the file.

KilledKilledThere is not enough system memory to run the program. This could be due to There is not enough system memory to run the program. This could be due to

the the presence of other processes on the system consuming most of the available presence of other processes on the system consuming most of the available

memory or memory or the program’s memory requirements exceed the limits for the system.the program’s memory requirements exceed the limits for the system.

Segmentation faultSegmentation faultThis usually means that the memory allocated to the program as it is This usually means that the memory allocated to the program as it is

running has been running has been corrupted in some way. It often arises with illegal array processing e.g. corrupted in some way. It often arises with illegal array processing e.g.

try to write out try to write out a(1) … a(1000) when the maximum size of a is (say) 5.a(1) … a(1000) when the maximum size of a is (say) 5.

I/O errorI/O errorThis occurs when you have the wrong format This occurs when you have the wrong format e.g. e.g. read (1,’(I5)’)xread (1,’(I5)’)xwhere x is real. Note that this is a runtime error – where x is real. Note that this is a runtime error – depending on the compiler it may not show up in the depending on the compiler it may not show up in the compilation stage.compilation stage.

Subscript out of boundsSubscript out of boundsThis occurs when you try to process an array element This occurs when you try to process an array element outside the valid range when the program was outside the valid range when the program was

compiled compiled with f77 –C (Sun) or g77 –ffortran-bounds-check with f77 –C (Sun) or g77 –ffortran-bounds-check

(Linux PC)(Linux PC)e.g. e.g. real a(5)real a(5) write(*,*)a(6)write(*,*)a(6)The element a(6) is not valid so using the above The element a(6) is not valid so using the above

options options will cause the program to abort.will cause the program to abort.