Anda di halaman 1dari 38

Programming in FORTRAN

FORTRAN as a Programming Language:


The FORTRAN programming language was conceived in the early 1950s the name produced from the two words FORmula TRANslation. In 1966 the language was standardized and FORTRAN IV was born. Revision of the language led to FORTRAN 77, the language we use today. The standard for FORTRAN 90 is now available although not yet in widespread use. F77 is a subset of F90. FORTRAN was designed for scientists and engineers, and has dominated this field. For the past 30 years FORTRAN has been used for such projects as the design of bridges and aeroplane structures, it is used for factory automation control, for storm drainage design, analysis of scientific data and so on. Throughout the life of this language, groups of users have written libraries of useful standard FORTRAN programs. These programs can be borrowed and used by other people who wish to take advantage of the expertise and experience of the authors, in a similar way in which a book is borrowed from a library. The individual user may wish to build up their own library of routines they often use. Course structure. Work your way through the following components attempting the exercises as you come across them: Programs Variables Arithmetic Operations Input and Output Looping in Programs Arrays in Programs Checking variables Subprograms and functions Formatting and File Handling

Programs and Problem Solving:


A program is a list of instructions or program statements composed in such a way as to enable a computer to solve a problem. The problem to be solved is broken down into successively smaller parts. These parts should form a well-defined structure, the large complex problem at the top the small easy to handle problems at the bottom. Hence the term top down programming. To get a programming language to help you solve a problem, follow the steps below. 1. State the problem in English 2. Examine the problem and break down into several parts. 3. Examine the parts and refine into smaller parts. 4. Sketch a picture/structure plan 5. Write the main program with references to the subprograms. 6. Test the program. It is important to note that the actual writing of the program is almost the last step. Program Format

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

Variables and Constants:


Variables: A variable is something that may change in value. A variable might be the number of words on different pages of this booklet, the air temperature each day, or the exam marks given to a class of school children. A variable could be likened to a storage box whose contents may often change. The box or variable must be given a name to distinguish it from others. According to FORTRAN rules, the variable name must begin with a letter and may be followed by up to five characters (letters or numbers only). Variables in FORTRAN are of different types. You specify the type and name of each variable you intend to use at the top of your program, after the PROGRAM statement and before any other executable lines. Commented lines are non-executable so they can appear anywhere in the program. If the variable declarations are omitted, the compiler will make certain assumptions, for example, that any variables beginning with the letters I, J, K, L, M, and N are INTEGER. The lack of specification often leads to program errors and it is strongly recommended that variable types are always declared. Numerical data may be separated into integer and real numbers. Integers: Integers are whole numbers, those without a decimal point, (for example 7, 4563, 99) and are stored in integer variables. The general form of the declaration of integer variables is:

INTEGER name1, name2

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

REAL name1, name2

Example: REAL FRACT, MEAN, STDDEV

Characters: Character variables contain one or more characters, (for example G or OXFORD). The general forms are:

CHARACTER name1, name2

where name1 and name2 are 1character each.

CHARACTER*n name1, name2

where name1 and name2 are n characters in length each.

CHARACTER name1*n1, name2*n2

where name1 is of length n1 and name2 is of length n2.

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.

The general form of the declaration of a double precision variable is:

DOUBLE PRECISION name1, name2

Example: DOUBLE PRECISION ROOT, VELO

Arithmetic Operations and Functions:


Operations: In FORTRAN, addition and subtraction are denoted by the usual plus (+) and minus (-) signs. Multiplication is denoted by an asterisk (*). This symbol must be used to denote every multiplication; thus to multiply N by 2, we must use2 * N or N * 2 not 2N. Division is denoted by a slash (/), and exponentiation is denoted by a pair of asterisks (**). Operator + * / ** Operation addition, unary plus subtraction, unary minus Multiplication Division Exponentiation

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.

Funtionname (name1, name2 ...)

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

* I = integer, R = real, DP = double precision.

Assignment Statement The assignment statement is used to assign values to variables and has the form:

variable = expression

For Example: x = 2356.0 y = SQRT (25.0) direction = x * y

Input and Output:


In the preceding section, we considered the assignment statement, which enables us to calculate the values of expressions and store the results of these computations by assigning them to variables. An assignment statement does not, however, display these results on an output device, nor does it allow the user to enter new values during execution. For example, if a projectile is launched from an initial height of HGHT0 with an initial vertical velocity of VELOC0 and a vertical acceleration of ACCEL, then the equations HGHT = 0.5 * ACCEL * TIME ** 2 + VELOCO * TIME + HGHT0 And VELOC = ACCEL * TIME + VELOC0 Give the height (HGHT) and the vertical velocity (VELOC) at any TIME after launch. The program below assigns the value9.807 (m/sec2) to ACCEL, 150.0 (m) to HGHT0, 100.0 (m/sec) to VELOCO, and 5.0 (sec) to TIME and then computes the corresponding values of HGHT and VELOC. 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 = 150.0 VELOC0 = 100.0 TIME = 5.0

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.

Iteration (or Looping):


DO Loops: A DO loop allows repetition of a section of program a set number of times. In DO loops the section to be repeated is started with the statement DO and ended with a labelled CONTINUE statement. The repeated part of the program is called the loop body, and the number of times this is repeated is set by the START, STOP and STEP values. DO n X = START, STOP, STEP . . loop body . . . n CONTINUE

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.

One Dimensional Arrays:


