You are on page 1of 19


Chemical Engineering Department, Middle East Technical University


Course: ChE 352, Mathematical Modelling in Chemical Engineering
Instructor: Prof.Dr. Nevin Selçuk
Assistant: Necip Berker Üner

1) Introduction
FORTRAN is the oldest programming language, developed in 1957. It is renewed many times and the
latest version is FORTRAN 2008. FORTRAN set the foundations of scientific computing with the version 77
and it is still the most widely used scientific language, due to its computing speed and extensive libraries
on the internet (subprograms, see Chapter 7). This course will use the FORTRAN 95 edition, which is the
upgraded version of 77 and includes some extensions to the 90 version.

a) Execution of a Program
Execution involves several steps. After establishing an algorithm, the source code is written with a
text editor. Then compiler software translates the code into a machine code. Finally the code is
executed. For compiling we will use the “Silverfrost Plato FTN95 Personal Edition” software, which is free
and can be downloaded from: .
Another option is “Force 2.0”. But it is not compatible with some of the new pcs.

Plato FTN95
This compiler can create different formats of file. The ones that we are going to use is the free
format files with .f95 extension. The old 77 format is named as the fixed format which restricts
the programmer with paragraphs at the beginning of each row and a maximum row length of 66
characters. The free format is like a text file with no paragraph requirement and a maximum row
length of 128 characters. Figure 1 shows the interface of the program.

b) Notes on Code Writing

Use spaces and indentation to make the code readable
Use explanations, or in programming terminology: comments (explained in chapter 3), to
make the code understandable.


Commands in blue. Line and column numbers. Execute button also automatically compiles. Multiple tabs can be opened. Compiling log. Shows errors and warnings after compiling and building. The first three buttons represent compile. Figure 1. Checkmate is the default. Compiler Setup. which is a midstep between compiling and execution. Slower but safer. FTN95 Interface Text code. 2 . operative symbols in red and comments are in green. values and variables in black.exe file. The Build Toolbar. Build function generates an . build and execute.Program Tab.

Anything which has pre-defined attributes in FORTRAN. which are integer. These define the value of a variable. for example: -45. The code must be finalized by END statement.23043 Double Precision: stores values with 11 decimals. In part d. rounds the 6th decimal up or down. (In this course always use DOUBLE PRECISION instead of REAL!) Character: stores a text instead of values. rounds the 12th decimal up or down for example: -45. for example :32. The first four is important for us. There are also derived types and adjusted precision. This command is not necessary. 49802. No longer than 31 characters. Constants. which are out of the scope of this tutorial. Operators a) Starting and ending the program With the “PROGRAM name” command. logical. - 1 Integer Type: stores values without decimals. real. for example: “root” or ‘root’. an example is shown. Its use can be seen in Figure 1.23043778221. the program starts.2) General Code Layout i) ii) iii) iv) Program Name Type Declarations (Chapter 3) File Management (Chapter 8) Initialization & Input (Chapter 3) v) vi) vii) viii) Main Calculations Output (Chapter 8) End Subprograms & Functions (Chapter 7) 3) Types. Names are case insensitive! c) Variable Types There are 6 intrinsic1 types in FORTRAN. 3 . b) Variable Names     Composed of letters and/or digits and/or underscores. First character must be a letter. complex. “name” is the given title of the program. Variables. and character.-9 Real Type: stores values with 5 decimals. double precision.

