Subroutines
Subroutine Subprograms Common features of Subroutines and functions –They perform particular tasks under the control of some other program unit. –They have the same basic form: Heading Specification Part Execution Part END statement
Subroutine Subprograms Common features of Subroutines and functions –They may be internal, module, or external. –Same scope rules apply to both. –They may be used as arguments –They may be recursive
Subroutine Subprograms Subroutines and functions differ in...: –Functions are designed to return a single value, Subroutines often return more than one value (or they may return no value at all). –Functions return values via functions names; subroutines return values via arguments. –A function is referenced by using its name in an expression, whereas a subroutine is referenced by a CALL statement
The form of a subroutine SUBROUTINE name (formal-argument-list) Specification Part Execution Part END SUBROUTINE statement
Invoking a Subroutine CALL subroutine-name (actual-argument-list)
PROGRAM Angles_1 IMPLICIT NONE INTEGER :: NumDegrees, NumMinutes, NumSeconds CHARACTER(1) :: Response ! Read and convert angles until user signals no more data DO WRITE (*, '(1X, A)', ADVANCE = "NO") & "Enter degrees, minutes, and seconds: " READ *, NumDegrees, NumMinutes, NumSeconds CALL PrintDegrees(NumDegrees, NumMinutes, NumSeconds) WRITE (*, '(/ 1X, A)', ADVANCE = "NO") "More (Y/N)? " READ *, Response IF (Response /= "Y") EXIT END DO
CONTAINS SUBROUTINE PrintDegrees(Degrees, Minutes, Seconds) INTEGER, INTENT(IN) :: Degrees, Minutes, Seconds PRINT 10, Degrees, Minutes, Seconds, & REAL(Degrees) + REAL(Minutes)/ REAL(Seconds)/ FORMAT (1X, I3,” degrees", I3," minutes",I3," seconds" & / 1X, "is equivalent to" / 1X, F7.3, " degrees") END SUBROUTINE PrintDegrees END PROGRAM Angles_1
Converting Coordinates Example X= r cos Ø Y= r sin Ø P(r, Ø) r Ø
PROGRAM Polar_to_Rectangular IMPLICIT NONE REAL :: RCoord, TCoord, XCoord, YCoord CHARACTER(1) :: Response DO WRITE (*, '(1X, A)', ADVANCE = "NO") & "Enter polar coordinates (in radians): " READ *, RCoord, TCoord CALL Convert_to_Rectangular(RCoord, TCoord, XCoord, YCoord) PRINT *, "Rectangular coordinates:", XCoord, YCoord WRITE (*, '(/ 1X, A)', ADVANCE = "NO") & "More points to convert (Y or N)? " READ *, Response IF (Response /= "Y") EXIT END DO
CONTAINS SUBROUTINE Convert_to_Rectangular(R, Theta, X, Y) REAL, INTENT(IN) :: R, Theta REAL, INTENT(OUT) :: X, Y X = R * COS(Theta) Y = R * SIN(Theta) END SUBROUTINE Convert_to_Rectangular END PROGRAM Polar_to_Rectangular