An array is a set of related variables that have the same name and are of the same type (REAL, INTEGER, CHARACTER). For example, a group of 10 students are given marks for a particular essay. The marks could be assigned to 10 individual variables each of a different name, MARK1, MARK2 ... MARK10. Or this set of values could be given a group or array name of MARK and each individual value, called an array element, can be referred to by a subscript number from 1 to 10. The first student's mark is referred to as MARK (1), the second as MARK (2) and so on. A note on pronunciation: MARK (1) would be said as mark sub Because accessing the values in the various elements of an array is done by just referring to the subscript, working with groups of values becomes relatively easy. For example, finding the total of the marks given could be found using a DO loop index to refer to successive addresses as follows: SUM = 0 DO 25 I = 1, 10 SUM = SUM + MARK (1) 25 CONTINUE To do a similar calculation without an array, you would have to write one huge assignment statement: SUM = MARKl+MARK2+MARK3+...+MARK9+MARK10 Imagine how long that assignment statement be if you wanted to sum 100 or even 1000 numbers! Array Declarations Arrays must be declared at the beginning of the program. The easiest way to do this is to state what type of values the array will contain (REAL, INTEGER, CHARACTER) followed by the name of the array followed by the number of elements in the array enclosed in brackets. INTEGER NAME1(n) REAL NAME2(n) where: NAME1 and NAME2 are array names and n is the number of array elements Example: INTEGER MARK (10) REAL TABLE (25), TIME (50) In the above example, MARK will hold 10 integer values with addresses (subscripts) beginning at 1. TABLE will hold 25 real values with addresses beginning at l and TIME will hold 50 real values with

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

Logical expressions may be linked with the logical operators:

.AND. and. OR.

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.

IF ... THEN ... ELSE...


This decision structure is used if code is to be executed whether the logical expression is true or false. In the example below, Block A is executed if the expression is true and Block B is executed if the expression is false. IF (logical expression) THEN Block A ELSE Block B END IF

IF ... THEN ... ELSE IF ... THEN...


This structure is used when more than one block of code can be executed if the initial logical expression is false or if you need to make additional decisions. Because there are more blocks with the potential for execution, there need to be additional decisions to determine if the block can be executed or not. If none of the decisions are true, then none of the blocks are executed. IF (decision 1) THEN Block A ELSE IF (decision 2) THEN Block B ELSE IF (decision 3) THEN Block C END IF

IF ... THEN ELSE IF ... THEN ELSE


This is a third possible decision structure which can be used to make multiple decisions. If none of those decisions are true then Block D is executed. IF (decision1) THEN Block A ELSE IF (decision2) THEN Block B ELSE IF (decision 3) THEN Block C ELSE Block D END IF

IF without THEN and END IF


There is an additional decision structure which may be useful. If the block of code you wish to execute is only one line and there are no additional decisions to be made, you can eliminate the THEN and the END IF statements. You cannot do something like this with ELSE and ELSE IF decision structures. Example IF (A .GT. B) PRINT*, 'B is greater than A' IF (NUMBER .LT. MIN) MIN = NUMBER Now go to the exercises and work your way through the checking variables exercise.

Functions and Subroutines:


Functions and subroutines are FORTRAN's subprograms. Most problems that require a computer program to solve them are too complex to sit down and work all the way through them in one go. Using subprograms allows you to tackle bite size pieces of a problem individually. Once each piece is working correctly you then put the pieces together to create the whole solution. To implement functions and subroutines, first write a main program that references all of the subprograms in the desired order and then start writing the subprograms. This is similar to composing an outline for an essay before writing the essay and will help keep you on track.

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 CALC(A,B,C, SUM,SUMSQ)

REAL A,B,C,SUM,SUMSQ SUM = A + B + C SUMSQ = SUM **2 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.

Formatting and File Handling:


Formatted Input and Output Input from the keyboard and output to the screen are possible using the READ and PRINT statements. So far only list-directed input and output has been encountered, READ * and PRINT *. The programmer has had little control over the way in which data can be input and the layout of printed results. Input and output statements can contain information on how input data should be interpreted and how output data should be laid out. The information is placed in a FORMAT statement. Edit Descriptors FORMAT statements contain edit descriptors that provide layout information. Exponentials are numbers adjusted so they are expressed as: 0.dddd x 10X. In FORTRAN notation such a number is written: s0.dddd x 10X. The italicised letters represent the mantissa and the underlined letters, the exponent. Where: s is sign of the mantissa and sign of the exponent d is significant figures of mantissa x is number of digits in exponent Variable Type Integer Reals Edit Descriptor Iw Fw. d Specifications w is width of value w is width of value (including negative sign, decimal point and decimal places) of value, d decimal places displayed w characters in width n blanks d significant figures in the mantissa, w total width (d + 7 )

Character Blanks Exponential

Aw nX Ew. d

The table below shows the edit descriptor you would use to display each value.

Value 2099 -72.81 1.86x105 (+0.186E+06) Cup of Tea

Edit Descriptor i4 f6.2 e10.3 a10

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)

Glossary of FORTRAN 77 Statements

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

Assigns a value to a variable

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

Specifies character type

CLOSE

Closes a file

COMMON

Establishes blank or named common areas

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

GO TO (10, 20, 30, 40) CLASS

CONTINUE DATA DIMENSION DO

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

Specifies double precision type

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

See block IF statement

END END IF ENDFILE END WHILE, END DO ENTRY

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

Defines a list of descriptors

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

Heading for a function subprogram Unconditionally transfers control to a specified statement

IMPLICIT

Used to establish a naming convention

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

INTEGER INTRINSIC LOGICAL

Logical IF

IF (DISC .GT. 0) DISC = SQRT(DISC)

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

Interrupts program execution, program may be restarted

PRINT

Output statement

PROGRAM

Program heading

READ

Input statement

REAL

Specifies real type

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

Returns control from subprogram to calling program unit

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

Heading for subroutine subprogram

WRITE

Output statement

Anda mungkin juga menyukai