The following is a program which contains
(1) A non-recursive FUNCTION called FUN_SUM.
(2) A recursive FUNCTION called REC_ FUN_SUM.
(3) A non-recursive SUBROUTINE called SUB_SUM.
(4) A recursive SUBROUTINE called REC_SUB_SUM.
All of the above internal FUNCTIONS/SUBROUTINES compute the sum of the positive integers greater than or equal to 1 and less than or equal to N. Thus the input for each one of them is N, where N is a positive integer, and the output is the sum of the integers greater than or equal to 1 and less than or equal to N.
The program asks the reader to enter a positive integer, which will be called N, and it displayes the sum (described above) as it is computed by each FUNCTION/SUBROUTINE.
PROGRAM PROG_SUM
IMPLICIT NONE
INTEGER :: N, Z
PRINT *, “Enter a positive integer N”
READ *, N
PRINT *, “Sum= “, FUN_SUM(N), “ by non-recursive FUNCTION”
PRINT *, “Sum= “, REC_FUN_SUM(N), “ by recursive FUNCTION”
CALL SUB_SUM(N,Z)
PRINT *, “Sum= “, Z, “ by non-recursive SUBROUTINE”
CALL REC_SUB_SUM(N,Z)
PRINT *, “Sum= “, Z, “ by recursive SUBROUTINE”
CONTAINS
FUNCTION FUN_SUM(N)
INTEGER, INTENT(IN) :: N
INTEGER :: FUN_SUM, I
FUN_SUM=0
DO I=1, N
FUN_SUM=FUN_SUM+I
END DO
END FUNCTION FUN_SUM
RECURSIVE FUNCTION REC_FUN_SUM(N) RESULT (MySum)
INTEGER, INTENT(IN) :: N
INTEGER :: MySum
IF (N==1) THEN
MySum=1
ELSE
MySum=N+REC_FUN_SUM(N-1)
END IF
END FUNCTION REC_FUN_SUM
SUBROUTINE SUB_SUM(N, MySum)
INTEGER, INTENT(IN) :: N
INTEGER, INTENT(OUT) :: MySum
INTEGER :: I
MySum=0
DO I=1, N
MySum=MySum+I
END DO
END SUBROUTINE SUB_SUM
RECURSIVE SUBROUTINE REC_SUB_SUM(N, MySum)
INTEGER, INTENT(IN) :: N
INTEGER, INTENT(OUT) :: MySum
IF (N==1) THEN
MySum=1
ELSE
CALL REC_SUB_SUM(N-1, MySum)
MySum=N+MySum
END IF
END SUBROUTINE REC_SUB_SUM
END PROGRAM PROG_SUM