!------------------------------------------------------------------------------
!
!  Program name:
!
!    odd_values
!
!  Purpose:
!
!    This program creates an integer array whose size is allocated dynamically
!    (read size from terminal), assigns odd and even values to the array (same
!    as matrix.f90), and passes the array to a subroutine which uses an 
!    assumed shape argument and returns all odd values of the array and 0 
!    elsewhere.
!
!------------------------------------------------------------------------------

PROGRAM odd_values

  IMPLICIT NONE
  INTEGER, DIMENSION (:,:), ALLOCATABLE :: ia
  INTEGER :: i, j, n, status

  ! Read size of matrix and allocate array:

  WRITE (*,'(A)',ADVANCE='NO') 'Input matrix size: '
  READ (*,'(I4)') n
  ALLOCATE (ia(n,n), STAT = status)

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

  ! Assign matrix ia with DO loops - SHAPE parameter in RESHAPE must be
  ! a constant, so cannot use variable size as in the following:
  !
  ! ia = RESHAPE( (/ (((i + j*10), j=1,n), i=1,n) /), SHAPE = (/ n,n /) )

  WRITE(*,'(//"Assign with DO loops:"/)')
  DO i=1,n
    DO j=1,n
      ia(j,i) = i + j*10
    END DO
  END DO
  DO i=1,n
    WRITE(*,'(10i5)') ia(i,:)
  END DO

  CALL odds(ia)
  WRITE(*,'(//"Array of odd values and zeroes:"/)')
  DO i=1,n
    WRITE(*,'(10i5)') ia(i,:)
  END DO

  DEALLOCATE (ia)

CONTAINS

  SUBROUTINE odds(ia)

    IMPLICIT NONE
    INTEGER, DIMENSION (:,:) :: ia

    ! Array of odd values and zeroes using WHERE:

    WHERE ( MOD(ia,2) == 1)
      ia = ia
    ELSEWHERE
      ia = 0
    END WHERE

  END SUBROUTINE odds

END PROGRAM odd_values







