!------------------------------------------------------------------------------
!
!  Program name:
!
!    sum3
!
!  Purpose
!
!    This program shows how to use allocatable array to declare an array 
!    with required size, so no incompatibility when pass whole array. 
!    It sums all elements of a two dimensional array. 
!
!------------------------------------------------------------------------------

PROGRAM sum3

  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,n1,nsum)
  WRITE (*,'("Sum for matrix of size ",I3," = ",I10)') n1,nsum

  DEALLOCATE (ra)

CONTAINS 

  SUBROUTINE sumsub(ra, n1, nsum)

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

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

    RETURN

  END SUBROUTINE sumsub

END PROGRAM sum3