COEFFICIENT2 CHARACTER(LEN=5) :: LINE The LEN statement defines the maximum string length.14159 e) Arithmetic Operations. The command can be placed above the type declaration block. PARAMETER :: PI = 3. rounded after the 17th. The mathematical precedence of the operators is important in FORTRAN since all equations are written is a linear form. The second code shows an example of giving certain character intervals to a type of variables. R_OLD DOUBLE PRECISION :: COEFFICIENT1.5 LINE = ’Mark‘ Note that the character strings are written in quotes (“ or ‘). but preferentially at the beginning. such as +.67 COEFFICIENT1 = 240. For example: ( ) corresponds to 4 * (3 + 7)-2**4/2. But for exponentiation ** is used instead of ^. one can write the following commands at any row of the code. after the PROGRAM statement: IMPLICIT NONE IMPLICIT DOUBLE PRECISION (A-H. After this code type of every variable must be declared. They are used as in the following context2: INTEGER :: ITERATION.-. The PARAMETER command serve for defining the value of a constant. d) Implicit Statements and the PARAMETER Command In FORTRAN all variables starting with i. m or n are considered as integer and the remaining is real.O-Z) The first code removes all available definitions. l. REAL. j.These commands constitute the type decleration part.* and /. Simple Input & Output Basic operators are used as they are. 4 . 2 REAL and DOUBLE PRECISION can also be defined as REAL(KIND=1) and REAL(KIND=2). Values may be given to these variables such as: NUM = 1 R_OLD = 5. NUM REAL :: RESULT. REAL(KIND=3) is another definition which allows 16 decimals. To remove this intrinsic definition. k. yields 4 * 10 – 16 / 2 and thus 32.

NOT. such as A = 3. The important logical operators are: . “ command is its counterpart for output. the execution screen comes up as: Figure 2. As seen from the rows 4 and 10.RES1. there is an exception. ."RES2=". it can output texts also.RES2 PRINT*./7 f) instead of A = 3/7 Logical and Relational Operators These are used in conditional statements. When this program is run. . The value of A is given during execution via the READ statement."INPUT A" READ*. RES1. The Execution Screen Integer division leads to different values. such as the IF commands.D. and it is evaluated from right to left. PRINT statement displays the values of variables in the monitor after execution.AND. is written as 3**2**3. "RES1=". “ statement is a basic input command and the “ PRINT*. 5 . But any operation between a real and an integer variable lead a real result. Note that the semicolon operator allows multiple statements per row. RES2 END PROGRAM TEST The “ READ*. Integer to integer division will give an integer result and inexact division cause a loss of precision since integers do not have decimals. For example: PROGRAM TEST INTEGER :: A.OR. A B=3 C=7 . To avoid integer division.B REAL :: C. Integer divisions need some special care.D=3 RES1 = A/B RES2 = C/D PRINT*.For multiple exponentiations. the decimal point can be put after integers.

6 . These comments can also be used on the same row with statements.& 2 * A * B * cos(alpha)) which is equal to: C = SQRT(A ** 2 + B ** 2 . Natural logarithm function Logarithm function with the base of ten (common logarithm) Exponential function Absolute value of the numerical argument X Square root function h) Comments and Continuation Lines The exclamation mark “!” can be used to input comments. The most important ones may be listed as: SIN(X) LOG(X) LOG10(X) EXP(X) ABS(X) SQRT(X) Sine function. For example C = SQRT(A ** 2 + B ** 2 . If a statement is too long to fit in 128 characters.The relational operators are renewed in F90.GT. then the “&” mark is added to the end of the line. Other trigonometric functions are available and similarly used. (greater than) are replaced with: < less than <= less than or equal to > greater than >= greater or equal to == equal to /= not equal to g) Intrinsic Functions There are lots of mathematical and non-mathematical functions in F90. textual operators such as . The usage of “!” can be seen in Figure 1.2 * A * B * cos(alpha)) *From now on the chapters will be explained via examples. Anything written after “!” will be considered as a comment in FORTRAN. and then the continuing part of the statement is written on the next line.

"INPUT THE LOWEST NUMBER" READ*. X2 7 . NUMHIGH Check if NUMLOW is even IF(MOD(NUMLOW. ESUM END PROGRAM EVEN_SUM The example above demonstrates the two way conditioning with the basic combination of IF and GO TO statements. C.NUMLOW.1: Write a program to find the sum of even numbers between two integers PROGRAM EVEN_SUM INTEGER :: ESUM. Example-4. then IF blocks should be used. "SUM OF EVEN NUMBERS IS:". which calculates the remainder of the integer division of NUMLOW by 2. X.2)==1) NUMLOW=NUMLOW+1 ! 10 ! IF loop to find the sum ESUM=0 ESUM=ESUM+NUMLOW NUMLOW=NUMLOW+2 IF(NUMLOW<=NUMHIGH) GO TO 10 Output PRINT*.4) IF Statements Frequently used with GO TO statement. B. If the outcome of an conditional statement is multiple.NUMHIGH ! The lowest and highest numbers ! PRINT*.2: Write a program to input three coefficients of the quadratic equation and find and print the possible real roots using the block IF structure. D. X1. NUMLOW PRINT*. PROGRAM QUADRATIC_ROOTS IMPLICIT NONE REAL :: A. Note the use of MOD intrinsic function. An example is shown below. Example-4."INPUT THE HIGHEST NUMBER" READ*.

