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

DO Loops

Although the annual repayments on a home loan are usually fixed, the outstanding balance does not decline linearly with time. The next program demonstrates this with the aid of a DO-loop.

 
      PROGRAM REDUCE 
      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 
      WRITE(UNIT=*, FMT=*)'End of Year  Balance' 
      DO 15,IYEAR = 1,NYEARS 
          AMOUNT = AMOUNT + (AMOUNT * RATE) - REPAY 
          WRITE(UNIT=*, FMT=*) IYEAR, AMOUNT  
15    CONTINUE 
      END
The first part of the program is similar to the earlier one. It continues with another WRITE statement which produces headings for the two columns of output which will be produced later on.

The DO statement then defines the start of a loop: the statements in the loop are executed repeatedly with the loop-control variable IYEAR taking successive values from 1 to NYEARS. The first statement in the loop updates the value of AMOUNT by adding the annual interest to it and subtracting the actual repayment. This results in AMOUNT storing the amount of the loan still owing at the end of the year. The next statement outputs the year number and the latest value of AMOUNT. After this there is a CONTINUE statement which actually does nothing but act as a place-marker. The loop ends at the CONTINUE statement because it is attached to the label, 15, that was specified in the DO statement at the start of the loop.

The active statements in the loop have been indented a little to the right of those outside it: this is not required but is very common practice among Fortran programmers because it makes the structure of the program more conspicuous.

The program REDUCE produces a table of values which, while mathematically correct, is not very easy to read:

 
Enter amount, % rate, years 
2000, 9.5, 5 
Annual repayments are    520.8728     
End of Year  Balance 
      1   1669.127     
      2   1306.822     
      3   910.0968     
      4   475.6832     
      5  2.9800416E-04



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