next up previous contents index
Next: Integer and Real Data Up: Basic Fortran Concepts Previous: Statements

Expressions and Assignments

The next example solves a somewhat more realistic problem: it computes the repayments on a fixed-term loan (such as a home mortgage loan). The fixed payments cover the interest and repay part of the capital sum; the annual payment can be calculated by the following formula:

displaymath3009

In this formula, rate is the annual interest rate expressed as a fraction; since it is more conventional to quote interest rates as a percentage the program does this conversion for us.

 
       PROGRAM LOAN 
       WRITE(UNIT=*, FMT=*)'Enter amount, % rate, years' 
       READ(UNIT=*, FMT=*) AMOUNT, PCRATE, NYEARS 
       RATE = PCRATE / 100.0 
       REPAY = RATE * AMOUNT / (1.0 - (1.0+RATE)**(-NYEARS)) 
       WRITE(UNIT=*, FMT=*)'Annual repayments are ', REPAY 
       END
This example introduces two new forms of statement: the READ and assignment statements, both of which can be used to assign new values to variables.

The READ statement has a similar form to WRITE: here it reads in three numbers entered on the terminal in response to the prompt and assigns their values to the three named variables. FMT=* again selects list-directed (or free-format) input which allows the numbers to be given in any convenient form: they can be separated by spaces or commas or even given one on each line.

The fourth statement is an assignment statement which divides PCRATE by 100 and assigns the result to another variable called RATE. The next assignment statement evaluates the loan repayment formula and assigns the result to a variable called REPAY.

Several arithmetic operators are used in these expressions: as in most programming languages ``/'' represents division and ``*'' represents multiplication; in Fortran ``**'' is used for exponentiation, i.e. raising one number to the power of another. Note that two operators cannot appear in succession as this could be ambiguous, so that instead of ``**-N'' the form ``**(-N)'' has to be used.

Another general point concerning program layout: spaces (blanks) are not significant in Fortran statements so they can be inserted freely to improve the legibility of the program.

When the program is run, the terminal dialogue will look something like this:

 
Enter amount, % rate, years 
20000, 9.5, 15 
Annual repayments are    2554.873
The answer given by your system may not be exactly the same as this because the number of digits provided by list-directed formatting depends on the accuracy of the arithmetic, which varies from one computer to another.


next up previous contents index
Next: Integer and Real Data Up: Basic Fortran Concepts Previous: Statements

Mario Storti
Wed Nov 4 19:32:56 ART 1998