Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Recursive Subroutine works in fortran?

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?

like image 272
cyb0k Avatar asked Mar 19 '23 16:03

cyb0k


1 Answers

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
like image 81
Vladimir F Героям слава Avatar answered Mar 24 '23 09:03

Vladimir F Героям слава