The reason is. it may not be equal (Computers are not always exact. Although the precision of the variables are set to 5 numbers after the decimal. D ! IF-THEN-ELSE structure IF(A<=0. After this condition. A. comparing floating point quantities3 may be erroneous. C ! The discriminant: D D=B**2-4*A*C PRINT*.! The coefficients 10 READ*.'INPUT COEFFICIENTS ARE:'.X2 ENDIF GO TO 10 END PROGRAM QUADRATIC_ROOTS Note that the discriminant is not zero for coincident roots. Plato stores more than that. That line only shows an interval between -10-5 and 10-5. 8 . special care must be taken to place the blocks in each other. B. An IF block starts with a regular IF statement and continues with the THEN statement. as can be seen from first IF of the IF-THEN-ELSE structure.'ONE REAL ROOT EXISTS AND IT IS:'. The first (the outer) block must have its ENDIF statement at the end.). A. C PRINT*. in Plato. it may print the real variable D as 0. Since the accuracy after 10-5 is not necessary for this example. Hence.00000 but when comparing it to an actual zero. 'NO REAL ROOTS EXISTS' ELSE IF(ABS(D)<1E-5) THEN X=-B/(2*A) PRINT*. 3 Values with decimals. each IF statement includes a relational or logical condition with ELSE IF and the THEN statement. The block should be ended with ENDIF. setting an interval is a practical solution.X ELSE X1=(-B-SQRT(D))/(2*A) X2=(-B+SQRT(D))/(2*A) PRINT*. B.0) THEN STOP ELSE IF(D<0) THEN PRINT*. When multiple IF blocks are used.X1.'TWO REAL ROOTS EXISTS AND THEY ARE'. The STOP statement can be used to terminate the program at specific points. except the last condition is only comprised of ELSE.

NUMHIGH.1."INPUT THE LOWEST NUMBER" READ*. It starts from the lowest number.NUMLOW. NUMHIGH ! Check if NUMLOW is even IF(MOD(NUMLOW. A basic example is shown below. It increases I by the amount of 2.1 with using DO loops.1: Rewrite Example 4. The ENDDO statements works as the lines NUMLOW=NUMLOW+2 IF(NUMLOW<=NUMHIGH) GO TO 10 in Example-4. PROGRAM EVEN_SUM_II INTEGER :: ESUM."INPUT THE HIGHEST NUMBER" READ*. 9 . and continues to perform the loop until I ≥ NUMHIGH. Thus the DO statement provides an easy way of performing loops. then the below commands are performed. "SUM OF EVEN NUMBERS IS:".NUMHIGH.LOWBOUN ! The lowest and highest numbers PRINT*. ESUM END PROGRAM EVEN_SUM_II “I” is the counter for the DO loop. 2)==1) NUMLOW=NUMLOW+1 ! Do loop to find the sum ESUM=0 DO I= NUMLOW. NUMLOW PRINT*. The next example shows the way of using nested loops. 2 ESUM=ESUM+I ENDDO ! Output PRINT*. Example -5.5) DO Loops DO loops are useful when recycling a part of the code for different cases and variables.

some extensions to this chapter. 1. -0.5.TERM. During lectures. 0. 1 by using the first 10 terms of the series for each value of x.EXPX.0 and ending at 1.5 ! Calculate the e^x using the first 10 terms EXPX=1+X DO ITERM=2. 9 ! The factorial of a term FACT=1 DO M=ITERM.0.5.X. -1 FACT=FACT*M ENDDO ! Compute the term and add it to the sum TERM=X**ITERM/FACT EXPX=EXPX+TERM ENDDO ! Print out the result for an x value and cycle PRINT*. 0. starting from -1.Example-5.0. PROGRAM POWEREXP DOUBLE PRECISION :: X.0. such as endless DO loops.0.FACT ! GENERATE THE X VALUES DO X= -1.5.2: Evaluate the power series of ex For the x values -1.EXP(X) ENDDO END PROGRAM POWEREXP The DO loops counter is X and it is incremented by 0. 1. 0. 10 . the EXIT command and CASE constructs will be demonstrated.EXPX.

