Defining Your Own Subroutines

A subroutine is structured much like a function, except that it does not have a return value. Calling custom-written subroutines also differs slightly from calling intrinsic subroutines like write, print, and read, in that the arguments are enclosed in parentheses and we use the keyword call before the subroutine name.

!-----------------------------------------------------------------------
!   Program description:
!       Swap two integer values
!-----------------------------------------------------------------------

!-----------------------------------------------------------------------
!   Modification history:
!   Date        Name        Modification
!   2011-03-23  Jason Bacon Begin
!-----------------------------------------------------------------------

module subprograms
    interface
        subroutine swap(num1, num2)
        integer, intent(inout) :: num1, num2
        end subroutine
    end interface
end module

! Main program body
program subroutine_example
    use subprograms
    
    ! Disable implicit declarations (i-n rule)
    implicit none
    
    ! Variable defintions
    integer :: x, y
    
    ! Statements
    print *, 'Enter x and y on one line:'
    read *, x, y
    call swap(x, y)
    print *, 'x = ', x, 'y = ', y
end program


!-----------------------------------------------------------------------
!   Description:
!       Swap the contents of two integer variables
!
!   Arguments:
!       num1, num2: References to the variables to swap
!-----------------------------------------------------------------------

!-----------------------------------------------------------------------
!   Modification history:
!   Date        Name        Modification
!   2011-03-23  Jason Bacon Begin
!-----------------------------------------------------------------------

subroutine swap(num1, num2)

    ! Disable implicit declarations (i-n rule)
    implicit none
    
    ! Dummy variables
    integer, intent(inout) :: num1, num2

    ! Local variables
    integer :: temp

    temp = num1
    num1 = num2
    num2 = temp
end subroutine