user2241691
user2241691

Reputation: 9

Gfortran do loop if-statement error

I have a simple Fortran code, and I am getting an error that I cannot find a solution to. Does anyone know how to fix this?

subroutine sort(A,A_done,N,P)
! Sort a real array by algebraically increasing value and return the permutation that 
! rearranges the array
  implicit none

  Integer N, TEMP1, K, L, P(N), TEMP2
  real(8), dimension(:) ::  A_done
  real(8), dimension(:) ::  A

  DO K=1, N-1
    DO L=K+1, N
        if A(K)>A(L)
                TEMP1=A(K)
            TEMP2=P(K)
            A(K)=A(L)
                P(K)=P(L)
        A(L)=TEMP1
            P(L)=TEMP2
    end if

    END DO
  END DO
  A_done=A
  RETURN
  END

gfortran -Wall -Werror -fbounds-check -w -L -lm -o Simulation readinput.for noutfile.for mean.for covariance.for correlation.for rperm.for simmain.for sort.for In file sort.for:13

     if A(K)>A(L)
    1

Error: Unclassifiable statement at (1) In file sort.for:20

    end if
      1

Error: Expecting END DO statement at (1) make: * [Simulation] Error 1

Thanks for the help

Upvotes: 0

Views: 3142

Answers (1)

MakisH
MakisH

Reputation: 1183

You have forgotten a pair of parentheses and a "then":

At if A(K)>A(L) you must type if (A(K)>A(L)) then

Other than that, your code has multiple issues:

  1. At TEMP1=A(K) and similar expressions, you pass a real(8) value to an integer variable
  2. I don't understand what the P variable does (could you describe please?), but you also mix real(8) and integer there.
  3. You MUST specify the dimension of the arrays in the subroutine. (I think there is a way not doing so by using modules)
  4. Keep in mind that you change A and then you copy it to A_done. Why to do so? You lose your original values and consume more memory.

I have made some corrections that you may want to keep, you may make more. This code compiles and runs well.

Program test

    implicit none
    integer N
    real(8), allocatable :: A(:), A_done(:), P(:)

    N=5
    Allocate (A(N), A_done(N), P(N))

    A=(/5,3,6,1,9/)
    call sort(A, A_done, N, P)

    Write (*,*) A_done

End

subroutine sort(A,A_done,N,P)
! Sort a real array by algebraically increasing value and return the permutation that 
! rearranges the array
    implicit none

    Integer N, K, L
    real(8), dimension(N) ::  A, A_done, P
    real(8) :: TEMP1, TEMP2

    DO K=1, N-1
            DO L=K+1, N
                    if (A(K)>A(L)) then
                            TEMP1=A(K)
                            TEMP2=P(K)

                            A(K)=A(L)
                            P(K)=P(L)

                            A(L)=TEMP1
                            P(L)=TEMP2
                    end if
            END DO
    END DO
    A_done=A
    RETURN
END 

Upvotes: 1

Related Questions