The positions within a line are called columns and are numbered 1, 2, 3, . . ., 80. All FORTRAN statements must be positioned in columns 7 through 72; characters that appear in columns 73 and beyond are ignored. If a statement re quires a statement label, this label must appear in columns 1 through 5. Statement labels must be integers in the range 1 through 99999. Occasionally it may not be possible to write a complete FORTRAN statement using only columns 7 through 72 of a line. In this case, the statement may be continued on another line or lines (up to a maximum of 19), provided that a continuation indicator is placed in column 6 of the line(s) on which the statement is continued. This continuation indicator may be any alphabetic or numeric character other than a zero or a space. A zero or a space in column 6 indicates the first line of a statement. Lines that contain only blanks or that have the letter C or an asterisk (*) in column 1 represent comment lines. Comments are not executed but, rather, appear only in the listing of the program unit. In standard FORTRAN, comments themselves may not be continued from one line to another by using a continuation indicator in column 6; instead, all comments must begin with a C or * in column 1.
Program Layout:
The general form of a program in FORTRAN is This statement marks the beginning of the program and gives it a name. This opening documentation contains info about the program's input, output and purpose. This includes the names and types of the constants and variables used to store input and output values as well as intermediate results are declared. This contains the statements that carry out steps of the algorithm.
heading
commented documentation
specification part
execution part
Here is an example FORTRAN program: PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height, initial velocity, and constant Acceleration. Variables used are: HGHT0 : initial height HGHT : height at any time VELOC0 : initial vertical velocity VELOC : vertical velocity at any time ACCEL : vertical acceleration TIME : time elapsed since projectile was launched Input: none Output: VELOC, HGHT ************************************************************************ REAL HGHT0, HGHT, VELOC0, VELOC, ACCEL, TIME ACCEL = -9.807 HGHT0 = 100.0 VELOC0 = 90.0 TIME = 4.3 HGHT = 0.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *, 'AT TIME ', TIME, ' THE VERTICAL VELOCITY IS ', VELOC PRINT *, 'AND THE HEIGHT IS ', HGHT END
Example: Reals: Reals are fractional numbers, those including a decimal point, (for example, 0.2, 653.46, 1.0) and are stored in real variables. Real numbers cannot be stored accurately. The accuracy of a real variable depends on the computer. The general form of the declaration of a real variable is: INTEGER WHOLE, AVERAGE, SUM
Characters: Character variables contain one or more characters, (for example G or OXFORD). The general forms are:
Constants: Constants are quantities whose values do not change during program execution. In FORTRAN they may be of numeric or character type. Double Precision: Real data values are commonly called single precision data because each real constant is stored in a single memory location. This usually gives seven significant digits for each real value. In many calculations, particularly those involving iteration or long sequences of calculations, single precision is not adequate to express the precision required. To overcome this limitation, FORTRAN provides the double precision data type. Each double precision is stored in two memory locations, thus providing twice as many significant digits.
Real Arithmetic: Providing all variables and constants in the expression are real, real arithmetic will be carried out as expected, with no decimal places being truncated. Integer Arithmetic: Providing the expression has all integers, subtraction, addition, multiplication and exponentiation will prove no problem. However integer division is somewhat different than normal division with real values. Integer division ignores the fractional part. Any decimal places are truncated. Example: 5 / 2 give the result 2 instead of 2.5 3 / 4 gives the result 0 instead of 0.75
Mixed Mode Arithmetic: Mixed mode arithmetic is when an expression contains both reals and integers. If ANY of the operands are real then result of the operation will be real. However, mixed mode arithmetic should be used with extreme care. You may think you have a real operand when in reality you have two integer operands. Example: 5 / 2 * 3.0 is 6.0 Incorrect because the order of operation is left to right. 5/2 = 2 then 2 * 3.0 = 6.0
3.0 * 5 / 2 is 7.5 Correct because of mixed mode arithmetic 3.0 * 5 = 15.0 then 15.0/2 = 7.5
Mixed Mode Variable Assignments: If the variable to which an expression is assigned has been declared as a real variable, any decimal places resulting from the evaluation of the expression will be preserved. Example: Real variable 5 * 2.1 will have a value of 10.5. However, if the variable to which an expression is assigned has been declared as an integer variable, any decimal places resulting from the evaluation of the expression will be lost. Example Integer variable 5 * 2.1 will have a value of 10 Priority Rules: Arithmetic expressions are evaluated in accordance with the following priority rules:
All exponentiations are performed first; consecutive exponentiations are performed from right to left. All multiplication and divisions are performed next, in the order in which they appear from left to right. The additions and subtractions are performed last, in the order in which they appear from left to right.
Functions:
FORTRAN provides several intrinsic functions to carry out calculations on am number of values or arguments and return as result. Commonly used functions are shown in the table below. To use a function we simply give the function name followed by the argument(s) enclosed in parenthesis.
Some FORTRAN Functions Function ABS (x) COS (x) DBLE(x) DPROD(x,y) EXP(x) INT(x) LOG(x) MAX(x1, . . ,Xn) MIN(x1, . .. ,xn) MOD(x,y) NINT(x) REAL(x) SIN(x) SQRT(x) Description Absolute value of x Cosine of x radians Conversion of x to double precision form Double precision product of x and y Exponential function Integer part of x Natural logarithm of x Maximum of x1, . . .,xn Minimum of x1, . . ., xn x (mod y); x - INT(x/y) * y x rounded to nearest integer Conversion of x to real type Sine of x radians Square root of x Type of Argument(s)* I, R, DP R, DP I, R R R, DP R, DP R, DP I, R, DP I, R, DP I, R, DP R, DP I, DP R, DP R, DP Type of Value Same as argument Same as argument DP DP Same as argument I Same as argument Same as argument Same as argument Same as argument I R Same as argument Same as argument
Assignment Statement The assignment statement is used to assign values to variables and has the form:
variable = expression
HGHT = 0.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 END
The values of HGHT and VELOC are calculated as desired, but they are stored internally and are not displayed to the user. Moreover, if the same calculation is to be done for the same acceleration but with values 100.0 for HGHT0, 90.0 for VELOC0, and 4.3 for TIME, then several statements must be modified, as shown in below, and the program executed again. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height, initial velocity, and constant acceleration. Variables used are: HGHT0 : initial height HGHT : height at any time VELOC0 : initial vertical velocity VELOC : vertical velocity at any time ACCEL : vertical acceleration TIME : time elapsed since projectile was launched Input: none Output: none ************************************************************************ REAL HGHT0, HGHT, VELOC0, VELOC, ACCEL, TIME ACCEL = -9.807 HGHT0 = 100.0 VELOC0 = 90.0 TIME = 4.3 HGHT = 0.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 END
The output statement that we consider in this section provides a method for easily displaying information. We also consider an input statement that provides a convenient way to assign values from an external source during execution of the program. FORTRAN provides two types of input/output statements. In the first type, the programmer must explicitly specify the format in which the data is presented for input or, in the case of output, the precise format in which it is to be displayed. In the second type of input/output, certain predetermined standard formats that match the types of items in the input/output list are automatically provided by the compiler. It is this second type, known as list-directed input/output that we consider in this section. List-Directed Output: The simplest list-directed output statement has the following form: List-Directed Output Statement Form: PRINT *, output-list where: Output-list is a single expression or a list of expressions separated by commas. Each of these expressions is a constant, a variable, or a formula. The statement may also be used in the form PRINT * Where no output list is used. Purpose: Displays the values of the items in the output list. Each PRINT statement produces a new line of output. If the output list is omitted, a blank line is displayed.
For example, to display some of the relevant information from the preceding example, we might add two PRINT statements, as shown below. Execution of the program produces output similar to that shown. The exact format and spacing used to display these values are compiler dependent; for example, in some systems, real values might be displayed in scientific notation, and the number of spaces in an output line might be different from that shown. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height, initial velocity, and constant acceleration. Variables used are:
HGHT0 : initial height HGHT : height at any time VELOC0 : initial vertical velocity VELOC : vertical velocity at any time ACCEL : vertical acceleration TIME : time elapsed since projectile was launched Input: HGHT0, VELOC0, TIME Output: VELOC, HGHT ************************************************************************ REAL HGHT0, HGHT, VELOC0, VELOC, ACCEL, TIME ACCEL = -9.807 READ *, HGHT0, VELOC0, TIME HGHT = 0.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *, 'AT TIME ', TIME, ' THE VERTICAL VELOCITY IS ', VELOC PRINT *, 'AND THE HEIGHT IS ', HGHT END
In some situations, one or more blank lines in the output improve readability. A blank line can be displayed by a PRINT statement of the form PRINT * In which the output list is empty. Note that the comma that normally follows the * is also omitted. Execution of each statement of this form causes a single blank line to be displayed. List-Directed Input The simplest form of the list-directed input statement is
List-Directed Input Statement READ *, input-list where Input-list is a single variable or variables separated by commas. Purpose: Causes the transfer of values from some external source (usually the keyboard or a file) and the assignment of these values to the variables in the input list. The following rules apply: i. ii. A new line of data is processed each time a READ statement is executed. If there are fewer entries in a line of input data than there are variables in the input list, successive lines of input are processed until values for all variables in the list have been obtained. If there are more entries in a line of input data than there are variables in the input list, the first data values are used, and all remaining values are ignored. The entries in each line of input data must be constants and of the same type as the variables to which they are assigned. (However, an integer value may be assigned to a real or a double precision variable, and a real value may be assigned to a double precision variable, with automatic conversion taking place.) Consecutive entries in a line of input data must be separated by a comma or by one or more spaces
iii.
iv.
v.
For example, the statement READ *, HGHTO, VELOCO, TIME assigns values to the variables HGHTO, VELOCO, and TIME. Therefore, this single READ statement replaces the three assignment statements used to assign values to these variables in the preceding examples. The modified program is shown below. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height, initial velocity, and constant acceleration. Variables used are: HGHT0 : initial height HGHT : height at any time VELOC0 : initial vertical velocity VELOC : vertical velocity at any time
ACCEL : vertical acceleration TIME : time elapsed since projectile was launched Input: HGHT0, VELOC0, TIME Output: VELOC, HGHT ************************************************************************
REAL HGHT0, HGHT, VELOC0, VELOC, ACCEL, TIME ACCEL = -9.807 READ *, HGHT0, VELOC0, TIME HGHT = 0.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *, 'AT TIME ', TIME, ' THE VERTICAL VELOCITY IS ', VELOC PRINT *, 'AND THE HEIGHT IS ', HGHT END
In an interactive mode of operation, the values assigned to variables in an input list are entered during program execution. In this case, when a READ statement is encountered, program execution is suspended while the user enters values for all the variables in the input list. Program execution then automatically resumes. Because execution is interrupted by a READ statement and because the correct number and types of values must be entered before execution can resume, it is good practice to provide some message to prompt the user when it is necessary to enter data values. This is accomplished by preceding each READ statement with a PRINT statement that displays the appropriate prompts. The program below illustrates this by prompting the user when values for HGHT0, VELOC0, and TIME are to be entered; it is a modification of the program in above. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height, initial velocity, and constant acceleration. Variables used are:
HGHT0 : initial height HGHT : height at any time VELOC0 : initial vertical velocity VELOC : vertical velocity at any time ACCEL : vertical acceleration TIME : time elapsed since projectile was launched Input: HGHT0, VELOC0, TIME Output: VELOC, HGHT ************************************************************************ REAL HGHT0, HGHT, VELOC0, VELOC, ACCEL, TIME ACCEL = -9.807 PRINT *, 'ENTER THE INITIAL HEIGHT AND VELOCITY:' READ *, HGHT0, VELOC0 PRINT *, 'ENTER TIME AT WHICH TO CALCULATE HEIGHT AND VELOCITY:' READ *, TIME HGHT = 0.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *, 'AT TIME ', TIME, ' THE VERTICAL VELOCITY IS ', VELOC PRINT *, 'AND THE HEIGHT IS ', HGHT END
Now go to the exercises and work your way through the input/output and arithmetic problems.
Where n is a statement line number containing the region for the repetitive loop. It can be a positive integer of up to five digits. X will be incremented each time round the loop by the value of STEP. Its initial value is START and looping will end when x exceeds the value STOP at which point the program will carry on after the CONTINUE statement. X is called the loop index and must be an integer variable. The name is not restricted to X. It is also possible to have implied DO loops. Example DO 12 J = 1, 10 12 CONTINUE When the STEP value is omitted from the expression, its default value is set to 1. The loop body is normally indented to support readability of programs. Example DO 20 I = 10, 0,-1 Print *, I 20 CONTINUE In the above example the value of I is printed. Initially it is 10 and reduces by one each time round the loop until I has a value of -1. Now go to the exercises and work your way through the looping problems.
addresses beginning at 1. It is important to differentiate between an address of an array element and the contents of an array element. The contents of an array element can change, the address cannot. Sometimes you may want the addresses of an array to begin at a different number than 1. In these instances, you can use an extended form of the declaration, stating the minimum and maximum values of the subscript. INTEGER NAME1(L:U) REAL NAME2(L:U) where: NAME1 and NAME2 are array names of 6 alphanumeric characters. L is the lower subscript value. U is the upper subscript value. Example INTEGER ERROR (-10:10) REAL SECNDS (0:50) Initial Values for Arrays You can use an assignment statement to fill up arrays: MARK (1) = 23.5 MARK (2) = 45 MARK (10) = 85 Values for array elements can also be read from the keyboard within a loop: DO 10 I = l, N READ *, AGE (I) 10 CONTINUE
However, for arrays of any significant size, reading from a file is more efficient: COUNT = 15 DO 20 J = 1, COUNT READ (1,*) NAME (J), NUMBER (J) 20 CONTINUE
The program segment above will repeat the following sequence 15 times: read two values from the file opened with unit number 1, put the first value into the Jth address for NAME and the second value into the Jth address for NUMBER.
This works fine if you have two columns in the data file, the first column goes into the array NAME and the second column goes into the array NUMBER. What if you know the first 15 values in the file will go into one array? A statement referring to the array without subscripts like the one below will do the trick. REAL NUMBER (15) READ (1,*) NUMBER Printing of Arrays All the elements of an array will be printed if the array name is used without a subscript: Now go to the exercises and work your way through the array problems.
Decisions:
The IF ... THEN Statement
Decisions in FORTRAN are accomplished with an IF-THEN program structure. Usually the block of code affected by the decision is indented to make it stand out from the rest of the program. The logical expression is something that is true or false. If it is true, the block of FORTRAN statements is carried out. If it is false, the program continues from the statement after the END IF. IF (logical expression) THEN block END IF The most common form of logical expression takes the form: (Arithmetic Expression Relational Operator Arithmetic Expression) Example (A .GT. 0) The relational operators are: (note that the full stops must be on either side) .GT. .LT. .EQ. .GE. .LE. .NE. Greater than Less than Equal to Greater than or equal to Less than or equal to Not equal to
Note: When using .AND. or .OR. Each logical expression must be bracketed and the entire logical expression must also be bracketed, as in the example below. Example IF ((A.GT.B).AND. (B.LT.C)) THEN END IF IF ((C.GT.D).OR. (B.EQ.C)) THEN IF ((C.GT.D).OR. (B.EQ.C)) THEN
END IF Logical expressions may be preceded by .NOT. This reverses the expressions truth. Example IF (.NOT. (A.GT.B)) THEN END IF In English the above expression reads: if A is not greater than B.
Functions:
The purpose of a function is to take in a number of values or arguments, do some calculations with those arguments and then return a single result. There are some functions which are written into FORTRAN and can be used without any special effort by you, the programmer. They are called intrinsic functions. There are over 40 intrinsic functions in FORTRAN and they are mainly concerned with mathematical functions. The general way to activate a function is to use the function name in an expression. The function name is followed by a list of inputs, also called arguments, enclosed in parenthesis: answer = functionname (argument1, argument2, . . .
Example: PRINT*, ABS (T) The compiler evaluates the absolute value of T and prints it out The compiler calculates the value of sin x, adds 45 then puts the result into the variable Y, where x is in radians. The compiler puts the maximum value of a, b, c and d into the variable M. If a=2, b=4, c=1 and d=7, then M would have a value of 7. The compiler evaluates the expression, a**2+b**2, sends that value to the SQRT function, and places the answer in the variable
Y = SIN (X) + 45
M=MAX(a,b,c,d)
C=SQRT ( a* * 2 +b* * 2 )
As shown by the MAX function example above, a function may have one or more arguments but will only give one result. Also, as shown by the SQRT function example above, the argument for a function does not have to be a variable. It can be an expression or even a constant if you want to reference it again. One last item to remember, you must use result of a function call in an assignment statement or a PRINT statement, as shown in the examples above.
External Functions:
The intrinsic functions in FORTRAN are useful but there will be a time when there is no intrinsic function to meet your needs. When this occurs you may write your own function subprogram. You have to do one thing in the main program to use an external function. You need to declare the function name in the variable declaration section. Function names follow the same rules as for variable names: less than six letters or numbers and beginning with a letter. Because of this, function names should not be used as variable names. Once that is done and the function is written, activating it is just like activating an intrinsic function. Now you are ready to write your function. There are a few rules for writing external functions:
Function subprograms and any other subprograms are placed after the END statement of the main program. They are started with a line that includes the type of value the function will return, the function name, and the list of arguments the function takes as inputs. Any variables the function uses, including the arguments, must be declared in the function right after the first line. The function name is not declared within the function. You must use the function name in an assignment statement within the function. This is how the compiler knows which value to pass back to the main program. A function must finish with RETURN and END statements.
The example program below shows how to write an external function which calculates the average of three numbers. Note the argument list in the main program does not use the same variable names as the argument list in the function. This is not a problem because a function is a selfcontained entity whose only tie with the main program is the order of the values in the argument list. So in the first reference to the function, the value in A (5.0) gets transferred to x, the value in B (2.0) to Y and the value in c (3.0) to z. However, in the third reference to the function, it is the squared values (25.0, 4.0, 9.0) that are transferred to x, Y and z respectively in the function. Note also that the variable SUM is used only in the function and therefore is declared only in the function. Example Program PROGRAM FUNDEM C Declarations for main program REAL A,B,C REAL AV, AVSQ1, AVSQ2 REAL AVRAGE C Enter the data DATA A,B,C/5.0,2.0,3.0/
Calculate the average of the numbers AV = AVRAGE(A,B,C) AVSQ1 = AVRAGE(A,B,C) **2 AVSQ2 = AVRAGE(A**2,B**2,C**2) PRINT *,'Statistical Analysis' PRINT *,'The average of the numbers is: ',AV PRINT *,'The average squared of the numbers: ',AVSQ1 PRINT *,'The average of the squares is: ', AVSQ2 END REAL FUNCTION AVRAGE(X,Y,Z) REAL X,Y,Z,SUM SUM = X + Y + Z AVRAGE = SUM /3.0 RETURN END
Subroutines:
You will want to use a function if you need to do a complicated calculation that has only one result which you may or may not want to subsequently use in an expression. Recall the external function example program where the average was called and then squared in one line. Subroutines, on the other hand, can return several results. However, calls to subroutines cannot be placed in an expression. In the main program, a subroutine is activated by using a CALL statement which include the subroutine name followed by the list of inputs to and outputs from the subroutine surrounded by parenthesis. The inputs and outputs are collectively called the arguments. A subroutine name follows the same rules as for function names and variable names: less than six letters and numbers and beginning with a letter. Because of this, subroutine names should be different than those used for variables or functions. As with functions, there are some rules for using subroutines. Keep these in mind when writing your subroutines:
You do not need to declare the subroutine name in the main program as you do with a function name. They begin with a line that includes the word SUBROUTINE, the name of the subroutine, and the arguments for the subroutine.
One way of indicating which variables are inputs and which are outputs is to put the inputs on the first line, use a continuation marker and put the outputs on the second line. See the example program for an application of this programming style. All variables used by the subroutine, including the arguments, must be declared in the subroutine. The subroutine name is not declared anywhere in the program.A subroutine is finished off with a RETURN and an END statement. Exercise 4: Subroutines In larger programs it is good programming style to include after the FUNCTION or SUBROUTINE statements comments explaining the meanings of the arguments and what the subprogram does. A hint when you are debugging your programs: When extraordinary, incorrect numbers start appearing from nowhere as your program runs, you probably have not got your subroutine arguments in the right order in either the main program or in the subroutine. The same trick applies to functions. Example Program PROGRAM SUBDEM REAL A,B,C,SUM,SUMSQ CALL INPUT( + A,B,C) CALL CALC(A,B,C,SUM,SUMSQ) CALL OUTPUT(SUM,SUMSQ) END
SUBROUTINE INPUT(X, Y, Z) REAL X,Y,Z PRINT *,'ENTER THREE NUMBERS => ' READ *,X,Y,Z RETURN END
SUBROUTINE OUTPUT(SUM,SUMSQ) REAL SUM, SUMSQ PRINT *,'The sum of the numbers you entered are: ',SUM PRINT *,'And the square of the sum is:',SUMSQ RETURN END
Now go to the exercises and work your way through the subprograms and functions.
Aw nX Ew. d
The table below shows the edit descriptor you would use to display each value.
The Format Statement The general form of the FORMAT statement is: label Where label edl,ed2 text c is an identifying number for PRINT or READ. are edit descriptors separated by commas messages are surrounded by single quotes is carriage control for OUTPUT only and can be: lx O + l moving the output to the next line double spacing the output move to beginning of line, overwriting anything already there start a new page FORMAT(c, ed1, ed2,'Text message to the screen', ed3...)
The single quotes around the carriage control codes must be there. A comma (, ) is usually used to separate edit descriptors and text messages but if a slash / is used, instead of a comma, subsequent output will be on a new line. You have to put a carriage control code after a slash to indicate what kind of spacing you want. The label on a FORMAT statement replaces the * in a PRINT or READ statement. Up to this point, any text messages you wanted printed out were included in the PRINT * statement. With formatted output you must put the text message in the format statement. Only variable names may be included on a formatted PRINT or READ statement.
Formatted Input Getting a formatted READ to work correctly is very tricky to do. Every blank specified in the FORMAT statement must be present and the values have to appear exactly as specified in the FORMAT statement. The only real advantage of doing a formatted READ iS that character variables do not need single quotes around them to be read in properly. There are no rules governing the location of FORMAT statements in programs except that they must be in the same local or sub program unit that refers to them. So any format statements used by the main program must appear in the main program and any format statements used by a subroutine or function must appear within that subroutine or function. Format statements can be placed directly after PRINT and READ statements but some programmers prefer to keep them together near the end of a program. File Handling So far the programs written have taken input data from the keyboard and the results have been displayed on the computer screen. Data is often input from a file, acted on by a FORTRAN program and output to a file. This is advantageous when the amount of data is large and may be manipulated several times or when the results need to be kept for further calculations. The statements for input and output must include details of how and where to input data from and output to. READ * may be expanded to include these controls, however WRITE iS used for output rather than PRINT. Example Program 5 exemplifies common ways of dealing with files: opening, closing, reading from and writing to. Input/output Statements READ WRITE (control list) variable list (control list) variable list
Where the control list items can be a number of the following and are described later on: UNIT = unit identifier FMT = format identifier END = label ERR = label Example: READ (UNIT = 1, FMT = 10) A, B, C READ (1, 10) A, B, C WRITE (UNIT = 2, FMT = 20) X, Y, Z WRITE (2, 20) X, Y, Z
Unit identifier Every control list must contain a unit identifier. It is this that identifies the location of the file or device to be accessed. If the unit identifier is first in the control list the UNIT = may be omitted. For example: WRITE (2, FMT=20) X, Y, Z You may choose any number for a unit identifier except for two reserved values that generally have predefined meanings. The number 5 represents keyboard input and 6 represents screen output. So READ(5,*) A,B,C is another way of writing READ*, A,B,C. Likewise, WRITE(6,*) A,B,C is another way of writing PRINT*, A,B,C. Format identifier This identifies how the data is organised either by reference to a FORMAT statement or an asterisk indicating list-directed format. Example: READ (UNIT=l, FMT = 10) A, B, C the FORMAT statement it is at label 10 READ (UNIT=1, FMT = *) A, B, C Asterisk (*) means list-directed formatting. In other words, no formatting If the format identifier is second in the control list the FMT = may be omitted. Example: READ (1, 10) A, B, C The more usual concise form. End-of-file condition Only one end-of-file condition may appear in the control list. When the READ statement reaches the end of the data file without an error occurring, no more data is transferred and the control of the program jumps to the label specified in the READ statement. In the example below, a GO TO statement is used to continue reading from the file until the file is completely read. GO TO statements can be dangerous because they tend to create jumps in control which are hard to follow. It is wise to keep use of GO TO statements to a minimum. Example: 80 c READ(l,*,END=99)A,B,C do something with A, B, and C GO TO 80 99 PRINT *, ALL DATA READ'
Error condition If some error occurs on input/output and there is an error specifier, the input/output is stopped and the program jumps to the label given in the error specifier. Example READ(l,*,ERR=100,END=200)A,B,C 100 PRINT *, ERROR ON READING, STOPPING PROGRAM RUN' STOP c 200 or else continue with the rest of the program CONTINUE END A common cause of error in file reading is running out of numbers in the file before the compiler has filled up the requested variables. For example, say that the file accessed by the READ statement above, looked like this: 12, 13, 14 15 16 17 18 19 20 21 22 23 When the file is initially opened, a pointer is placed at the top of the file. As the file is read, the pointer moves through the file, keeping track of what line has been read and what line has not. The pointer will move for two reasons: l) after a line has been looked at or 2) if the compiler needs more values. So after the first read statement, the pointer gets positioned on the line with 15 in it because it was told to look for three values to fill A, B and c and it found all it needed on the first line. The pointer moved on because the line had been examined. The second time the READ statement is executed; the pointer is on the line with 18 in it. Again, the compiler was told to look for three values, but they were not on the same line so the pointer moved on to find enough values. When it found all the values it needed the pointer got positioned on the next fresh line, in this case the one beginning with 18. The third time the READ statement is executed; the pointer is left on the line beginning with 22. The compiler found the three values it needed on a single line, did not need the fourth value, 21, but moved on anyway.
During the fourth time the READ statement is executed, the program will have an error. The compiler was told to look for three values in the file. It only found two before it got to the end of the file. So 22 is put into A and 23 is put into B but c does not get a value and the control of the program jumps to line 10 o because that is where it was told to go if there were problems. , Implied DO loops describe a method of reading all the data. If later on in the program you want to move the pointer back to the top of the file, the REWIND statement can be used. Example REWIND (UNIT=1) Opening and Closing Files The OPEN statement The OPEN statement connects the file and defines the specifications according to the file specifications list. OPEN(UNIT = number, filespec list) where the file specifications list can be some of the following: ERR = label FILE = character, therefore enclosed in quotes STATUS = character, therefore enclosed in quotes There are more file specifications which can be looked up in one of the recommended texts. ERR - If an error condition occurs while the file is being opened, the program jumps to the label. FILE - This specifies the name of the file to be opened. The filename is considered a character entity so it must be enclosed in quotes. STATUS - This is also a character entity which must be enclosed in quotes OLD the file to be opened already exists. NEW the named file must not already exist. A file is created and opened. UNKNOWN The file may or may not exist.
The CLOSE statement: The CLOSE statement disconnects a file: CLOSE([UNIT=] number)
STATEMENT
Description Transfers control, depending on whether value of an arithmetic expression is negative, zero, or positive Assigns a statement number to a variable Transfers control to a statement specified by a variable; in conjunction with ASSIGN statement
Example of Usage
Arithmetic IF
IF (X-Y) 30, 40 , 50
ASSIGN
ASSIGN 50 TO N
Assigned GO TO
GO TO N
Assignment
PI = 3.1416 NUMBER = 0 MAJOR = ' CPSC ' Z FLAG =. TRUE. BACKSPACE 12 INTEGER MONTH, YEAR COMMON / INFO / MONTH, YEAR DATA MONTH, YEAR /12, 1995/ END IF (X.GT. O) THEN RESULT = SQRT(X) ELSE IF (X .EQ. 0) THEN PRINT *, 'NUMBER IS 0' ELSE PRINT *, 'NEGATIVE NUMBER' END IF CALL CONVER (A, T, X, Y) CHARACTER*10 NAME, INIT*1, LIST(20) CLOSE (12)
BACKSPACE
Backspace a file
BLOCK DATA
Heading of a block data subprogram used to initialize variables in named common blocks
BLOCK IF
Executes or bypasses a block of statements, depending on truth or falsity of a logical expression; must be paired with END IF and may have ELSE or ELSE IF blocks
CALL
Calls a subroutine
CHARACTER
CLOSE
Closes a file
COMMON
COMMON ALPHA, BETA, MAT (5,5) COMMON / INFO / MONTH, YEAR COMPLEX Z, W, MAT (5,5)
COMPLEX
Specifies complex type Transfers control to one of several statements, depending on the value of an integer expression Used to close a DO-loop Initializes variables at compile time Declares dimensions of arrays First statement of a DO-loop
Computed GO TO
5 CONTINUE DATA PI, (X(I),I=1,5) /3.14,5*0/ DIMENSION MAT(5,5), LIST(20) DO 5 I=1, N DOUBLE PRECISION A, B, ROOTS(20) See block IF statement
DOUBLE PRECISION
ELSE
Defines ELSE-block in a block IF statement Defines ELSE-IF block within a block IF used for multi alternative selection Last statement of each program unit Last statement of a block IF Places end-of-file record in a file Terminates a WHILE loop; not in standard FORTRAN 77 Specifies entry point in a subprogram Establishes sharing of memory locations by different variables in same program unit Specifies externally defined subprograms that may be used as arguments
ELSE IF
END See block IF statement ENDFILE 12 See WHILE statement ENTRY POLY (X) EQUIVALENCE(X,Y), (ALPHA,A,T(3))
EQUIVALENCE
EXTERNAL
EXTERNAL F, QUAD
FORMAT
20 FORMAT (1X, 'ROOTS ARE', 2F8.3) FUNCTION AVE(X, N) GO TO 100 IMPLICIT REAL (L,N-Z), INTEGER (A-K) INQUIRE (EXIST = FLAG, NAME =FNAME) INTEGER X, CLASS, TABLE(10,20) INTRINSIC SIN, DSQRT LOGICAL P, Q, TABLE(4,6)
FUNCTION GO TO
IMPLICIT
INQUIRE
Determines properties of a file or of its connection to a unit number Specifies integer type Specifies intrinsic functions that may be used as arguments Specifies logical type Executes or bypasses a statement depending on the truth or falsity of a logical expression
Logical IF
OPEN
Opens a file
OPEN(UNIT = 12, FILE = FNAME, STATUS = 'OLD') PARAMETER (LIM = 100, RATE =1.5 PAUSE PAUSE 'PROGRAM PAUSE' PRINT *, 'X = ', X PRINT * PRINT '(1X, 317)', M, N, M + N-e PROGRAM WAGES READ *, ALPHA, BETA READ '(15, F7.2)', NUM, Z READ (12, *, END = 20) HOURS, RATE
PARAMETER
Defines parameters
PAUSE
Output statement
PROGRAM
Program heading
READ
Input statement
REAL
REAL NUM, GAMMA, MAT(10,10) RETURN RETURN 2 REWIND 12 SAVE X, Y, NUM SAVE F(X,Y) = X**2 + Y**2 STOP STOP 'PROGRAM HALTS' SUBROUTINE CONVER (U, V, RHO, PHI) WRITE (*,*) A, B, C WRITE (12,'(1X, 316)') N1, N2, N3
RETURN
REWIND
Positions file at initial point Saves values of local variables in a subprogram for later references Function defined within a program unit by a single statement
SAVE
Statement function
STOP
Terminates execution
SUBROUTINE
WRITE
Output statement