0

I tried to write a code which gives GCD of two number:

program main 
    implicit none
    integer::A,B,gcd,ans=0
    read*,A,B
    gcd(A,B)
    write(*,*)'GCD of ',A,' and ',B,': ',ans
end program main

recursive function gcd(A,B) result(ans)
    implicit none 
    integer,intent(in)::A,B
    integer::ans
    if (A==0) ans=B
    if (B==0) ans=A
!base_case
    if (A==B) ans=A
!recursive_case
    if (A>B)then
        ans=gcd(A-B,B)
    else 
        ans=gcd(A,B-A)
    end if 
end function gcd

My input was:

98 56

I expect 14 but got this error:

source_file.f:5:4:

     gcd(A,B)
    1
Error: Unclassifiable statement at (1)

I didn't understand why I am getting this error? I heartily thank if anyone explain me why am I getting error.

NJN
  • 269
  • 1
  • 4
  • 14

1 Answers1

4

You cannot specify intent(out) or any other intent or related attribute for the result variable. See Fortran array cannot be returned in function: not a DUMMY variable

Use just

integer::ans

In addition, just

gcd(A,B)

is not a valid way to use a function in Fortran. Use

ans = gcd(A,B)

or

print *, gcd(A,B)

or similar.

Please realize that ans declared in the main program is a variable that is not related to the result variable of the function. Even if the name is the same, they are two different things. It will be better to rename one of them to make it clear.

  • I apply your answer yet getting another error @Vladimir F – NJN Jan 06 '20 at 12:44
  • @NajmunNahar That is some different error. This time a run-time error. It is probably the time to open a new question. Enable **all debug options** in your compiler. Use `gfortran -g -Wall -fcheck=all`. Check all your if branches. Dont you have some infinite recursion somewhere? Show that in a new question. Shouldn't you have `<=1` instead of `==0` in your if branches? – Vladimir F Героям слава Jan 06 '20 at 12:46
  • Sorry I haven't installed gfortran. I use an online compiler to run this code [this](https://rextester.com/GNVCD37686) Ok I deleted `if (A==0)` and `if (B==0)` branch although the error occur – NJN Jan 06 '20 at 12:50
  • @NajmunNahar You cannot just delete those branches, you should go through and understand what is happening. Print A and B inside the function to see where the problem is. You almost certainly have some unlimited recursion. I do think it should be asked in a **new question**. Do not just change the title of this one. You cannot iteratively ask something new in the same question. You should have accepted the duplicate link and ask a **new question**. You really do need a proper compiler to do proper debugging. Notice that you **must** have some more `else` and `else if` in your function. – Vladimir F Героям слава Jan 06 '20 at 13:23