!------------------------------------------------------------------------------
!
!  Program name:
!
!    sum4
!
!  Purpose:
!
!    This program sums all elements of a two dimensional array. It shows 
!    how to use an assumed shape array to remove the necessity to pass array 
!    dimensions into the subroutine.
!    
!
!------------------------------------------------------------------------------

PROGRAM sum4

  IMPLICIT NONE
  REAL, DIMENSION (:,:), ALLOCATABLE :: ra
  INTEGER :: i, j, n1, nsum, status

  WRITE (*,'("Input matrix size:")')
  READ (*,*) n1
  ALLOCATE (ra(n1,n1), STAT = status)

  IF (status > 0) STOP 'Fail to allocate memory for allocatable array'

  DO i=1,n1
    DO j=1,n1
      ra(j,i) = (i-1)*n1 + j
    END DO
  END DO

  CALL sumsub(ra,nsum)
  WRITE (*,'("Sum for matrix of size ",I3," = ",I10)') n1,nsum

  DEALLOCATE (ra)

CONTAINS

  SUBROUTINE sumsub(ra,nsum)

    REAL, DIMENSION (:,:) :: ra
    INTEGER :: nsum, n1, i, j

    nsum = 0
    n1 = SIZE(ra,2)
    DO  i=1,n1
      DO j=1,n1
        nsum = nsum + ra(j,i)
      END DO
    END DO

    RETURN

  END SUBROUTINE sumsub

END PROGRAM sum4



