I am trying to understand how recursive subroutine works. For example this recursive function calculates fibonacci number.
RECURSIVE FUNCTION fibonacci(n) RESULT(fibo)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: fibo
IF (n <= 2) THEN
fibo = 1
ELSE
fibo = fibonacci(n-1) + fibonacci(n-2)
END IF
END FUNCTION fibonacci
Unfortunately I cant calculate it with recursive subroutines.
RECURSIVE SUBROUTINE fibonacci(n)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: fibo
IF (n <= 2) THEN
fibo = 1
ELSE
CALL fibonacci(n-1) + fibonacci(n-2)
END IF
END SUBROUTINE fibonacci
I can sum 2 fibonacci function in recursive functions but not in recursive subroutines. The problem is that how i can call fibonacci subrioutine recursively in recursive subroutines with CALL method?
Subroutines are not that nice for this particular problem. Nonrecursive solution would be more readable. You tried to use subroutine as a function. You cannot do that, they are very different. You must use them only in the call
statement and only one at a time. If you want some result, you must use an argument for that.
RECURSIVE SUBROUTINE fibonacci(n,fibo)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER, INTENT(OUT) :: fibo
INTEGER :: tmp
IF (n <= 2) THEN
fibo = 1
ELSE
CALL fibonacci(n-1,fibo)
CALL fibonacci(n-2,tmp)
fibo = fibo + tmp
END IF
END SUBROUTINE fibonacci
call fibonacci(5,i)
print *, i
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With