Search code examples
fortranconditional-statementsgfortranfortran95

Fortran Basic Conditional and Loop Code Errors


I'm doing a very basic Fortran tutorial to learn it for grad school and I input the codes for conditionals and loops exactly as they were written in the tutorial but I keep getting the "unexpected end of file" error when I try to compile with gfortran.

This is my conditional code:

if (angle < 90.0) then

    print *, 'Angle is acute'

else if (angle < 180.0) then

    print *, 'Angle is obtuse'

else

    print *, 'Angle is reflex'

end if

This is my loop code:

integer :: i

    do i=1,10,2
    
        print *, i ! print odd numbers
    end do

Both of them are completed with end statements, so I'm not sure what else it wants. I've only just started teaching myself today, so I'm still just copying codes verbatim from the tutorial and not sure how to troubleshoot anything.


Solution

  • In the tutorial you are following the pieces of code shown are not complete programs. They cannot be compiled as they are.

    You will see this frequently, especially in answers on this site.

    The code fragments shown miss a lot of context to make clear the parts that are to be taught. That's perhaps a little unfortunate, but Fortran is quite a verbose language, and so there's a trade-off for clarity.

    For a complete program you've possibly seen that "all programs must have an end statement to complete them". You may think that the end if and end do statements are suitable for this. They are not: you need an end program statement. The following are two minimal programs:

    end
    

    and

    end program
    

    (There are also forms with a program statement.)

    That is:

    if (.true.) then
      print *, "Hello, world!"
    end if
    
    end program
    

    is compilable if and only if that last line exists.

    Further, things like implicit none and variable declarations and definitions would be part of the implied context of example fragments.