This action might not be possible to undo. Are you sure you want to continue?
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.
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.
807 HGHT0 = 100.Here is an example FORTRAN program: PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height. initial velocity. ' THE VERTICAL VELOCITY IS '. 'AT TIME '. ACCEL. TIME.3 HGHT = 0. VELOC PRINT *. TIME ACCEL = -9.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *. 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 END . HGHT ************************************************************************ REAL HGHT0. VELOC.0 VELOC0 = 90. VELOC0. and constant Acceleration. HGHT. 'AND THE HEIGHT IS '.0 TIME = 4.
653. or the exam marks given to a class of school children. The box or variable must be given a name to distinguish it from others. J. 99) and are stored in integer variables. that any variables beginning with the letters I. Variables in FORTRAN are of different types. Commented lines are non-executable so they can appear anywhere in the program. those including a decimal point. Integers: Integers are whole numbers.2. A variable could be likened to a storage box whose contents may often change. name2 . M. L. the variable name must begin with a letter and may be followed by up to five characters (letters or numbers only). name2 Example: • Reals: Reals are fractional numbers. (for example. The accuracy of a real variable depends on the computer. and N are INTEGER. the compiler will make certain assumptions. for example. AVERAGE. The general form of the declaration of a real variable is: INTEGER WHOLE. 0. 1. the air temperature each day. (for example 7. You specify the type and name of each variable you intend to use at the top of your program. A variable might be the number of words on different pages of this booklet. 4563. those without a decimal point. Real numbers cannot be stored accurately.46.Variables and Constants: Variables: A variable is something that may change in value.0) and are stored in real variables. The lack of specification often leads to program errors and it is strongly recommended that variable types are always declared. According to FORTRAN rules. K. The general form of the declaration of integer variables is: INTEGER name1. Numerical data may be separated into integer and real numbers. If the variable declarations are omitted. after the PROGRAM statement and before any other executable lines. SUM REAL name1.
single precision is not adequate to express the precision required. name2 where name1 and name2 are n characters in length each. To overcome this limitation. CHARACTER*n name1. The general form of the declaration of a double precision variable is: DOUBLE PRECISION name1. name2*n2 where name1 is of length n1 and name2 is of length n2. In FORTRAN they may be of numeric or character type. name2 Example: DOUBLE PRECISION ROOT. MEAN. thus providing twice as many significant digits. In many calculations. particularly those involving iteration or long sequences of calculations. This usually gives seven significant digits for each real value. CHARACTER name1*n1. The general forms are: CHARACTER name1. FORTRAN provides the double precision data type. Each double precision is stored in two memory locations. name2 where name1 and name2 are 1character each. VELO . Double Precision: Real data values are commonly called single precision data because each real constant is stored in a single memory location.Example: • REAL FRACT. Constants: Constants are quantities whose values do not change during program execution. (for example G or OXFORD). STDDEV Characters: Character variables contain one or more characters.
subtraction. addition and subtraction are denoted by the usual plus (+) and minus (-) signs.0 = 6. Integer Arithmetic: Providing the expression has all integers. unary minus Multiplication Division Exponentiation Real Arithmetic: Providing all variables and constants in the expression are real. However integer division is somewhat different than normal division with real values. addition. Division is denoted by a slash (/). If ANY of the operands are real then result of the operation will be real. Any decimal places are truncated. This symbol must be used to denote every multiplication. Integer division ignores the fractional part. unary plus subtraction.5 3 / 4 gives the result 0 instead of 0. real arithmetic will be carried out as expected. and exponentiation is denoted by a pair of asterisks (**). mixed mode arithmetic should be used with extreme care. we must use2 * N or N * 2 not 2N. Example: 5 / 2 give the result 2 instead of 2. multiplication and exponentiation will prove no problem. thus to multiply N by 2.0 is 6.75 Mixed Mode Arithmetic: Mixed mode arithmetic is when an expression contains both reals and integers. Operator + * / ** Operation addition.Arithmetic Operations and Functions: Operations: In FORTRAN.0 . Multiplication is denoted by an asterisk (*). with no decimal places being truncated. However. Example: 5 / 2 * 3. You may think you have a real operand when in reality you have two integer operands.0 Incorrect because the order of operation is left to right. 5/2 = 2 then 2 * 3.
Funtionname (name1. any decimal places resulting from the evaluation of the expression will be preserved. Example Integer variable 5 * 2.5 Correct because of mixed mode arithmetic 3.0/2 = 7.. in the order in which they appear from left to right. To use a function we simply give the function name followed by the argument(s) enclosed in parenthesis. in the order in which they appear from left to right. All multiplication and divisions are performed next.) .0 * 5 = 15. consecutive exponentiations are performed from right to left.5 Mixed Mode Variable Assignments: If the variable to which an expression is assigned has been declared as a real variable.5.0 then 15. any decimal places resulting from the evaluation of the expression will be lost.1 will have a value of 10.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.. Commonly used functions are shown in the table below.0 * 5 / 2 is 7. Example: Real variable 5 * 2.3. if the variable to which an expression is assigned has been declared as an integer variable. • • Functions: FORTRAN provides several intrinsic functions to carry out calculations on am number of values or arguments and return as result. The additions and subtractions are performed last. However. name2 .
xn) MOD(x. DP I. . Assignment Statement The assignment statement is used to assign values to variables and has the form: variable = expression For Example: • • • x = 2356. . R..Xn) MIN(x1. DP = double precision. . R R R. . . R = real. . xn x (mod y). .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 I.. R. DP R.y) EXP(x) INT(x) LOG(x) MAX(x1.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. . DP R. x . DP I.Some FORTRAN Functions Function ABS (x) COS (x) DBLE(x) DPROD(x. DP I. 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. . .. . DP R. DP R. DP R. DP I.0 y = SQRT (25. .0) direction = x * y . DP R.xn Minimum of x1.
VELOC. TIME ACCEL = -9. initial velocity. 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.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.Input and Output: In the preceding section. ACCEL.0 VELOC0 = 100.0 . For example. HGHT. The program below assigns the value‹9. we considered the assignment statement.807 HGHT0 = 150. however. display these results on an output device. and constant acceleration. An assignment statement does not.0 (m/sec) to VELOCO.807 (m/sec2) to ACCEL.0 (sec) to TIME and then computes the corresponding values of HGHT and VELOC. and 5. VELOC0.0 TIME = 5. 150.0 (m) to HGHT0. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height. then the equations HGHT = 0. if a projectile is launched from an initial height of HGHT0 with an initial vertical velocity of VELOC0 and a vertical acceleration of ACCEL. nor does it allow the user to enter new values during execution. which enables us to calculate the values of expressions and store the results of these computations by assigning them to variables. 100.
HGHT = 0.0 for HGHT0. and 4. initial velocity. VELOC. and the program executed again.3 HGHT = 0. if the same calculation is to be done for the same acceleration but with values 100.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 END . ACCEL. 90. and constant acceleration. Moreover.3 for TIME. VELOC0.0 for VELOC0. as shown in below.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 END The values of HGHT and VELOC are calculated as desired.807 HGHT0 = 100. then several statements must be modified. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height. TIME ACCEL = -9.0 TIME = 4. but they are stored internally and are not displayed to the user. HGHT.0 VELOC0 = 90. 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.
and the number of spaces in an output line might be different from that shown. a variable. If the output list is omitted. a blank line is displayed. real values might be displayed in scientific notation. to display some of the relevant information from the preceding example. for example. Each PRINT statement produces a new line of output.The output statement that we consider in this section provides a method for easily displaying information. certain predetermined standard formats that match the types of items in the input/output list are automatically provided by the compiler. We also consider an input statement that provides a convenient way to assign values from an external source during execution of the program. and constant acceleration. The statement may also be used in the form PRINT * Where no output list is used. in some systems. the programmer must explicitly specify the format in which the data is presented for input or. or a formula. known as list-directed input/output that we consider in this section. Purpose: Displays the values of the items in the output list. It is this second type. In the first type. List-Directed Output: The simplest list-directed output statement has the following form: List-Directed Output Statement Form: PRINT *. FORTRAN provides two types of input/output statements. as shown below. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height. In the second type of input/output. the precise format in which it is to be displayed. Each of these expressions is a constant. Variables used are: . Execution of the program produces output similar to that shown. For example. in the case of output. initial velocity. we might add two PRINT statements. The exact format and spacing used to display these values are compiler dependent. output-list where: Output-list is a single expression or a list of expressions separated by commas.
TIME HGHT = 0. Note that the comma that normally follows the * is also omitted.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. VELOC PRINT *.807 READ *.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *. A blank line can be displayed by a PRINT statement of the form PRINT * In which the output list is empty. HGHT. 'AND THE HEIGHT IS '. 'AT TIME '. VELOC0. VELOC0. ' THE VERTICAL VELOCITY IS '. Execution of each statement of this form causes a single blank line to be displayed. HGHT ************************************************************************ REAL HGHT0. ACCEL. TIME. TIME ACCEL = -9. List-Directed Input The simplest form of the list-directed input statement is . HGHT END In some situations. VELOC. HGHT0. one or more blank lines in the output improve readability. VELOC0. TIME Output: VELOC.
) Consecutive entries in a line of input data must be separated by a comma or by one or more spaces iii. HGHTO. with automatic conversion taking place. and TIME. VELOCO. Variables used are: HGHT0 : initial height HGHT : height at any time VELOC0 : initial vertical velocity VELOC : vertical velocity at any time . this single READ statement replaces the three assignment statements used to assign values to these variables in the preceding examples. VELOCO. and a real value may be assigned to a double precision variable. ii. and all remaining values are ignored. (However. If there are fewer entries in a line of input data than there are variables in the input list. TIME assigns values to the variables HGHTO. If there are more entries in a line of input data than there are variables in the input list. and constant acceleration. the statement READ *. v. The modified program is shown below. A new line of data is processed each time a READ statement is executed.List-Directed Input Statement READ *. For example. an integer value may be assigned to a real or a double precision variable. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height. Therefore. iv. successive lines of input are processed until values for all variables in the list have been obtained. 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. input-list where Input-list is a single variable or variables separated by commas. The following rules apply: i. the first data values are used. The entries in each line of input data must be constants and of the same type as the variables to which they are assigned. initial velocity.
HGHT. VELOC0. The program below illustrates this by prompting the user when values for HGHT0. This is accomplished by preceding each READ statement with a PRINT statement that displays the appropriate prompts. VELOC0. initial velocity. the values assigned to variables in an input list are entered during program execution. Variables used are: .807 READ *. Program execution then automatically resumes. In this case. and TIME are to be entered. HGHT END In an interactive mode of operation. Because execution is interrupted by a READ statement and because the correct number and types of values must be entered before execution can resume.ACCEL : vertical acceleration TIME : time elapsed since projectile was launched Input: HGHT0. HGHT0. PROGRAM PROJEC ************************************************************************ This program calculates the velocity and height of a projectile given its initial height. VELOC0. when a READ statement is encountered. and constant acceleration. ACCEL. TIME. TIME ACCEL = -9. it is a modification of the program in above.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *. TIME HGHT = 0. VELOC PRINT *. VELOC0. 'AT TIME '. HGHT ************************************************************************ REAL HGHT0. ' THE VERTICAL VELOCITY IS '. 'AND THE HEIGHT IS '. VELOC. program execution is suspended while the user enters values for all the variables in the input list. it is good practice to provide some message to prompt the user when it is necessary to enter data values. TIME Output: VELOC.
VELOC0. VELOC PRINT *. TIME. VELOC. HGHT.5 * ACCEL * TIME ** 2 + VELOC0 * TIME + HGHT0 VELOC = ACCEL * TIME + VELOC0 PRINT *. VELOC0.807 PRINT *. TIME Output: VELOC. TIME ACCEL = -9. 'ENTER TIME AT WHICH TO CALCULATE HEIGHT AND VELOCITY:' READ *. HGHT END Now go to the exercises and work your way through the input/output and arithmetic problems. 'ENTER THE INITIAL HEIGHT AND VELOCITY:' READ *. 'AT TIME '. 'AND THE HEIGHT IS '. . VELOC0 PRINT *. HGHT ************************************************************************ REAL HGHT0. TIME HGHT = 0. ' THE VERTICAL VELOCITY IS '.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. ACCEL. HGHT0.
Initially it is 10 and reduces by one each time round the loop until I has a value of -1. In DO loops the section to be repeated is started with the statement DO and ended with a labelled CONTINUE statement. Example DO 20 I = 10. . STOP and STEP values. 0. .-1 Print *.Iteration (or Looping): DO Loops: A DO loop allows repetition of a section of program a set number of times. loop body . X will be incremented each time round the loop by the value of STEP. Example DO 12 J = 1. 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. n CONTINUE Where n is a statement line number containing the region for the repetitive loop. 10 12 CONTINUE When the STEP value is omitted from the expression. . . The name is not restricted to X. It can be a positive integer of up to five digits. DO n X = START. STEP . I 20 CONTINUE In the above example the value of I is printed. It is also possible to have implied DO loops. The repeated part of the program is called the loop body. its default value is set to 1. STOP. Now go to the exercises and work your way through the looping problems. and the number of times this is repeated is set by the START. The loop body is normally indented to support readability of programs.
. 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. 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. a group of 10 students are given marks for a particular essay. the second as MARK (2) and so on. MARK will hold 10 integer values with addresses (subscripts) beginning at 1.. MARK10. can be referred to by a subscript number from 1 to 10.+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. TIME (50) In the above example. 10 SUM = SUM + MARK (1) 25 CONTINUE To do a similar calculation without an array. For example. The easiest way to do this is to state what type of values the array will contain (REAL. CHARACTER). working with groups of values becomes relatively easy. For example. Or this set of values could be given a group or array name of MARK and each individual value. 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).. MARK2 . INTEGER. MARK1. TABLE will hold 25 real values with addresses beginning at l and TIME will hold 50 real values with . called an array element.. The first student's mark is referred to as MARK (1). INTEGER. The marks could be assigned to 10 individual variables each of a different name. you would have to write one huge assignment statement: SUM = MARKl+MARK2+MARK3+.One Dimensional Arrays: An array is a set of related variables that have the same name and are of the same type (REAL. CHARACTER) followed by the name of the array followed by the number of elements in the array enclosed in brackets.
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. the address cannot. The contents of an array element can change. L is the lower subscript value. COUNT READ (1. Sometimes you may want the addresses of an array to begin at a different number than 1. In these instances. 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.addresses beginning at 1. INTEGER NAME1(L:U) REAL NAME2(L:U) where: NAME1 and NAME2 are array names of 6 alphanumeric characters. U is the upper subscript value. you can use an extended form of the declaration. for arrays of any significant size. stating the minimum and maximum values of the subscript.*) NAME (J). N READ *. AGE (I) 10 CONTINUE However. It is important to differentiate between an address of an array element and the contents of an array element. reading from a file is more efficient: COUNT = 15 DO 20 J = 1.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. 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. . 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.*) 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. the first column goes into the array NAME and the second column goes into the array NUMBER. REAL NUMBER (15) READ (1.
Decisions: The IF . If it is false.GT.EQ.AND. If it is true. Each logical expression must be bracketed and the entire logical expression must also be bracketed.C)) THEN END IF IF ((C. The logical expression is something that is true or false. 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: • . (B..GT. . as in the example below.NE. THEN Statement Decisions in FORTRAN are accomplished with an IF-THEN program structure. (B.LT. . 0) The relational operators are: (note that the full stops must be on either side) .C)) THEN IF ((C.GE.LE.LT.EQ. (B. ..D). the block of FORTRAN statements is carried out. Example IF ((A.D).B).C)) THEN .GT.AND. or .OR. the program continues from the statement after the END IF. Note: When using . OR.EQ. .GT.OR. . and.OR.GT. 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 .AND. Usually the block of code affected by the decision is indented to make it stand out from the rest of the program.
(A. 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 . This reverses the expression’s truth.. THEN . ELSE IF .... Block A is executed if the expression is true and Block B is executed if the expression is false.GT. Because there are more blocks with the potential for execution.B)) THEN END IF In English the above expression reads: if A is not greater than B.... In the example below. Example IF (.NOT. ELSE. IF . 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. THEN ...NOT.. This decision structure is used if code is to be executed whether the logical expression is true or false. IF (logical expression) THEN Block A ELSE Block B END IF IF ... If none of the decisions are true. there need to be additional decisions to determine if the block can be executed or not.END IF Logical expressions may be preceded by . THEN...
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. . THEN ELSE IF ... If none of those decisions are true then Block D is executed. You cannot do something like this with ELSE and ELSE IF decision structures. Example IF (A . THEN ELSE This is a third possible decision structure which can be used to make multiple decisions.LT. MIN) MIN = NUMBER Now go to the exercises and work your way through the checking variables exercise.IF .GT. you can eliminate the THEN and the END IF statements.. If the block of code you wish to execute is only one line and there are no additional decisions to be made. 'B is greater than A' IF (NUMBER . B) PRINT*..
Once each piece is working correctly you then put the pieces together to create the whole solution. Example: PRINT*. then M would have a value of 7. as shown in the examples above. . enclosed in parenthesis: answer = functionname (argument1. Also. c and d into the variable M. you must use result of a function call in an assignment statement or a PRINT statement. also called arguments.Functions and Subroutines: Functions and subroutines are FORTRAN's subprograms. the programmer. where x is in radians. a function may have one or more arguments but will only give one result. first write a main program that references all of the subprograms in the desired order and then start writing the subprograms.c. The compiler evaluates the expression. a**2+b**2. c=1 and d=7. One last item to remember. b. and places the answer in the variable Y = SIN (X) + 45 M=MAX(a. do some calculations with those arguments and then return a single result. The general way to activate a function is to use the function name in an expression. the argument for a function does not have to be a variable. Functions: The purpose of a function is to take in a number of values or arguments. There are some functions which are written into FORTRAN and can be used without any special effort by you. argument2. The compiler puts the maximum value of a. To implement functions and subroutines. If a=2. Using subprograms allows you to tackle bite size pieces of a problem individually. The function name is followed by a list of inputs. . . . This is similar to composing an outline for an essay before writing the essay and will help keep you on track.d) C=SQRT ( a* * 2 +b* * 2 ) As shown by the MAX function example above. as shown by the SQRT function example above. sends that value to the SQRT function. 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. It can be an expression or even a constant if you want to reference it again. b=4.b. 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. They are called intrinsic functions. There are over 40 intrinsic functions in FORTRAN and they are mainly concerned with mathematical functions.
it is the squared values (25.C REAL AV.B. 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. Y and z respectively in the function. However.0. AVSQ2 REAL AVRAGE C Enter the data DATA A. • • • • The example program below shows how to write an external function which calculates the average of three numbers. must be declared in the function right after the first line. Any variables the function uses. the value in B (2. and the list of arguments the function takes as inputs. They are started with a line that includes the type of value the function will return. This is how the compiler knows which value to pass back to the main program.B.0.0. When this occurs you may write your own function subprogram. the function name. including the arguments.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. You have to do one thing in the main program to use an external function. The function name is not declared within the function.0) gets transferred to x.0/ . the value in A (5. activating it is just like activating an intrinsic function. Because of this. Now you are ready to write your function.2. in the third reference to the function. You need to declare the function name in the variable declaration section.0) to z.C/5. 9. AVSQ1. function names should not be used as variable names. Once that is done and the function is written. Note also that the variable SUM is used only in the function and therefore is declared only in the 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. Example Program PROGRAM FUNDEM C Declarations for main program REAL A. A function must finish with RETURN and END statements.0. Note the argument list in the main program does not use the same variable names as the argument list in the function. 4.0) to Y and the value in c (3.0) that are transferred to x. You must use the function name in an assignment statement within the function. So in the first reference to the function. Function names follow the same rules as for variable names: less than six letters or numbers and beginning with a letter.3.
SUM SUM = X + Y + Z AVRAGE = SUM /3.AV PRINT *. Keep these in mind when writing your subroutines: . In the main program. subroutine names should be different than those used for variables or functions. AVSQ2 END REAL FUNCTION AVRAGE(X.C) AVSQ1 = AVRAGE(A. Because of this. can return several results.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. Subroutines.'The average of the squares is: '.Y.AVSQ1 PRINT *.'The average of the numbers is: '.'Statistical Analysis' PRINT *.C**2) PRINT *. The inputs and outputs are collectively called the arguments.B.Y.Z. calls to subroutines cannot be placed in an expression.Z) REAL X. on the other hand. Recall the external function example program where the average was called and then squared in one line. However. 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. 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.'The average squared of the numbers: '. there are some rules for using subroutines.B**2.C) **2 AVSQ2 = AVRAGE(A**2. As with functions.C Calculate the average of the numbers AV = AVRAGE(A.B.
and the arguments for the subroutine. The same trick applies to functions.C. SUM.SUMSQ) END SUBROUTINE INPUT(X.SUMSQ) . Example Program PROGRAM SUBDEM REAL A.C.B.B.Y.B. Y.• You do not need to declare the subroutine name in the main program as you do with a function name.Z RETURN END SUBROUTINE CALC(A. The subroutine name is not declared anywhere in the program.Z PRINT *. 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.C. must be declared in the subroutine. Z) REAL X. • One way of indicating which variables are inputs and which are outputs is to put the inputs on the first line.X.B.SUMSQ CALL INPUT( + A.SUMSQ) CALL OUTPUT(SUM.C) CALL CALC(A. use a continuation marker and put the outputs on the second line.Y.'ENTER THREE NUMBERS => ' READ *. They begin with a line that includes the word SUBROUTINE. the name of the subroutine.SUM. you probably have not got your subroutine arguments in the right order in either the main program or in the subroutine. A hint when you are debugging your programs: When extraordinary. All variables used by the subroutine. See the example program for an application of this programming style.SUM. including the arguments.A subroutine is finished off with a RETURN and an END statement. incorrect numbers start appearing from nowhere as your program runs.
SUMSQ) REAL SUM. .B.REAL A. SUMSQ PRINT *.SUMSQ SUM = A + B + C SUMSQ = SUM **2 RETURN END SUBROUTINE OUTPUT(SUM.'The sum of the numbers you entered are: '.SUMSQ RETURN END Now go to the exercises and work your way through the subprograms and functions.SUM.SUM PRINT *.C.'And the square of the sum is:'.
d Specifications w is width of value w is width of value (including negative sign. decimal point and decimal places) of value. READ * and PRINT *. The programmer has had little control over the way in which data can be input and the layout of printed results. Edit Descriptors FORMAT statements contain edit descriptors that provide layout information. . Exponentials are numbers adjusted so they are expressed as: 0. So far only list-directed input and output has been encountered.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. The information is placed in a FORMAT statement.dddd x 10X. d decimal places displayed w characters in width n blanks d significant figures in the mantissa. d The table below shows the edit descriptor you would use to display each value. 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. The italicised letters represent the mantissa and the underlined letters. Input and output statements can contain information on how input data should be interpreted and how output data should be laid out. In FORTRAN notation such a number is written: s0. the exponent.dddd x 10X. w total width (d + 7 ) Character Blanks Exponential Aw nX Ew.
instead of a comma.Value 2099 -72. ed3.186E+06) Cup of Tea Edit Descriptor i4 f6. With formatted output you must put the text message in the format statement. overwriting anything already there start a new page FORMAT(c. The label on a FORMAT statement replaces the * in a PRINT or READ statement.2 e10. ed1.86x105 (+0..'Text message to the screen'. A comma (.ed2 text c is an identifying number for PRINT or READ. Up to this point.. 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. You have to put a carriage control code after a slash to indicate what kind of spacing you want.81 1. ) is usually used to separate edit descriptors and text messages but if a slash / is used.3 a10 The Format Statement The general form of the FORMAT statement is: label Where label edl. any text messages you wanted printed out were included in the PRINT * statement. Only variable names may be included on a formatted PRINT or READ statement. ed2.) The single quotes around the carriage control codes must be there. . subsequent output will be on a new line.
Z . B. Y. 10) A. Data is often input from a file. 20) X. Example Program 5 exemplifies common ways of dealing with files: opening. however WRITE iS used for output rather than PRINT. 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. FMT = 20) X. 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. C WRITE (UNIT = 2. 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. 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. acted on by a FORTRAN program and output to a file. 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. Y. The statements for input and output must include details of how and where to input data from and output to. reading from and writing to. File Handling So far the programs written have taken input data from the keyboard and the results have been displayed on the computer screen. C READ (1. READ * may be expanded to include these controls. Z WRITE (2.Formatted Input Getting a formatted READ to work correctly is very tricky to do. closing. FMT = 10) A. Every blank specified in the FORMAT statement must be present and the values have to appear exactly as specified in the FORMAT statement. 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. B.
GO TO statements can be dangerous because they tend to create jumps in control which are hard to follow. FMT = 10) A.C. ALL DATA READ' . B. For example: WRITE (2. C The more usual concise form. FMT=20) X.Unit identifier Every control list must contain a unit identifier. and C GO TO 80 99 PRINT *. C Asterisk (*) means list-directed formatting.C. The number 5 represents keyboard input and 6 represents screen output. C the FORMAT statement it is at label 10 READ (UNIT=1. A. If the unit identifier is first in the control list the UNIT = may be omitted. A.B. In the example below. Example: 80 c READ(l. no formatting If the format identifier is second in the control list the FMT = may be omitted.B. FMT = *) A.*) A. 10) A. Example: READ (1. It is wise to keep use of GO TO statements to a minimum.C is another way of writing READ*. Likewise. no more data is transferred and the control of the program jumps to the label specified in the READ statement. WRITE(6.B. Y. End-of-file condition Only one end-of-file condition may appear in the control list. Format identifier This identifies how the data is organised either by reference to a FORMAT statement or an asterisk indicating list-directed format. In other words. Example: READ (UNIT=l.C do something with A. When the READ statement reaches the end of the data file without an error occurring. It is this that identifies the location of the file or device to be accessed.B. So READ(5. B.*) A.B. a GO TO statement is used to continue reading from the file until the file is completely read. B. Z You may choose any number for a unit identifier except for two reserved values that generally have predefined meanings.C is another way of writing PRINT*.*.END=99)A. B.
the pointer is on the line with 18 in it. the pointer gets positioned on the line with 15 in it because it was told to look for three values to fill A.B. did not need the fourth value. The second time the READ statement is executed. The compiler found the three values it needed on a single line. Again. The pointer moved on because the line had been examined. For example. looked like this: 12. When it found all the values it needed the pointer got positioned on the next fresh line. So after the first read statement. .ERR=100. ERROR ON READING. The third time the READ statement is executed. say that the file accessed by the READ statement above. keeping track of what line has been read and what line has not. the input/output is stopped and the program jumps to the label given in the error specifier. 14 15 16 17 18 19 20 21 22 23 When the file is initially opened. the compiler was told to look for three values.Error condition If some error occurs on input/output and there is an error specifier. in this case the one beginning with 18.END=200)A. a pointer is placed at the top of the file. B and c and it found all it needed on the first line. Example READ(l. The pointer will move for two reasons: l) after a line has been looked at or 2) if the compiler needs more values. the pointer is left on the line beginning with 22. but moved on anyway. but they were not on the same line so the pointer moved on to find enough values.*. 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. the pointer moves through the file. 21. 13. As the file is read.C 100 PRINT *.
This is also a character entity which must be enclosed in quotes OLD the file to be opened already exists. If later on in the program you want to move the pointer back to the top of the file. ERR . therefore enclosed in quotes STATUS = character. the REWIND statement can be used.If an error condition occurs while the file is being opened. STATUS . NEW the named file must not already exist. UNKNOWN The file may or may not exist. therefore enclosed in quotes There are more file specifications which can be looked up in one of the recommended texts. Implied DO loops describe a method of reading all the data. 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. The filename is considered a character entity so it must be enclosed in quotes. FILE . The CLOSE statement: The CLOSE statement disconnects a file: CLOSE([UNIT=] number) .This specifies the name of the file to be opened.During the fourth time the READ statement is executed. the program will have an error. A file is created and opened. 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. filespec list) where the file specifications list can be some of the following: ERR = label FILE = character. 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. the program jumps to the label. . OPEN(UNIT = number.
or positive Assigns a statement number to a variable Transfers control to a statement specified by a variable.1416 NUMBER = 0 MAJOR = ' CPSC ' Z FLAG =. depending on whether value of an arithmetic expression is negative. 1995/ END IF (X. in conjunction with ASSIGN statement Example of Usage Arithmetic IF IF (X-Y) 30. zero. 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 . T. 'NUMBER IS 0' ELSE PRINT *. TRUE. INIT*1. 50 ASSIGN ASSIGN 50 TO N Assigned GO TO GO TO N Assignment Assigns a value to a variable PI = 3. X.EQ. YEAR COMMON / INFO / MONTH.Glossary of FORTRAN 77 Statements STATEMENT Description Transfers control. 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. YEAR /12. 'NEGATIVE NUMBER' END IF CALL CONVER (A. YEAR DATA MONTH. depending on truth or falsity of a logical expression. Y) CHARACTER*10 NAME. BACKSPACE 12 INTEGER MONTH. 0) THEN PRINT *. 40 . O) THEN RESULT = SQRT(X) ELSE IF (X .GT.
(X(I).5*0/ DIMENSION MAT(5.COMMON Establishes blank or named common areas COMMON ALPHA. N DOUBLE PRECISION A. 30. 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. (ALPHA. 40) CLASS CONTINUE DATA DIMENSION DO 5 CONTINUE DATA PI. YEAR COMPLEX Z. MAT (5. W. 20.5) COMPLEX Specifies complex type Transfers control to one of several statements.5) COMMON / INFO / MONTH. 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. END DO ENTRY END See block IF statement ENDFILE 12 See WHILE statement ENTRY POLY (X) EQUIVALENCE(X.Y). MAT (5. B.T(3)) EQUIVALENCE EXTERNAL EXTERNAL F.I=1. 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.5).5) /3.A. BETA. LIST(20) DO 5 I=1.14. QUAD .
N-Z). ALPHA. STATUS = 'OLD') PARAMETER (LIM = 100. 'X = '. *. M.20) INTRINSIC SIN. N) GO TO 100 IMPLICIT REAL (L.FORMAT Defines a list of descriptors 20 FORMAT (1X. Z READ (12. Q. 317)'. NUM. END = 20) HOURS.GT. RATE PARAMETER Defines parameters PAUSE Interrupts program execution. DSQRT LOGICAL P.5 PAUSE PAUSE 'PROGRAM PAUSE' PRINT *. NAME =FNAME) INTEGER X. RATE =1. TABLE(10. CLASS. F7.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 . X PRINT * PRINT '(1X. 0) DISC = SQRT(DISC) OPEN Opens a file OPEN(UNIT = 12. program may be restarted PRINT Output statement PROGRAM Program heading READ Input statement . M + N-e PROGRAM WAGES READ *. TABLE(4. 2F8. N. FILE = FNAME. BETA READ '(15.2)'. INTEGER (A-K) INQUIRE (EXIST = FLAG.3) FUNCTION AVE(X. 'ROOTS ARE'.
'(1X.Y) = X**2 + Y**2 STOP STOP 'PROGRAM HALTS' SUBROUTINE CONVER (U. 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 . B. MAT(10. C WRITE (12. 316)') N1.10) RETURN RETURN 2 REWIND 12 SAVE X.REAL Specifies real type REAL NUM. Y. PHI) WRITE (*. RHO.*) A. V. GAMMA. NUM SAVE F(X. N2.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview.