fortran 95 an introductory course

24
1 FORTRAN 95 an introductory course Chapter 1 Getting started 1.1 Introduction Computers are controlled by software (or programs). Whenever the computer is switched on there is always a program running. This may only be controlling the display, waiting for input from the keyboard , the mouse or via a network, or it may be a more specific piece of software that is running such as a spreadsheet, a word processing package or a mail program such as Pegasus. This short course in FORTRAN 95 will give you an introduction to some of the basic ideas used in most programming languages. In many respects the language we are using is irrelevant, though FORTRAN is more suited for scientific and numerical computing rather than, say, constructing a Web page, where Java might be more appropriate. 1.2 Plato At City we are using Salford FORTRAN 95. In order to construct a program we need to be able to enter the instructions (compose, edit) and then transform them (compile and link) into a form that can be acted upon (run) by the computer. The finished program will also need to be saved for further use. To carry out this process the Salford company have written an Integrated Development Environment (IDE) called Plato. Since during the process of constructing and running a program you will make many mistakes Plato has been designed to help you identify your errors (debugging). 1.3 Getting started Assuming that you are logged in to the City University system you need to locate the Salford software and run Plato. To do this you need to click the following on the desktop: Start Programs Programming Languages Salford Software Salford Plato IDE This should open the Salford Plato window, you are now ready to start a new program or edit one you prepared earlier. 1.4 Creating a new program To create a new program: Select: File (from the top line) Select: New You should now have a blank white window ready for entering your program Before starting to type in your program it is best to give your program a name by saving it. (though at this stage there is nothing to save) Select: File SaveAs Enter a file name: prog1.f95 You can use any name instead of prog1 for your program but the extension .f95 is essential. If you wish to save your program in a different directory then this is possible using the dialogue box. 1 1.5 Task 1 - program simple The following simple program illustrates the basic steps involved in preparing and running a program using Plato As in 1.4 above start a new program and name it task1.f95 Type in the following program: NB. Plato will automatically add the bold face to certain words. (see 1.6) The program now needs to be compiled, linked and run. These three steps can be done with one click of the [execute] button. This is the fourth button from the right hand side of the button bar and has a single black arrow head icon. Execute the program. If successful: You will be presented with a black window and a flashing cursor. The program is now running and waiting for you to input a number Type in a number (4 say) and press the enter key Your program should add one to the number and then write out the result (5 in this case). Press enter to return to your program 1 The U drive is your own personal space on the City system and programs saved there will be available the next time you logon. The D drive is local to your machine and work saved there will be lost when you logout or at best at the end of the day. You can save programs on the A drive if you insert a floppy disc into your computer program simple real x read(*,*) x x=x+1 write(*,*) x end simple

Upload: others

Post on 28-Jan-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

1

FORTRAN 95an introductory course

Chapter 1Getting started

1.1 Introduction

Computers are controlled by software (or programs).Whenever the computer is switched on there is always aprogram running. This may only be controlling the display,waiting for input from the keyboard , the mouse or via anetwork, or it may be a more specific piece of software thatis running such as a spreadsheet, a word processing packageor a mail program such as Pegasus.

This short course in FORTRAN 95 will give you anintroduction to some of the basic ideas used in mostprogramming languages. In many respects the language weare using is irrelevant, though FORTRAN is more suited forscientific and numerical computing rather than, say,constructing a Web page, where Java might be moreappropriate.

1.2 Plato

At City we are using Salford FORTRAN 95. In order toconstruct a program we need to be able to enter theinstructions (compose, edit) and then transform them(compile and link) into a form that can be acted upon (run)by the computer. The finished program will also need to besaved for further use. To carry out this process the Salfordcompany have written an Integrated DevelopmentEnvironment (IDE) called Plato. Since during the processof constructing and running a program you will make manymistakes Plato has been designed to help you identify yourerrors (debugging).

1.3 Getting started

Assuming that you are logged in to the City Universitysystem you need to locate the Salford software and runPlato. To do this you need to click the following on thedesktop:

• Start• Programs• Programming Languages• Salford Software• Salford Plato IDE

This should open the Salford Plato window, you are nowready to start a new program or edit one you preparedearlier.

1.4 Creating a new program

To create a new program:• Select: File (from the top line)

• Select: New

You should now have a blank white window ready forentering your program

Before starting to type in your program it is best to giveyour program a name by saving it. (though at this stage thereis nothing to save)

• Select: File SaveAs• Enter a file name: prog1.f95

You can use any name instead of prog1 for your programbut the extension .f95 is essential.

If you wish to save your program in a different directorythen this is possible using the dialogue box.1

1.5 Task 1 - program simple

The following simple program illustrates the basic stepsinvolved in preparing and running a program using Plato

• As in 1.4 above start a new program and name ittask1.f95

• Type in the following program:

NB. Plato will automatically add the bold face to certainwords. (see 1.6)

• The program now needs to be compiled, linked andrun. These three steps can be done with one click ofthe [execute] button. This is the fourth button fromthe right hand side of the button bar and has a singleblack arrow head icon.

• Execute the program.

If successful:

• You will be presented with a black windowand a flashing cursor.

• The program is now running and waiting foryou to input a number

• Type in a number (4 say) and press the enterkey

• Your program should add one to the numberand then write out the result (5 in this case).

• Press enter to return to your program

1 The U drive is your own personal space on the City system andprograms saved there will be available the next time you logon. The Ddrive is local to your machine and work saved there will be lost whenyou logout or at best at the end of the day. You can save programs onthe A drive if you insert a floppy disc into your computer

program simplereal xread(*,*) xx=x+1write(*,*) xend simple

2

• Select [OK ] to get rid of the Build successfulwindow or RUN to run your program again

If unsuccessful:

• You will get a Build Failed window insteadof the black input window.

• Click the [Details] button to get informationon your error(s)

• This will open an Error and Warningwindow

• Click on the first message in the error andwarning window, this will highlight theposition of your error in the program Thistogether with the message should help youcorrect your program

• Correct all errors• Try to re-execute your program

• Save your program

Although Plato should automatically save theprogram every time you try to compile a newversion, just to make sure you should save theprogram using the save button (third from the lefton the top button bar).

1.6 Details of program simple in task 1

The program simple in 1.5 consists of six lines eachcarrying out a specific task in the order in which they arewritten. The words in bold face (such as real) are reservedwords and have a special meaning. Plato will change theseto bold automatically.• program: this is optional, its purpose is to enable you

to identify the program. It is followed by a space and aname which can be any string of letters and numberswithout spaces.

• real: this tells the computer that the variable x is to betreated as a real number and stored in a standardexponential form. (e.g. +2.13 10-2 for 0.0213 ) Analternative to real is integer where the variable isstored exactly. There are other differences inFORTRAN between real and integer that becomeimportant later on.

• read: this tells the computer to wait until you type in anumber at the keyboard. The variable x is then giventhis value. The (*,*) part of the instruction is used laterto control how and where from the number is to beread. (it may be from a file on the hard disc)

• x=x+1 This is not an equation. It has the effect ofadding 1 to the existing value of x. In words ‘xbecomes x plus one’ Thus if x has the value 4,because you have entered 4 from the keyboard, thenafter this statement it has the value 5

• write: this tells the computer to write the value of x tothe screen. It was this statement that caused 5 to bedisplayed on your screen when you ran the program andinput the value 4.

• end: this signals the end of the program, and isessential. The program name following this is optional

but must, if used, be the same as the program nameused in the first line.

1.7 Task 2 - program compound

If I invest £a at r% for n years then the amount at theend of the period, assuming that the interest is compounded

annually is given by : A a r n= +( )1100

. The task is to

write a FORTRAN program to calculate A , given the initialsum a, the annual percentage interest rate r and the numberof years n.

We will design the program to:• request the input of the three unknowns a, r and n• identify on the screen the output of the result

• Start a new program and name it task2.f95• Type in the following program:

program compoundreal a, r, capitalinteger nwrite(*,*) ‘input the initial amount’read(*,*) awrite(*,*) ‘input the interest percentage rate’read(*,*) rwrite(*,*) ‘input the number of years’read(*,*) ncapital = a*( (1+r/100)**n)write(*,*) ‘final amount = ‘ , capitalend compound

• Execute the program as in 1.5 above providing yourown values of a, r and n. I suggest you use simplevalues so that you can check that the program isrunning correctly.

1.8 Details of program compound in task 2

• real a,r,capital This statement declares three realvariables, a, r and a third variable called capital, eachbeing separated by a comma. In general variables canbe given any name consisting of letters and numbersstarting with a letter. Thus the shortest variable nameis a single letter.

• write(*,*) ‘input the initial amount’ In order to senda message to the screen requesting the input of a pieceof data, namely the initial amount of the capital, we usethe write statement. The character string ‘input theinitial amount’ is written to the screen without thequote marks. It is the quote marks that identifies it asbeing a character string and not a variable name or listof names.

• read a After prompting the user with the message toinput the initial amount the program uses the read

3

statement to input its value. The program will waituntil a value is input at the keyboard. On input thevariable a is set equal to this value.

• capital = a*( (1+r/100)**n)FORTRAN uses:

** for powers* for multiplication/ for division+ for addition- for subtraction

Although there are rules for controlling the order in whichexpressions are evaluated the use of brackets isrecommended.

Since ** is given a higher precedence than * the aboveexpression for capital could have been written asa*(1+r/100)**n The bracket will be raised to the power nbefore it is multiplied by a.

Question In your program remove all the brackets from theexpression for capital and run your program with a=1, r=100and n=2. Is the answer what you expect?

• write(*,*) ‘final amount = ‘ , capitalThe write statement is used here to output two items,the character string ‘final amount = ‘ and the value ofthe variable capital; note that the two items areseparated in the statement by a comma.

1.9 Integer arithmetic

If we declare a variable n as being an integer then its valuewill be stored exactly. The range of values that an integercan take will depend on the system being used, we need notbother with this constraint at the moment. There are twoimportant side effects that we need to be aware of:

a) The statement n=23.1 will result in n being given thevalue 23. Since n is to be an integer the decimal partof the number is truncated. Indeed assignment of n toany real value or real expression will result in n beingtruncated to an integer.

b) A more surprising result is that obtained with integerdivision. If one integer or integer expression isdivided by another then the result is truncated. Thus:

2/3 = 07/2 = 3if n=14 then n/3 = 4

NB 2.0 is treated as a real because of the decimal point,thus 7/2.0 would be calculated as 3.5

Usually one has to be careful when carrying out a divisionif integers or integer variables are involved, however thisapparent shortcoming can be exploited as we see in the nexttask.

1.10 Task 3 - program change

Write a program to find the least number of one, two, five,ten, twenty and fifty pence pieces that make up a givennumber of pence. For example 123p consists of 2 fiftypence pieces, one twenty pence piece, one two pence pieceand one one pence piece. Such a program would be usefulin calculating the amount of change required in a vendingmachine.

We can see how the program will work by looking at how tocalculate the number of fifty pence pieces in the aboveexample of 123p.Using integer division 123/50 = 2 exactly the number offifty pence pieces in 123p. The amount remaining, whichstill has to be split up is given by 123 - 50*(123/50) = 23

We repeat this process next with 20 then 10,5,2 and finally1.

Complete the following program , save it as task3.f95 ,run and test it.

Note the inclusion of comment lines which are there solelyto help you follow the program . A comment is preceded by!

program change! n is the amount to be broken into change! one, two, five, ten, twenty, fifty are the number! of coins of respective denomination in the changeinteger n, one, two, five, ten, twenty, fifty

! request input of amount to be changed and write first line of! final outputwrite(*,*) ‘input amount to be changed’

read(*,*) nwrite(*,*) n , ‘ pence breaks down into’

! calculate the number of fifty pence pieces! and set n equal to the remaining changefifty=n/50n=n-fifty*50

Write code for twenty ten five two and one

! output the resultswrite(*,*) fifty, ‘ fifty pence pieces ‘

Write similar code for the others

end change

You should run this program using different amounts andcheck your results by hand.

1.11 Details of program change in task 3

• integer n, one, two, five, ten, twenty, fifty Thisdeclares the seven variables as integers. Note that wehave used words for the variables that relate to their

4

meaning in the program. Doing this makes it easier tofollow the program.

• write(*,*) n , ‘ pence breaks down into’ Thisstatement writes two items to the screen. The value ofn, which at this stage in the program is equal to theamount to be split into change, and the character string‘pence breaks down into’

If n has the value 123 then on execution of thisstatement the following is written to the screen:

123 pence breaks down into

• fifty=n/50 This statement is the key statement thatexploits integer division. The result of dividing n by50 is to calculate how many fifties there are in n, theremainder being discarded.

To see this suppose that n=123 then 123/50 = 2.46but the integer division discards the 0.46 leavingfifty=2.

To calculate the remainder, which we need for therest of the program we use the next statement:

• n=n-fifty*50 Using the data from above n=123 andfifty=2 thus n is reset equal to 123 - 2*50 = 23 Thuswe start the problem again with n=23 and in the nextstep, which you should have written, you calculate thevalue of twenty. Continue this through ten ,five, andtwo to one.

Exercise 1.1

a) Write a program to input a real number x and outputthe areas of the square with side x, the circle withradius x and the equilateral triangle with side x

b) For given integers n and m write a program to calculatethe remainder when n is divided by m. i.e. Yourprogram should read in values of n and m from thekeyboard and write out the remainder to the screen.

c) The natural exponent e can be defined as the limit of

11+

N

N

as N gets larger and larger. Amend your

program compound in (1.7) to calculate this function.You should allow N to be input by the user. Run yourprogram with different values of N to obtain anapproximation to e correct to 3 decimal places.

5

Chapter 2Control Structures

2.1 Conditional Branching - if… ..then

It is often necessary to decide between two courses ofaction. For example if we are about to calculate a/b then weshould first test to see if b=0. If b=0 then we should notattempt to carry out the division but follow some othercourse of action.

In the following short program, which you should attempt torun, the if statement is used to sort two numbers intoascending order.

Program sortreal x,y,tempwrite(*,*) ‘ input two numbers’read(*,*) x,y

order: if (x>y) thentemp=xx=yy=temp

end if order

write(*,*) ‘in ascending order the two numbers are’,x,yend sort

The syntax of the if statement is:

[name:] if (logical expression) thenstatements… … … …… … … …

end if [name]

The use of square brackets around the initial [ name:] andthe final [name] indicate that they are optional. 2 They aresimply used to make the program more readable.

2.2 Details of the program in 2.1

• real x,y,temp declares that the three variables x,y andtemp are to be treated as real numbers

• write(*,*) ‘ input two numbers’ read(*,*) x,y These two statements deal with theinput of the two numbers to be placed in order. Thefirst issuing a message to the sceen and the secondwaiting until the user has typed in two numbersseparated by a space. Assume that you have input 4 2ie x=4 and y=2

• if (x>y) then This tests to see if x is greater than y,which in this example it is. Thus the next three linesof code are executed. If x is not greater than y then theprogram jumps to the statement after the end if orderstatement.

2 [ ] in a syntax context will always be used to indicate that thecontents of the bracket are optional. The brackets do not form part ofthe statement!

• temp=x Since we are about to swap the values of xand y , in order to put them in ascending order, weneed to save the value of x before we start. Thisstatement saves the original value of x in temp. ietemp=4.

• x=y The original value of y is now placed in x. iex=2. If we hadn’t saved the original value of x itwould at this stage be lost.

• y=temp The original value of x, which has been storedin temp, is now placed in y. ie y=4.

• write(*,*) … … .. Outputs the values of x and y tothe screen.

2.3 Logical Expressions

A logical expression is an expression that has the valuetrue or false. As in the above example x>y is a logicalexpression and is true when x=4 and y=2 but is false if x=2and y=4.

As you would expect we can also use the following:

x<y x less than yx<=y x less than or equal to yx==y Yes there are two equal signs for x=y as a

logical expressionx/=y x not equal to yx>y x greater than y (as in the program above)x>=y x greater or equal to y

The above logical expressions can be combined using oneor more of the following:

.or.

.and.

.not.For example if we wish to execute a piece of code when x islarger than y and z then we would use:

if ( (x>y) .and. (x>z) ) then… … … …… … … …end if

NB The outer brackets are essential and contain thelogical expression (x>y) .and. (x>z) The brackets in thisexpression are not essential but are recommended.As with arithmetic expressions there are rules for evaluatinglogical expressions but this is best controlled using brackets.

FORTRAN, like most programming languages, allows us tohave variables of type logical. With care these can bemanipulated to great effect, however, in this introductionwe will restrict ourselves to the above arithmetic use.

6

2.4 Task 4 - program quadratic1 - sqrt( )

The quadratic ax bx c2 0+ + = has two real solutions

given by xb b ac

a= − ± −2 4

2 provided that a ≠ 0 and

b ac2 4≥ .

Complete the following program that inputs real values ofa, b and c and outputs the two real solutions. The programshould test that a ≠ 0 and b ac2 4≥ before attempting touse the formulae.*

The program denotes the two real solutions as x1 and x2.

program quadratic1real a,b,c,x1,x2write(*,*) ‘input a ,b and c ‘read(*,*) a,b,c

test: if ( logical expression) thenx1= … … … .x2= … … … ..write(*,*) … … … ..end if test

end quadratic1

Run your program with the following sets of data:

a) a=1,b=3,c=2b) a=1,b=2,c=1c) a=1,b=1,c=1d) a=0,b=2,c=4

You will observe that the program is less than helpful for c)and d). To write a complete program to solve the quadraticwe need to introduce a more complete form of theconditional branching statement.

2.5 Conditional Branching

In the quadratic example if a=0 then we can still solve the

problem, indeed xcb

= − provided b ≠ 0 . If both a and b

are zero then the quadratic is satisfied only if c happens toalso be zero. Furthermore if a ≠ 0 and b ac2 4= then thequadratic will only have one solution. Finally if a ≠ 0 and

b ac2 4< then there are no real solutions. For the programto be able to deal with all these possibilities in an efficientway we introduce a more elaborate form of conditionalbranching.

[name:] if (logical expression) then… … … … … … … … … … .… … … … … … … … … … .else if (logical expression) then [name]

* In FORTRAN the square root function issqrt(real expression)

… … … … … … … … … … …… … … … … … … … … … …else [name]… … … … … … … … … … …… … … … … … … … … … …end if [name]

• As before the use of a name is optional.• You may have as many else if as you wish.• The final else is also optional, but is usually present to

deal with the case when all the other logicalexpressions have been false. (ie when all else fails)

2.6 Task 5 - program quadratic2

Rewrite quadratic1 to deal with any of the above cases:

program quadratic2real a,b,c,x1,x2write(*,*) ‘input a ,b and c ‘read(*,*) a,b,c

if ( (a==0) .and. (b==0) .and. (c==0) ) then write(*,*) ‘the quadratic is satisfied for all x’else if ( (a==0) .and. (b==0) ) then write(*,*) ‘the quadratic has no solutions’else if (a==0) then x1=-c/b write(*,*) ‘equation is linear with x = ‘,x1else if (

… … … … … … … ..complete the program… … … … … ..

Test the program with a range of data that tests each part ofthe program.

2.7 Task 6 - decode

This is the reverse of a programming exercise, the object ofthe task is for you to read the program and then draw thegraph of the function that is defined by the code.

Given the following program describe its action and sketchthe function that is being defined. Pay particular attention tothe case n=m.

Your description should also include details of the inputrequired and the output observed on the screen.

If you wish you can type in and run the program though thisis not necessary for the exercise.

program decodereal x,y,n,m,tempwrite(*,*) ‘input two numbers, n and m’read(*,*) n ,mswap: if (n<m) then

temp=mm=nn=temp

7

end if swapwrite(*,*) ‘input the value of x ‘read(*,*) x

function: if (x<=m) theny=x**2else if ( (x>m) .and. (x<n) ) theny=1elsey=x+1end if function

write(*,*) ‘at x = ‘,x, ‘the function = ‘,y

end decode

2.8 Simple if

If we only need to execute one statemet depending onwhether or not a single logical expression is true the we canuse the simplified version of the above if statements.

if (logical expression) single statement

Example 1When about to calculate the square root of a

number we may wish to stop the program if the number isnegative. We could use the lines

if (x<0) stopy=sqrt(x)

These two lines of code will set y x= if x ≥ 0 but stopthe program if x<0.

The FORTRAN instruction stop stops the programcompletely and can be followed by a message which isoutput to the screen. Thus a more informative piece of codewould have been:

if (x<0) stop ‘negative square root encountered’y=sqrt(x)

Example 2

In a program to calculate yx

= 1 if x ≠ 0 and set

y = 1 if x=0 we could use the followingy=1if (x/=0) y=1/x

instead of an if then else structure.

The key point with the simple if structure is that it can onlybe used when there is only one statement to be executed.

2.9 do loop - unbounded do - exit

Consider the following problem:

Write a program to input a real positive number x. If theuser inputs a negative or zero number then the program

must respond by writing to the screen a message sayinginput must be positive, please try again.

To achieve this it is necessary to continue to execute a readstatement and test the input until the input is greater thanzero.

FORTRAN introduces the unbounded do loop as follows:

[name:] do… … … …… … … …end do [name]

This piece of code would execute itself for ever if we didn’tintroduce the exit statement.

The exit statement makes the program jump down to thestatement after the next end do. i.e. the current do loop isterminated.

Consider the following program:

program nice_inputreal x

write(*,*) ‘input a positive number’

doread(*,*) xif (x>0) exitwrite(*,*) ‘input must be positive, please try again’

end doend

Task 7

Enter the above program and run to satisfy yourself that itdoes only take in positive values. Try inputting a characterrather than a number.

Task 8 - triangle - :: - &

In triangle ABC, the angles A and C, and the side AC areknown. Calculate angle B and the other two sides. This canbe done using the sine rule and the fact that the angle sumof a triangle is 180 degrees. The task is to write a programwhich will take as input two values for the angles,measured in degrees and a value for the side. Clearly allthree quantities must be positive and the sum of the twoangle must be less than 180. Thus the program must testthat the input satisfies these criteria before it starts tocalculate the third angle and the other two sides. Your taskis to complete the following program.

NB The FORTRAN function sin(x) requires x to be inradians thus to calculate the sine of A degrees we need towrite sin(A*pi/180) where we have set pi equal to the valueof π

Program triangle

8

!declare and initialize the variable pireal :: pi=3.1415

! declare the angles and sides of the trianglereal A,B,C,AB,AC,BC

! issue initial invitation for input and start do loopwrite(*,*) ‘input two angles A and B &&and side AB of triangle ABC’doread(*,*) A,B,ABif (… … … … … … … ) exitwrite(*,*) ‘all input must be positive and angle sum<180’end do

! Calculate the third angle and other two sidesC =AC =BC =

! output resultswrite(*,*) … … … … … … … … … …

end triangle

a) We can simultaneously declare and initialize variablesas we have for the variable pi above. In general we candeclare some and declare and initialize others in onestatement.The line:

real :: x,y,z=1,w,v=1.2

declares the variables x, y, z, w and v as real and initializesz=1 and v=1.2 The other variable have no defined value atthis stage though most systems will give them the valuezero.

b) The & sign is used to extend the line - the lines arejoined at the & signs but the signs themselves are notprinted out.

2.10 do loop - bounded do

One of the strengths of the computer is the ability to repeatoperations over and over again. In the case of theunbounded do loop we need an exit statement to stop therepetition. We now look at a do loop that only executes agiven number of times.

Task 9 - Summation Σ

Consider the following simple problem:

Evaluate ii

i N2

1=

=

∑ where N is provided by the user.

Since we know a closed form formula for this expression:

ii

i N2

1=

=

∑ = + +N N N( )( )1 2 16

we can check the program.

Complete the following program and hence run withsuitable values of N to check that your program is correct.

Program suminteger :: I ,N,sum=0,formula

write code to input a positive value of N - see task 7

do I=1,Nsum = sum + I*Iend do

write code to evaluate the summation using the formulaformula =

write code to output the value of sum and the value offormula, identifying which is which. They should be thesame of course!

end sum

The do loop first makes the trip with I =1 then with I=2 etcup to I= N. The order in which the above process iscarried out is:

1) first set I=12) if I N≤ then execute the code down to the end do3) if I >N then jump to the next statement after the end

do.4) increase I by one5) repeat the process from (2) with the new value of I .

The general form of the do loop is given by:

[name::]do variable = expression1, expression2[,expression3]

… … … … … … … … … … … … … … … …… … … … … … … … … … … … … … … …end do [name]

As usual we can add an optional name to the process.

variable is an integer and expression1 and expression2 areinteger expressions. In the above, expression1 is just thenumber 1 and expression2 is the trivial expression N. Theoptional integer expression3 allows us to increment the doloop variable by increments other than 1.If expression3 is negative then the variable will bedecremented and the loop executed until the variable is lessthan expression2

Consider the following :

sum=0do I = 2*N*N, N**3, 4sum=sum+I*Iend do

If initially N=3 then the first line of the do loop readsdo I=18, 27, 4 and will produce

sum =18 22 26 14842 2 2+ + =

9

Since initially I starts at 18 and is incremented by 4, when itreaches 30 it fails to be less than the upper limit 27 and thusthe process is terminated and the program continues on pastthe end do. At this point sum has reached the above value.

NB If initially N=1 then the code in the do loop is neverexecuted since the first line of the do loop now reads:do I =2, 1, 4 The initial value of I is 2, which is greaterthan the upper limit 1 hence the process jumps to thestatement after the end do. Such a do loop is referred to asa Zero Trip do loop.Task 10 * - sum up or down

In task 9 we did not allow N to be zero or negative.However if N is zero or negative we can interpret the

summation ii

i N2

1=

=

∑ to be ii N

i2

1

=

=

∑ . Thus if N = − 2 the

summation is :( ) ( ) ( ) ( )− + − + +2 1 0 12 2 2 2

which can be rewritten as : ( ) ( ) ( ) ( )1 0 1 22 2 2 2+ + − + −

This is now a summation with increment -1 rather than 1.Thus irrespective of the sign of N we can carry out thesummation using the same do loop do I =1, N , M where weset M=1 if N >0 and set M=-1 otherwise.

Rewrite program sum in task 9 to allow for any integervalue of N by:• declaring a new integer M• relaxing the input to allow for any integer N• setting M=1 if N>0 and -1 otherwise• rewriting the do loop as do I =1, N , M• removing reference to the formula method which is

only correct for positive N, or if you wish retain it forN>0 only.

Task 11 - Loan Repayment Problem - iteration

Consider taking out a loan at a fixed interest rate r over aperiod of N years. Repayments are to be made in equalmonthly installments but the interest is calculated andcompounded annually.

Let Yn stand of the amount of the loan outstanding at the

beginning of the n th year. Thus Y1 is the initial amount of

the loan and YN + =1 0 if the loan is to be paid off in Nyears.

Let a be the annual repayment (monthly repayment = a/12)and let r be the interest rate expressed as a decimal. SinceYn is the amount owing at the start of the nth year the

* Omit if you don’t have time

interest charged for that year is r Yn . Thus at the start of

the (n+1)th year the total owing is Y r an ( )1 + − since wehave repaid £a during the nth year. Mathematically we canwrite:

Y r Y an n+ = + −1 1( )This is a simple recurrence relation which has solution

Y Yar

rarn

n= − + +−( ) ( )111

To calculate the annual repayments we set n=N+1 andYN + =1 0 . This gives :

ar r

rY

N

N= +

+ −( )

( )1

1 11

We are now in a position to write a program which for agiven loan, interest rate and period of repayment willcalculate the monthly repayments and print out the amountowing at the start of each year. We can either use therecurrence relation or the solution to calculate Yn , I will usethe recurrence relation as it is a more flexible approach ifthe interest rate is variable.

Complete the following program

program repay_loanreal r, Y1,Y,ainteger I,N

! Y1 is the initial investment and Y the variable Yn above! r is the interest rate and a the annual repayment.! N is the length (term) of the loan in years

continued… … .

write code to input positive values for the interest rate r,initial amount Y1 and term of loan NI suggest that you invite the user to input the rate as apercentage and then convert to a decimal with r=r/100

! convert r to decimalr=r/100

! calculate a/12 and write monthly repayment to screena = use the above formula for awrite(*,*)… … … .

!Calculate amounts owing and write results to screendo I =1,N+1 write(*,*)… … output Y1 and N with suitable message Y=(1+r)*Y1-a! reset Y1 Y1=Yend do

end repay_loan

10

Test the program with Y1=100, r=10% and N=2, check byhand.

Try other values and see if they seem reasonable.

Task 12 - solve f(x) = 0 by iteration

Newton’s iterative scheme to solve f(x)=0 is given by:

x xf xf xn n

n

n+ = −

′1( )( )

You may or may not have seen this

before. It is not essential for this exercise that you arefamiliar with this formula.

To solve x x x a3 24 0+ + + = the iterative scheme isgiven by

x xx x x a

x xn n

n n n

n n+ = − + + +

+ +1

3 2

2

4

3 8 1

( )

( )

Write a program similar to that in task 11. In this problem:

• Y1= x1 , the starting value for the iteration.

• Y= xn+ 1

• N is the number of iterations to be carried out• a is a parameter - initially look for solutions with a=-6

Run your program with N=5, a=-6 and a starting value ofY1=1.5. Run it again but with Y1=-3.5

Run your program to find all the roots of the cubic:x x x3 24 1 0+ + − = correct to 3 decimal places.

2.11 goto - label - read errors - continue

labelOne to five digits placed at the beginning of the line beforea statement:

121 write(*,*) ‘this statement has a label’

gotoThis command is used to send control to a labelledstatement

goto 121

When this statement is encountered the program jumps tothe statement labeled 121, executes the statement thencontinues from that point on.

The following code was previously executed using anunbounded do (see task 7) which is much neater and doesnot use a label and a goto

write(*,*) ‘input a positive number’

121 read(*,*) x if (x<=0) then write(*,*) ‘input must be positive, please try again’ goto 121 end if

Originally FORTRAN programs contained many gotostatements and labels, however this can make the programhard to follow. In more recent languages the goto and labelare almost extinct. We will try and do without them asmuch as possible as they are considered to be bad practice.However there is one situation where a goto is unavoidable,this is when we have to deal with input errors.For example if N is declared as an integer and in responseto read(*,*) N we type in a real decimal number eg 2.1 or aletter then the program will stop and an error message willbe generated. You may already have come across this insome of your programs. To gain control of this situationFORTRAN provides the following:

read(*,*,err = label) N

Thus if an error occurs when inputting N the program willnot crash but will go to the statement with the given label.

Thus an improvement on task 7 is:

program nice_inputreal x

write(*,*) ‘input a positive number’ do

read(*,*,err = 121) x if (x>0) exit

121 write(*,*) ‘input must be positive, please try again’ end doend

task 13 *

Amend task 7 as above. Run this program and try enteringcharacters that are not positive numbers (ie letters ornegative numbers). You should find that the program willnot terminate until you have entered a positive number.

As labels can only be attached to statements and not, forexample, to declarations:

121 real x is illegalWe introduce the dummy statement continue.

Thus using: 121 continue enables us to jump tothis point in the program and then continue on from thatpoint.

Task 14 - program prime - the function real(N)

11

Write a program to input an integer N greater than 2, test tosee if its prime and output a suitable message.

A simple algorithm to test if a number is prime is to first tocheck that it is not even and then to see if it is divisible byany of the odd numbers from 3 to N Theoretically thisshould work, however there are two problems:

a) the FORTRAN square root function only takes real typesas its argument. Thus the integer value N has to beconverted to a real type. This is done using the functionreal(N) Thus instead of writing sqrt(N) which wouldgive an error we write sqrt (real (N) )

b) the FORTRAN square root function returns a real

answer, thus there may be a round off error. Forexample if N=49 then it may happen that

49 6 9999999= . and we would only test N forfactors of 3 and 5 and hence declare 49 to be prime. Toovercome this problem we will see if N is divisible byall odd numbers from 3 to N + 1

Complete and test the following program:

program primeinteger N, I, remainder

by adapting the program nice_input above write code to inputan integer greater than 2

! Test to see if evenif (N-2*(N/2) ==0) then write(*,*) ‘ the number is even - not prime’else! Test to see if divisible by odd numbers 3 - N + 1

do I = 3, sqrt(real(N)) + 1, 2remainder = N-I*(N/I)

if(remainder==0) thenwrite(*,*) output suitable messageexitend if

end doend if

! write code to output suitable message if remainder neverzero

end prime

2.12 details of program prime

N-I*(N/I) This tests to see if N is divisible by I.Try it with some numbers and you will see that it producesthe remainder on dividing N by I, provided you carry out theN/I quotient using integer division.(see 1.9)It is used in the first instance with I=2 to test if N is evenand then with I odd from 3 to N + 1 .

The control structure of this program is more complex thanany encountered so far. It contains an If then elsestructure which itself, in the else part, contains a do loopwhich in turn contains an if then structure. Note that eachof the structures has its own end statement. (namingindividual control structures can help you to follow the flowof the logic in the program, though I haven’t used nameshere))

The exit statement is used to get us out of the do loop assoon as we find a factor.

2.13 Task 15*It is rumoured that the quadratic N N2 41− + generates aprime number for each of the integers N from 1 to 40.Amend program prime to calculate the values of thisquadratic for N=1 to 40, check to see if each value is primeand output a suitable message for each value.

12

Chapter 3Subroutines and Functions

3.1 Introduction

FUNCTIONYou have already encountered some of FORTRAN’sintrinsic (built-in) functions such as sqrt(x) and sin(x), inthis section we look at how to define our own functions. Ingeneral a FORTRAN function, like a simple mathematicalfunction, takes any number of arguments and returns asingle value. Thus, for example, we can define a functioncalled dist that will calculate the distance between twopoints in two dimensions, it will have four arguments for theco-ordinates of the points and will return a single real value.Thus d=dist(x1,y1,x2,y2) will calculate the distancebetween the two points (x1,y1) and (x2,y2) and place theresult in d.It is usual practice not to allow the function to change thevalues of the arguments or to execute any input or outputroutines

SUBROUTINE - callA subroutine is a more versatile form of a function, like thefunction it can have several arguments, however it iscapable of returning more than one value. For example wemay wish to calculate the volume and surface area of arectangular box given its height, length and breadth. If werefer to the subroutine as sizebox then it would appear inthe programme as :

call sizebox (height,length,breadth,volume,area)

In this case the first three parameters are the data and thelast two return the required results after this statement hasbeen executed. The word call is a special FORTRAN wordthat is used with subroutines

We can also use subroutines to execute detailed input andoutput routines.

3.2 Task 16 - Creating a Function

So far our programs have only contained one segment,namely the main program segment. Functions andsubroutines appear after the main segment as separatepieces of code. The following program illustrates thedefinition and use of a function.Note that in the main program segment the function namedist is declared as real since the function is to return a realvalue. The function segment itself appears after the mainsegment and in general looks like:

function name (variable list)declare function type and variable type… … … … … … … … …… … … … … … … … … …end [name]

program distance! declare function types

real dist!declare other variables

real x1,y1,x2,y2,d!input datawrite(*,*) ‘input the X- co-ordinates of two points’read(*,*) x1,x2write(*,*) ‘input the Y co-ordinates of two points’read(*,*) y1,y2! invoke function

d=dist(x1,y1,x2,y2)!output resultwrite(*,*) ‘distance between the points = ‘, dend distance

function dist(x1,y1,x2,y2)real dist,x1,y1,x2,y2dist= sqrt((x2-x1)**2+(y2-y1)**2)end dist

3.3 Task 17 - Newton’s Method

We now return to the problem in task 12, that of solvingf(x)=0 using Newton’s method. The general formula for the

method is given by: x xf xf xn n

n

n+ = −1

( )' ( )

This task asks you to write a program that will :

• Input the initial value of x, an accuracy value and amaximum number of iterations, refered to respectivelyin the program as : y1, accuracy and MaxIt .

• Implement the functions f (x) and f ‘ (x) as userdefined FORTRAN functions. Clearly for eachproblem you will have to write new functions

• The iterative process should continue until thedifference between xn and xn+ 1 is less than thevariable accuracy or the maximum number of iterationshas been exceeded. To compute the differencebetween xn and xn+ 1 you should use

| |x xn n+ −1 which with the variables below will becoded as abs (Y-Y1). The program uses the variablecount to count the number of iterations performed.

• Output a suitable message, depending on whether ornot the program terminated because it exceeded MaxItor because it reach the required accuracy.

Complete, as above, the following skeleton program tosolve f (x) = 0 where f x x x( ) sin( )= − 2 x ≠ 0 .

13

Program newton! f and derivf are the function names of f and f ‘real f,derivf! y1 current value of x and y next value of xreal y1,y,accuracy,differenceinteger :: count=0, MaxIt

write code to input y1, accuracy and MaxIt

iterate: doy = y1-f(y1)/derivf(y1)count=count+1difference=abs(y-y1)

construct a simple if statement that will exit the do loop ifcount >= MaxIt or difference < =accuracy

y1=yend do iterate

write code to output the answer if the required accuracy isachieved within the maximum number of iterations or asuitable message if not

end newton

function f(x)write code for the above functionend f

function derivf(x)write code for the derivative of the above functionend derivf

NB In the definition of the functions I have used x asthe variable, any name is permissible provided you continueto use it inside the function segment. When we use thefunction as f(y1) then the value of y1 replaces x in order toevaluate f(y1). In this context x is called a dummy variable.

Run your program with y1 = 0.5 , MaxIt = 10 and accuracy= 0.01

task 18 *Amend task 17 to print out the values of xn and thevariable difference as you iterate. Solvef x x x x( ) sin( )= − + =3 2 0 , x ≠ 0 correct to three

decimal places. This problem has two solutions, onenegative and the other positive.

You may also wish to improve your program by trapping anypossible occurrence of f x' ( ) = 0

task 19 - creating a subroutine

The following program illustrates the simple use of asubroutine to calculate the volume and surface area of arectangular box given its height, length and breadth.

Note that unlike the function:• the subroutine is used to return several values. These

may be of different type, though here they are all real.• the FORTRAN word call is used to implement the

subroutine.• the subroutine name is not a data type, (e.g. real or

integer) and therefore it is not necessary to declare it

Note that like a function :• we can use dummy variables in the definition of the

subroutine

program boxreal height, length, breadth, volume, areawrite(*,*) ‘input the height, length and breadth of the box’read(*,*) height, length, breadthcall sizebox (height, length, breadth, volume, area)write(*,*) ‘volume =’ , volume, ‘area = ‘, areaend box

subroutine sizebox (ht, len, brdth, vol, area)real ht, len, brdth, vol, areavol = ht * len * brdtharea=2*(ht*len + ht*brdth + len*brdth)end sizebox

Run the program with suitable input and check your results.

task 20 - input/output with a subroutine

As mentioned in the introduction to this chapter it isconsidered bad practice to carry out any input or outputwithin a function, or change any of the variables passed toa function. Only the main segment or subroutine segmentsshould be used for these purposes. In program box, andindeed many of the above programs it would have beenneater to put all the i/o in a single subroutine. Write asubroutine called nice_input(ht,len,bdth) that will ONLYinput positive real values. Refer back to section 2.11 andtask 13 to see how this can be done.

Add you subroutine to the program box and replace theexisting input statements with a call to it. Test yourprogram.

14

task 21 - numerical integration f x dxa

b

( )∫We now consider a problem in which we use bothsubroutines and functions. First we look at themathematical problem of approximating the value of adefinite integral of a given function over a given interval.One of the most simplest methods is the trapezoidal rulewhich divides the interval of integration into parts and thenapproximates the area under the curve in each part using thearea of a trapezium. See fig 1.

Fig 1

We approximate f x dxx

x h

( )+

∫ by the area of the trapezium

STUV which is given by h

f x h f x2

[ ( ) ( )]+ + . Thus by

splitting the interval [a,b] into N strips each of width h wecan , by adding together all such approximations, obtain an

approximation for f x dxa

b

( )∫ .

The following program uses:• a function for f (x) which we use as f(x) and f(x+h)• a subroutine TrapInt(x,h,Intgl) which:

a) calculates the approximation to the integralon the interval [x,x+h]

b) adds the result to the existing value of Intglwhich already contains the integral from a tox

c) moves x on to the start of the next interval.

By calling the subroutine TrapInt N times we will addtogether all N trapeziums that make up the total area.

Although we will have to change the function routine forf(x) for different integrals we can input the interval [a,b]and the number of strips N at run time.

program Integratereal :: h, a, b, x, f, Intgl=0integer i, N

write code to input the limits a and b and the number ofstrips N. You may wish to do this in a separate subroutine

! initialise x = a and calculate hx=ah=(b-a)/N

!carry out the summationdo I=1,Ncall TrapInt(x,h,Intgl)end do

write code to output the result

end Integrate

function f(x)write code for f(x)end f

subroutine TrapInt(x,h,I)real x, h, I

write code to update:• I by adding to it the area of the trapezium in fig 1.• x by adding h to it

end TrapInt

Use the above program to obtain an approximation to

11 2

0

1

+∫ xdx correct to two decimal places. i.e.increase the

value of N until two answers agree to two decimal places

Is this result correct?

S

T U

V

x x+h

y f xx

= =+

( )1

1 2

15

Chapter 4

Arrays, Derived Types and Modules

4.1 Arrays - definition

An array consists of a rectangular set of elements all of thesame type (any type can be used). In mathematics simpleexamples of arrays are the components of a vector or theelements of a matrix. The vector A with components A(1),A(2) and A(3) is defined in FORTRAN using the statement:

real, dimension(3) :: A

This statement declares 3 real variables denoted A(1), A(2)and A(3)

To refer to the elements of a matrix we require twoparameters one for the row position and one for the column.Thus the element in the ith row and jth column of a matrix

B is denoted B(i,j). For example if B =

1 23 4

then

B(1,1)=1, B(1,2)=2 , B(2,1)=3 and B(2,2)=4. In FORTRANwe would declare such a matrix as:

real, dimension(2,2) :: B

• The rank of an array is the number of parametersrequired to reference one of its elements. In the aboveA is of rank one and B is of rank 2.

An array of rank 3 could be defined by

real, dimension(2,4,2) :: C

The elements of C are in general referenced by C(i,j,k) orspecifically for example by C(1,2,1). Note that C contains2 4 2 16× × = elements

• The shape of an array is given by writing down thenumber of elements in each component. Thus the shapeof A is (3) the shape of B is (2,2) and the shape of C is(2,4,2)

In each of the above examples each of the indices starts at 1and runs to the number indicated in the definition. Forexample in C the first index runs from 1 to 2, the secondfrom 1 to 4 and the last index from 1 to 2. In each case thelower bound of the index is 1. Sometimes it is desirable tostart the index at some other value, this can be done asfollows:

real, dimension(-1:2,3) :: D

D is an array of rank 2 and shape (4,3). Thus if we useD(i,j) in our program the value of i can be one of -1, 0, 1 or2 and the value of j one of 1, 2, or 3

Since D is of rank 2 and its shape is (4,3) it is just a 4 3×matrix. However its row reference runs from -1 to 2 ratherthan the usual 1 to 4 as one might expect for such a matrix.

Task 22 Array assignment - do implied list

Run the following program and convince yourself that you argetting the correct output.

program rank1_array

!declare two real arrays of rank 1 size (4) and integer Ireal, dimension(4) :: A,Binteger I

! assign values to the two arrays A and Bdo I=1,2A(I)=I*IB(2*I-1)=3*IB(2*I)=4*Iend doA(3)=0A(4)=0

write(*,*) ‘array A’ , (A(I),I=1,4)write(*,*) ‘array B’ , Bend program rank1_array

• I have used an integer expressions for the indices of theB array viz. B (2*I-1) and B(2*I) . This picks out theodd and even indices respectively.

• The structure (A(I),I=1,4) is called a do implied list and

is the same as writing A(1),A(2),A(3),A(4) • An alternative way to write out an array is to just use the

name as in: write(*,*) ‘array B’ , B

Task 23 Order of Array - Nested do loop

The following program:• Assigns values to an array of rank 2• Writes out the array in a controlled way along the rows

so that the output to the screen gives the array as amatrix.

• Writes out the array in the order in which it is stored.viz moving down the first column then the second and soon.

Try running the program to observe the output.

Program array_orderreal, dimension(3,3) :: Ainteger I ,J

! Use nested do loop to assign values to the matrixrow_index: do I=1,3column_index: do J=1,3 A(I,J)=I*I+2*J end do column_index end do row_index! output a row at a timedo I=1,3write(*,*) (A(I,J),J=1,3)end do

16

! output in the natural order in which A is storedwrite(*,*)write(*,*) Aend program array_order• Note that the two do loops are nested one inside the

other. The outer loop row index I is first set equal to 1and then the inner loop is executed with J=1, 2 and 3.The outer loop index I is then increased to 2 and theinner loop execution repeated. This continues until allcombinations of I and J have been exhausted

• The write(*,*) is used to output a blank line to makethe output more readable

4.2 Matrix Multiplication

Definition

If the I-K th element∗ of the matrix A is denoted A(I,K) andthe K-J th element of B is denoted B(K,J) then the:

I-J th element of AB is defined by A I K B K JK

N

( , ) ( , )=

∑1

• For this definition to be valid the number of columns ofA must equal the number of row of B; this is denoted byN in the above definition.

• If B has only one column this becomes the definition ofthe action of a matrix on a vector.

Example:

1 23 4

5 67 8

1 5 2 7 1 6 2 83 5 4 7 3 6 4 8

=× + × × + ×× + × × + ×

=19 2243 50

Task 24 Program MatrixProd - passing arrays

Construct the following program which uses threesubroutines, one for input, one for multiplying the twomatrices and one for output. These should be placed afterthe main program segment.

In particular you should note the way in which the arrays arepassed to the subroutines.

Program matrixprodreal, dimension(3,3) : : A,B,Cinteger :: dim=3call InMatrix(A,dim)call InMatrix(B,dim)call MatProd(A,B,C,dim)call OutMatrix(C,dim)end program matrixprod

∗ When referring to the I-K th element of a matrix the first letter alwayscorresponds to the row position and the second to the column . Thusfor example A (1,2) would be the element of A in row 1, column 2.

The subroutine InMatrix:• Is written to input a rank 2 array of shape (dim,dim) (ie

a square matrix)• Uses variable X , which has to be declared inside the

routine using the variable dim to determine its size.• Prompts the user to input the elements one row at a

time.

Subroutine InMatrix(X,dim)integer dim,I,Jreal, dimension :: X(dim,dim)write(*,*) ‘input a’ , dim, ’by’, dim, ’matrix one row at a time’write(*,*)do I=1, dimread(*,*) (X(I,J),J=1,dim)end dowrite(*,*)end subroutine InMatrix

• The subroutine MatProd takes three arrays of shape(dim,dim), forms the product of the first two and putsthe result in the third.

• To implement the technique of forming a summation

(see task 9) we need to first set every element of C tozero, this can be done with the statement C=0.FORTRAN allows certain operations and assignmentwith arrays but you need to be careful.

Subroutine MatProd(A,B,C,dim)

declare the real matrices shape (dim,dim) and integer dimdeclare integers I, J and K to carry out the product

!Initialise the matrix C equal to zeroC=0

construct a triple nested do loop to calculate the product ABplacing the result in C as you go.

end subroutine MatProd

• The subroutine OutMatrix is almost identical to theroutine InMatrix but uses write statements rather thanread to transfer the data

Subroutine OutMatrix(X,dim)

declare X , dim and any other variable you use

write(*,*) ‘the product of the above two matrices is:’write(*,*)

write code to output the matrix X row by rowusing a similar do loop and do implied list as in InMatrix

end subroutine OutMatrix

17

Test your program with the example above.

Try the following exmple:

1 2 11 1 10 1 1

2 3 11 1 01 1 1−

−−− −

4.3 Derived Types - type - %

We have so far only discussed real, integer and array types.FORTRAN also allows complex types, character types,pointer types and logical types. In addition FORTRAN90/95 allows us to define our own types. This can be auseful facility as it allows us to code in a much more logicalfashion which is a great advantage when writing longprograms.

Given two points in two dimensions consider:

a) Calculating the distance between the two pointsb) Calculating the co-ordinates of their mid-point.

We introduce the data type point which consists of a pair ofnumbers. We then declare two variables, each of typepoint, to represent the two points and a variable M, also oftype point, for the mid-point. .

The following program inputs two points, calculates thedistance between them and the co-ordinates of their mid-point

The new features of the program are:

• The creation of the data type using the word typeThe lines.

type pointreal X,Yend type point

create a data type called point

• The line:type(point) , dimension(2) :: P

declares two points , P(1) and P(2), each of which hasan X and Y componentThe line:

type(point) M

declares a single variable M with components X and Y.Note how type(point) is used in the same way as wemight use real or integer.

• To refer to the coordinate of the point P(1) we use the %

symbol. The X coord is referred to as P(1)%X and the Y coord

as P(1)%Y. Similarly for P(2) and M

• Note how we have used a do loop to input the co-ordinates of both P(1) and P(2) by referring to the pointsas P(I)%X and P(I)%Y and then letting I loop from 1 to2.

• Some programming languages use a . instead of the %sign.

Type in the program and run.

Program dist2d

type pointreal X,Yend type point

integer Ireal :: d=0type(point) , dimension(2)::Ptype(point) M

do I=1,2write(*,*) ‘input the X and Y coords of point number’ , Iread(*,*) P(I)%X, P(I)%Yend do

d = sqrt((P(1)%X-P(2)%X)**2 + (P(1)%Y-P(2)%Y)**2 )M%X=(P(1)%X+P(2)%X)/2M%Y=(P(1)%Y+P(2)%Y)/2

write(*,*) ‘distance between points = ‘,dwrite(*,*) ‘mid point at ‘, M%X,M%Yend program dist2d

4.4 Modules - use

This seems like a good time to introduce the concept of amodule, most languages have something similar. InFORTRAN we can, amongst other things, use a module todeclare variables and create types . The following problemuses a module to allow us to access our user defined typeinside different program segments. That is to say inside themain segment, subroutines and functions.

NB All modules must appear before the main programsegment which as we have seen comes before thesubroutines and functions.

Task 25

The following program rotates a triangle in two dimensionsthrough a given angle about the origin (see diagram). Thistype of calculation is clearly of great value when writingsoftware with animated graphical output.

18

θ

T(1)

T(2)

P (1)

P (2)

P (3)

The program will:

• Set up the co-ordinate of a triangle. For simplicity wewill allow the program to specify the triangle and notthe user.

• Ask the user to input an angle through which thetriangle is to be rotated

• Call a subroutine to calculate the new co-ordinates• Output the result

In the program we define, inside a module, the followingtypes:

• As in the above we define a type point to represent theco-ordinates of the vertices of the triangle.

• A type triangle that consists of three variables of typepoint.

Module geom_objectstype pointreal X,Yend type point

type triangletype(point) , dimension(3) :: Pend type triangle

end module geom_objects

NB The type triangle contains three points P(1), P(2) andP(3) each of which has an X and Y component

program rotate_triangle

! declare two triangles T(1) and T(2) and angle of rotation use geom_objects type(triangle), dimension(2) :: T real :: theta,pi=3.1415927 integer I

! create the co-ordinates of triangle T(1) do I=1,3

T(1)%P(I)%X = I T(1)%P(I)%Y=I*I end do

! input the value of theta and convert to radians write(*,*) ‘specify, in degrees, the angle of rotation’ read(*,*) theta theta=theta*pi/180

! rotate triangle T(1) and store result in triangle T(2)call rotate(T,theta)

!write results to screen write(*,*) ‘The new co-ordinates are’ do I=1,3 write(*,*) ‘ X = ‘ ,T(2)%P(I)%X, ’ Y = ‘ , T(2)%P(I)%Y end do

end program rotate_triangle

NB. To refer to the X component of the I th point oftriangle T(2) we write T(2)%P(I)%X

Subroutine rotate(T,theta)! Declare the types of the subroutine arguments and integer I use geom_objects type(triangle),dimension(2) :: T real theta integer I

!rotate the three points of triangle T(1) and store in T(2)do I=1,3T(2)%P(I)%X=T(1)%P(I)%X*cos(theta) - T(1)%P(I)%Y*sin(theta)T(2)%P(I)%Y=T(1)%P(I)%X*sin(theta) + T(1)%P(I)%Y*cos(theta)end do

end subroutine rotate

• Before running the program look at the code that setsthe position of T(1) and write down the co-ordinates ofits vertices .

• Enter the module, main program segment and

subroutine in that order and as a check run initially withtheta equal to zero. This should give the co-ordinate ofT(1).

• Run with theta =45 and theta = -45. Are the new co-ordinates of P(1) equal to what you expect?

• Calculate a value of theta such that after rotation the

side P(1)P(2) is parallel to the x-axis. Run yourprogram to check this result. Repeat this exercise forthe other two sides of the triangle.

19

Task 26 - Rotating Rectangle

Amend task 25 to deal with a rectangle rather than atriangle.

You will need to:

• replace the type triangle with a type rectangle whichwill require four points rather than three

• Declare two rectangles, R(1) and R(2) would be a goodchoice

• Initialise the position of R(1). I suggest that you positionit on the x-axis with one corner at the origin, this willmake it easier for you to calculate the initial co-ordinates of the corners.

Run your program and test with values of theta that giveknown results. Eg θ = 0 , θ = 90 , θ = 180 .

20

Chapter 5Input and Output

5.1 Introduction

We have seen that the commands read(*,*) and write(*,*)are used to input data from the keyboard and output data tothe screen. Used in this form the facility is extremely basic,we have very little control for example over where, on thescreen, the output should be written or indeed how manyfigures should be used to express a particular value. Inaddition we have only been able to read from the keyboardand write to the screen, we have no means of reading fromor writing to a file. (i.e. data held on a disc on the systemeither on your U drive or on any other available drive)

We now introduce two separate items:

• The concept of formatted read and write along with thefacility to use a file rather than the keyboard and thescreen. This is part of the FORTRAN standard.

• The concept of windows input and output. We will

look at the idea of a dialogue box and a canvas. Theformer will enable us to input data at a specific point onthe screen (you already do this when you log into thesystem, inputting your id and your password) and thelatter enable us to draw graphs and pictures. Theimplementation of these facilities is NOT part of theFORTRAN standard thus any program that containscommand that involve this type of input and output willnot be transferable to another machine that does notsupport Salford FORTRAN.

5.2 Format statement

To see that we have a need for controlling the output to thescreen consider the output from the following program:

program F_outreal a, cinteger Ia=1/7.0c=1/10000000.0I=1234write(*,*) a, c, Iend program F_out

The three number are presented on the screen as follows:

0.142857 1.000000E-07 1234

we have no control over the spacing between the numbers orthe number of figures that will be displayed. Note how thesystem has resorted to a standard floating point form for cbecause it could not express the number using only sixdecimal places. To control the output we associate witheach write statement a format statement which providesinformation on how the data is to be written. The followingillustrates how this is done:

write(*,10) a, c, I10 format(2F12.8, I5)

Note how the second * in the write statement has beenreplaced with a label number that is attached to the formatstatement.

The format statement consists of the following:

• label format ( list of instructions, called editdescriptors)

• F indicates that the number to be output is a floating

point number, i.e. one that has been declared using real

• I indicates that the number to be output is an integer,i.e. declared as an integer.

• F12.8 indicates that the output will take up 12 places

on the screen with 8 places being used for the decimalpart of the number and 4 for the decimal point, sign andinteger part of the number. In the example we havewritten 2 F12.8 , the 2 is inserted to indicate that thefirst two number in the write list should be output inthis style. As we see a and c are both declared as realand are the first two variables in the write list.

• I5 indicates that the output will take up 5 places on thescreen.

• If the number to be output is too small for the allocatedslot FORTRAN will pack out with spaces or zeros

• If the number to be output is too large for the slot

FORTRAN just outputs *s; not very helpful! • If there are more items in the write list than edit

descriptors in the format statement then a new line isstarted and the format statement is started again.

Task 26 - formatted output to screen

Amend the program F_out by including a label in the writestatement and introducing the format statement as above.Run to obtain the output which will be arranged on yourscreen as follows:

12 places 12 places 5 places0 . 1 4 2 8 5 7 1 5 0 . 0 0 0 0 0 0 1 0 1 2 3 4

Note that the numbers are placed over to the right of theirallocated slot.

Task 27 - formatted input from keyboard

There is no task 27 as formatted input from the keyboard isNOT VERY PRACTICAL. For example:

read(*,10) a,c,I10 format(2F12.8, I5)

would require the user to input the data to fit exactly intothe allocated slots, inputting spaces and zeros where

21

necessary. If you wished to input a=2.6 you would have totype in space space 2.60000000 in order to fill theallocated 12 places with the point in the correct place.

5.3 Read and Write to a FILE

In the same way that your program is saved to a disc in a filewe can save data from a program or alternatively read a fileto provide data for a program. We will finally get rid of thelast * in the read and write statements.

To use a file we need to:

• Identify the name of the file, giving its complete path ifnecessary

• Tell the system that we wish to use the file, this we referto as opening the file

• Associate individual read and write instructions with the

given file. It is possible to have more than one file openat a time as well as using the keyboard and screen forinput and output.

• When we have finished with the file we tell the systemthat it is no longer required by closing the file

The following program opens a file called tsk28.dat , thedat extension is just to remind me that it is a data file. If thefile doesn’t exist then one is created, if it does exist then itis made ready for reading and writing.

Type in and run the following program

Program OutFilereal a,cinteger Ia=1/7.0c=1/10000000.0I=1234open(11,FILE=’tsk28.dat’)

write(11,10) a,c,I10 format(2F12.8,I5)

close(11)end program OutFile

The two key statements are:

• open(11,FILE=’tsk28.dat’)

The number 11 is called the channel number and isused to identify the file with the read and writestatements that are used to access it. Thus instead ofwrite(*,10) we now have write(11,10)

FILE= ‘tsk28.dat’ tells the computer that it must find orcreate the file tsk28.dat ∗ .

• close(11) This tells the computer that we havefinished with the file that is associated with channelnumber 11.

Task 28 read a file

Assuming that you have already run the program OutFileamend it as follows to read the file tsk28.dat and print theresults to the screen.

• Replace the statement: write(11,10) a,c,I with read(11,10) a,c, I

• Write code to output the variables to the screen using

the existing format statement

You should of course get the results already observed in task26, the difference now is that they were created by oneprogram, stored and then at a later time retrieved andwritten to the screen.

Task 29 create a file and read with Excel

It is quite often necessary to create and save data and thenanalyse it using a separate piece of software. With this inmind the following task is to create a set of points, savethem to a file and then invoke Excel to read the file and plota graph of the data.

Complete the following and run.

Program CubicExcel

write code to define a type called point as in section 4.3

declare an array P(I)… P(50) of type point - section 4.3

integer I! open file for output with channel number 11 write code to open file - provide name for file

! calculate the co-ordinates of the fifty points

do I=1,50P(I)%X=I/10.0 -2.5P(I)%Y=P(I)%X**3 - P(I)%Xwrite(11,10) P(I)%X, P(I)%Y10 format(F12.8, 1X, F12.8)end do

write code to close file

end program CubicExcel

∗ The file will by default be placed or looked for in your homedirectory on the U drive. However if for example the file is to becreated or read from using the A: drive then we would have writtenFILE= ‘A:\tsk28.dat’ etc etc

22

NB To separate the X and Y components of each point sothat Excel can read them as separate pieces of data we have

introduced a space between the two values. This is done inthe format statement using 1X. (for two spaces we woulduse 2X etc )

Open Excel and open your data file. Excel will treat it as adata file and will take you through a few options beforedisplaying on the work sheet. Excel will refer to ‘fixedwidth columns separated with spaces’ as opposed to datadelimited using commas. Our data is of course the formerand you should select this option

Use the wizard to plot the data - ask tutor

5.4 Graphical Output to Screen

The Salford software supports many features for creatingwindows, using buttons, menus and the mouse. Here weintroduce just a few ideas that enable us to draw a pictureonto the screen. The first program below simply opens agraphics window and draws a line. The second programuses the idea of rotating a triangle seen in task 25 alongwith the output to the graphics screen.

Try the following program:

program lineinteger :: bkcol=2,col=4call vga@call clear_screen_area@(0,0,640,480,bkcol)call draw_line@(100,100,300,400,col)end

• colours are referenced by numbers, in the simplest casesthe numbers 0 to 15 are used. Here I have set bkcol=2to give a background colour of green and col=4 to give adrawing colour of red

• call vga@

This creates the graphics screen of size 640 longby 480 down. This gives 307,200 points on thescreen that can be illuminated in one of theavailable colours. (these points are called pixels)

• The origin for the graphics screen is in the top left handcorner, with the x co-ordinate running across the screenfrom 0 to 640 and the y co-ordinate running down thescreen from 0 to 480 Outer boundary in diagram below.

• The commandclear_screen_area@(X1,Y1,X2,Y2,colour)

will fill the area defined by the co-ordinates with thegiven colour. See shaded area in diagram below. In theprogram I have used it to completely fill the graphicsarea with clear_screen_area@(0,0,640,480,bkcol) withthe colour specified by the value of bkcol. This gives usa coloured ‘canvas’ of one colour on which to draw. Inthe program bkcol=2 which corresponds to green.Without this command the canvas will be black.

NB. all parameters must be of type integer

• draw_line@(a,b,c,d,col) this will draw a line in thecolour given by col from the point (a,b) to the point(c,d). In the program we draw a line in red from(100,100) to the point (300,400)

NB. all parameters must be of type integer

task 30

Run the above with different values of bkcol and make anote of the relationship between the colours and the colournumbers that generate them.

task 31

Amend the above code to draw a polygon through the points(100,100), (150,300), (300,400), (250,300) and (100,100)making each side a different colour.

5.5 Animated output to screen

One of the basic methods of animating a figure is to carryout the following steps:

• draw the figure• delete the figure by redrawing it in the same colour as

the back ground colour• draw the figure at its new position

By repeating these steps the figure will appear to move

As you would expect there are many variations on thisscheme plus other methods of creating animations.

The following program creates a triangle and then proceedsto rotate it about a fixed point.I have split it into logical segments and used derived typesand a module.

(0,0)

(640,480)

(X1,Y1)

(X2,Y2)Graphics window

23

The following module defines type point and type triangleas well as declaring and initialising integers for thebackground colour (bkcol), the drawing colour (drcol) andthe point of rotation (x0,y0).

module geomtype pointinteger X,Yend type point

type triangletype(point),dimension(3)::Pend type triangle

integer ::bkcol=3,drcol=15,x0=200,y0=200end module geom

This is the main segment and controls the programNote how the items in the module are made available to itvia the statement use geom

program rot_triangleuse geomtype(triangle),dimension(0:2)::Treal thetainteger I

!Create the basic trianglecall BasicTriangle(T(0))

! initialise T(1) and T(2) to be the same as T(0)T(1)=T(0);T(2)=T(0)

! create drawing areacall vga@call clear_screen_area@(0,0,640,480,bkcol)

!draw and animatedo i=1,100theta=0.1*i call drawtriangle(T(1),bkcol) call rotate(T,theta) call drawtriangle(T(2),drcol) T(1)=T(2)

! slow down the graphicsdo n=1,1000000end do

end doend program rot_triangle

This subroutine creates the basic triangle which is laterrotated. Note Z is a single triangle

Subroutine BasicTriangle(Z)use geom

type(triangle) ZZ%P(1)%X=300;Z%P(1)%Y=250Z%P(2)%X=400;Z%P(2)%Y=250Z%P(3)%X=350;Z%P(3)%Y=300end subroutine BasicTriangle

This subroutine rotates the basic triangle T(0) through thetaabout (x0,y0) and places the result in T(2) Note in thissubroutine T is defined to be the array of triangles T(0),T(1) and T(2). T(1) is not used.

subroutine rotate(T,theta)use geomtype(triangle),dimension(0:2)::Tinteger Ireal thetado i=1,3T(2)%P(I)%X=(T(0)%P(I)%X-x0)*cos(theta) - (T(0)%P(I)%Y-y0)*sin(theta)T(2)%P(I)%Y=(T(0)%P(I)%X-x0)*sin(theta) +(T(0)%P(I)%Y-y0)*cos(theta)T(2)%P(I)%X=T(2)%P(I)%X+x0T(2)%P(I)%Y=T(2)%P(I)%Y+y0end doend subroutine rotate

This subroutine actually draws the triangle T in the colourspecified by the integer col

When the program executes the statement draw_line theline is not immediately drawn to the screen but is held inmemory. Drawing to the screen only takes place when thecomputer has a bit of slack time. Thus we find that all thetriangles are drawn at the end of the program which isn’tmuch use as all we see it the last triangle to be drawn sincewhat happens, happens very quickly. To force the system todraw immediately to the screen we use the subroutineperform_graphics_update@().

Indeed I force the system to draw all the triangle it hasstored up when the draw colour is not the backgroundcolour. This has the effect of deleting a triangle and thendrawing a new one.

The subroutine perform_graphics_update is provided for usbut needs to be included as an extra into our subroutineusing include<windows.ins>

subroutine drawtriangle(T,col)use geominclude<windows.ins>type(triangle)Tinteger colcall draw_line@(T%P(1)%X,T%P(1)%Y,T%P(2)%X,T%P(2)%Y,col)call draw_line@(T%P(2)%X,T%P(2)%Y,T%P(3)%X,T%P(3)%Y,col)call draw_line@(T%P(3)%X,T%P(3)%Y,T%P(1)%X,T%P(1)%Y,col)if (col/=bkcol)call perform_graphics_update@()end

If you manage to type in and run this program thenyou really should spend some time working out what

24

is actually taking place in the program. What is thefunction of each segment and how it achieves its task.

It is not an exercise in typing!

The End