Let the program terminate when a zero value of x is read in. a2. starting from the 0th and ending at the 8th.6) Arrays An array means a set of variables with subscripts. N POLY=POLY*X+A(I) ENDDO 11 . For example a 1-D array stand for a vector and a 2-D array represents a matrix. the coefficients and X READ*. N. The element on the 2nd row and 4th column is shown as AMATRIX(2.-10). Arrays are declared similar in a similar way to single variables.1: Write a program to evaluate the polynomial expression for given values of n. Similarly it has 41 columns. which is based on the nesting: ( (( ) ) ) PROGRAM POLYNOMIAL_EVALUATION REAL :: A(25).A(N).POLY."WHEN X=0" STOP ENDIF Horner's Method POLY=A(1) DO I=2. X IF (X==0) THEN PRINT*.4).-30:10) The type of the elements of an array must be declared. an using various values of x which are read in . It is also a 2d matrix with 9 rows. (A(J).4) DOUBLE PRECISION :: BLOCK(0:8. REAL :: VECT(5) INTEGER :: AMATRIX(3. The element in the middle is designated as BLOCK(4. In engineering context a maximum of 4-D arrays are used. The first array consists of 5 real elements. Fortran 95 is limited to 7-D.X ! 10 ! Input the order."F(X)=". Example-6. Use the Horner’s method.J=1. The second one is a matrix with 3 rows and 4 columns. … . The program can be limited to n ≤ 25. The first element is designated as VECT(1) and the last one is VECT(5). N) READ*. a1. The third array is an example of adjustable bounds.

