next up previous contents
Next: Salaries Example Up: Summation Example Previous: Summation Example

Solution

 PROGRAM Summation
   INTEGER, PARAMETER :: n_miles=20, stretch=5
   REAL :: maxcost = TINY(0.0), cost5
   REAL, DIMENSION(n_miles) :: cost = &
   (/6.3, 7.6, 9.2, 3.4, 5.6, 7.23, 9.76, 6.83, 5.45, 4.56, &
     4.86, 5.8, 6.4, 7.43, 7.8, 8.6, 9.25, 8.9, 8.4, 7.23/)
   INTEGER :: start 
   DO I = 1, n_miles-stretch+1
     cost5 = 0
     DO J= I, I+stretch-1
       cost5 = cost5 + cost(J)
     END DO
     IF(cost5 > maxcost)THEN
       maxcost=cost5
       start = I
     END IF
   END DO
   PRINT*, &
    ' The most expensive ',stretch,' mile stretch is', & 
    ' from ',start,' to ',start+stretch,' and costs ',maxcost
 END PROGRAM Summation

Or, using whole array notation:

 PROGRAM Summation2
   INTEGER, PARAMETER :: n_miles=20, stretch=5
   INTEGER, PARAMETER :: n_stretches = n_miles-stretch+1
   INTEGER, DIMENSION(1) :: start  ! needed for result of MAXLOC
   REAL :: maxcost
   REAL, DIMENSION(n_stretches) :: cost5
   REAL, DIMENSION(n_miles) :: cost = &
   (/6.3, 7.6, 9.2 ,3.4, 5.6, 7.23 ,9.76, 6.83, 5.45, 4.56, &
     4.86, 5.8, 6.4, 7.43, 7.87, 8.6, 9.25, 8.9, 8.4, 7.23/)
   DO I= 1, n_stretches
     cost5(I) = SUM(cost(I:I+stretch-1))
   END DO
   maxcost = MAXVAL(cost5)
   start = MAXLOC(cost5)
   PRINT*, &
    ' The most expensive ',stretch,' mile stretch is', &
    ' from ',start,' to ',start+stretch,' and costs ',maxcost
 END PROGRAM Summation2

Note that the whole array solution involves the extra storage for the array cost.


next up previous contents
Next: Salaries Example Up: Summation Example Previous: Summation Example

©University of Liverpool, 1997
Thu May 29 10:11:26 BST 1997
Not for commercial use.