then every element of the array A is read in one line.L)=M(L. DIMENSION (:.J) ENDDO ! Transposition DO K=1. Example-6.(MT(L. First N.L=1.L).MT ! Input the number of rows & columns ! READ*. J Allocate the matrix size ALLOCATE (M(I.I MT(K.2: Write a program to take the transpose of any matrix.L=1.J PRINT*.J DO L=1. ALLOCATABLE.L).K) ENDDO ENDDO PRINT*.:) :: M. ((M(K.' ' ! Output DO L=1.K=1.J).(M(K.I PRINT*.K=1.I)) ! Read the values and print the matrix READ*.I) DO K=1.X GO TO 10 END PROGRAM POLYNOMIAL_EVALUATION The READ statement on line 6 is written an implied DO structure. I.J).K).POLY.PRINT*. PROGRAM TRANSPOSITION REAL.I) ENDDO END PROGRAM TRANSPOSITION 12 ."WHEN X=".MT(J."F(X)=".

7) Functions and Subroutines Some programs may need a block of computations to be repeated.(Y<=0). Y. 'THE AREA IS:'. Example-7. the size can be adjusted on each time we run the program. Use a FUNCTION type subprogram. Once a library of subprograms is established. Their examples are given below.OR. Y. PROGRAM AREA_TRIANGLE_SIDES PRINT*. In this code.1: Write a program which calculates the area of a triangle when the side lengths of a triangle are given. In Example-6. Writing the same of block of computation more than once generally makes the program hard to read and trace. using DO loops is very important in automatically assigning values to array elements.In this example allocatable arrays are used.1. the computation can be written as a subprogram and can be placed outside of the main code. X.OR. Another reason for using subprograms is to create a certain library of basic computations. Z) IF(A<=0) THEN PRINT*. The main code can call the subprogram and make it work for different sets of variables. the programmer can write any new relevant code faster. As seen in the examples of this chapter. we assumed a maximum size of the array. 'INPUT THE SIDE LENGHTS' READ*. There is also the DATA statement which allows this in a semi-manual manner. In such a case. There are two types of subprograms: functions and subroutines. but it will not be explained here.(Z<=0)) STOP ! Call the function & output the results A=AREA(X. A ENDIF END PROGRAM AREA_TRIANGLE_SIDES 13 . Simple DO loops and implied DO loops (nested & implied on line 14) are used to create a neat input-output structure. which are used repeatedly in the working field of the programmer. Z ! Build a checking mechanism to stop the program if negative side lengths are given IF((X<=0). 'NO SUCH TRIANGLE EXISTS' ELSE PRINT*.

The RETURN command works like the STOP command in a main program. 10 PROGRAM AVERAGE_ARRAY REAL :: A(100). do not have to have the same names used in program. RE-INPUT K:' GO TO 10 ENDIF 14 . B. Note that the dummy arguments of the function AREA. It might have type declaration lines after the FUNCTION statement. K ! Check the array size IF(K>=100) THEN WRITE(*.*) 'ARRAY SIZE IS LIMITED TO 100. X corresponds to A. Use a SUBROUTINE type subprogram.!-------. then involves computations and terminates with END. Also note that the type of the function name is declared since it has a value assigned.MEAN WRITE(*. Y and Z. In a FUNCTION type subprogram the name of the function must have a value assigned.Subprogram for calculating the area of the triangle from side lengths REAL FUNCTION AREA(A. which are A. B and C. all variables (A. B.5*(A+B+C) AREA=SQRT(S*(S-A)*(S-B)*(S-C)) END Line 8 demonstrates the use of multiple logical operators. It starts with the FUNCTION command.2: Write a program to calculate the average of a real array. The dummy variables are terminated after the subprogram is executed. C) AREA=0 ! Check the existence of the triangle IF(A>=B+C) RETURN IF(B>=A+C) RETURN IF(C>=A+B) RETURN ! Find the area if the triangle exists S=0. since only its value is sent to the main program. C. in this case. Y and Z correspond similarly to B and C respectively. Example-7. X. AREA and S) are predefined as real. K:' READ*. Only their order is important. Remember that the dummy variables cannot be chosen as array elements. having maximum 100 elements. The subprogram’s structure is the same with the main program. but in this case.*) 'INPUT ARRAY SIZE.

Its name does not have value assigned. (A(I). Example-7. all of it variables are processed and their values are kept in the main program.3: Write a program to evaluate ∫ ∫ numerically with trapezoidal integration [( ) ∫ ( ) where ( ) ( ) ( ) ( ( ) ) ( )] . It will be treated in detail in Chapter 8. I=1. but normally it is more capable.K) ! Call the subroutine to find the average CALL AVE(MEAN.K.N.*) 'THE AVERAGE IS:'.MEAN END !--------Subroutine for finding the average of a 1-D array of max. 15 . 100 elements SUBROUTINE AVE(MEAN. hence they are more frequently used.A) WRITE(*.! Input the array elements READ*. It needs the CALL statement in the main program to work. Instead of PRINT command. SUBROUTINEs are more capable then FUNCTIONs.MEAN SUM=0 DO I=1.A) REAL ::A(100).N SUM=SUM+A(I) ENDDO MEAN=SUM/N END The SUBROUTINE type subprogram is quite different than the FUNCTION type. It does the same job in this program. WRITE command is used here.

N)+TRAPEZ(FX2.B.'THE APPROXIMATE AREA IS:'.FX2 ! Input n PRINT*.0. two subprograms.N) H=(B-A)/N SUM=0 J=N-1 DO I=1. as dummy variables. 16 .'INPUT THE NUMBER OF INTERVALS' READ*. APPROXINT END PROGRAM TRAPEZOIDAL !-------.Subprogram to calculate (cos(x))^2 FUNCTION FX2(X) FX2=(COS(X))**2 END !-------.5.N) PRINT*.PROGRAM TRAPEZOIDAL EXTERNAL FX1.0.Subprogram to find the integral of a function with the trapezoidal rule FUNCTION TRAPEZ(FX. N ! Approximate the integral APPROXINT=TRAPEZ(FX1.0. Since FUNCTION TRAPEZ uses FX1 and FX2.4.0.Subprogram to calculate (sin(x))^2 FUNCTION FX1(X) FX1=(SIN(X))**2 END !-------.A.0.J SUM=SUM+FX(A+I*H) ENDDO TRAPEZ=(FX(A)+FX(B)+SUM*2)*(H/2) END This program demonstrates the linking of subprograms with the EXTERNAL statement.1. the main program must be acknowledged.

INTRINSIC. 8) Files and Formatted Output For a neat and processable output.10) "Numbers". N ! Use the functions and create the output file DO I=1.STIRLING.ERR ENDDO ! Output formats 10 20 FORMAT(A10. INTENT. "Standard Results".1: Write a program to calculate the factorial n! using both the standard method and Stirling’s approximation: ( ) Tabulate the results.txt". "Relative Percent Error" READ*. I24. ENTRY.Subprograms are an important part of programming. RECURSIVE and many more. only the basic use of them will be demonstrated through an example. In FORTRAN there are many other commands and principles related to subprograms such as EQUIVALENCE.STATUS="REPLACE") WRITE(5.FILE="Factorial Sheet.20) I. N STANDARD=IFACT(I) STIRLING=FACTST(I) ERR=ABS(STIRLING-STANDARD)/STANDARD*100 WRITE(5. COMMON. 2(F24. Example-8. INTERNAL. files and formatted output must be used. 3(A24)) FORMAT(I10. PROGRAM FACTORIAL INTEGER :: STANDARD ! Open the output file and input the factorial limit OPEN(5. BLOCK DATA. "Stirling's Results".5)) END PROGRAM FACTORIAL !-------.Subprogram to calculate a factorial INTEGER FUNCTION IFACT(N) IPROD=1 IFACT=1 17 . Since both file management and formats are broad topics.STANDARD.

14159) TERM2=FLOAT(N)**(FLOAT(N)+0. N IPROD=IPROD*I ENDDO IFACT=IPROD 50 END !-------. The values are always right adjusted.” command. The numbers after A and I show the number of spaces (a blank made by the “space” button in a text editor) that the variable is written on. Table 1: Table of Factorials A DO loop is used to print the output row by row. The intrinsic function FLOAT is there to convert integers into reals. In this example each WRITE statement has 2 numbers. The second one is either 10 or 20. the titles of the table columns are printed on the file (line 7.Subprogram to approximate a factorial by using Stirling's formula REAL FUNCTION FACTST(N) TERM1=SQRT(2*3. there are two numbers 18 . The first star means that the output will be given on the black execution screen (not on any file) and the second one indicates that the output format is the default one used by the unformatted “PRINT*. indicating the numbers of FORMAT statements. The OPEN statement creates a text file named “Factorial Sheet” with the . “I” is for writing integers and “F” is for real and double precision variables. For file numbering. There are four texts and they are written by using the FORMAT statement numbered as 10. “A” is for writing character variables or texts.txt format and numbers it as 5.*)” command is used. At the beginning. Note that FORMAT statements have some letters inside their parentheses.IF(N<=1) GO TO 50 DO I=2.2 “WRITE(*. use positive integers except 1 and 2. the number of the opened file. the first WRITE statement).5) TERM3=EXP(-FLOAT(N)) FACTST=TERM1*TERM2*TERM3 END The result is tabulated in Table 1. first one is 5. However. This number is used by WRITE statements. Remember that in Example 7.

14159 as 3. after running Example 8. Many of them include exercises of applying numerical methods. Although programming and numerical methods has diverse context. to create diagrams and plots. For example with F5. The data on files can be read by a graphing program. [4] REA’s Problem Solvers: Numerical Analysis. Programming with FORTRAN77. 1990. Fortran 90 for Fortran 77 Programmers. Research & Education Association. ParaView or even EXCEL. References: [1] van Mourik T.. Writing the output on a file is important. [3] Tokdemir F. the basic tools given in this tutorial is sufficient for solving many engineering problems numerically. 1993. Revised Edition. 2002.1. (Dir.141 since the decimal point also takes up a space. University College London. 2002 E-Book is available and free. For example. many books and e-books are available.. such as Tecplot. a plot of the relative percent error can be drawn to visualize its continuously decreasing trend. [2] Page C. The first one is the space indicator and the second one the number of decimals displayed.. Fortran 90/95 Programming Manual. 19 . ODTÜ-Ankara. by M. Fogiel).after F.3 will display 3. 9) Epilogue For FORTRAN programming.. since it allows processing of the data. E-Book is available and free.