Fortran Program Structure

The general layout of a simple Fortran program includes the following components:

  1. A block comment describing the program.
  2. Main program body (required):
    1. program <program-name>
    2. Optional use statements to enable extended features (like C #includes, but more abstract)
    3. Variable definitions/declarations + comments
    4. Program statements + comments
    5. end program <program-name>

Fortran is not case sensitive, so end is the same as END or End.

Example 16.2. A Simple Fortran Program

!-----------------------------------------------------------------------
!   Description:
!       Compute the area of a circle given the radius as input.
!
!   Modification history:
!   Date        Name        Modification
!   2011-02-16  Jason Bacon Begin
!-----------------------------------------------------------------------

!-----------------------------------------------------------------------
! Main program body

program Circle_area
    use iso_fortran_env     ! Enable error_unit for error messages
    
    ! Disable implicit declarations (i-n rule)
    implicit none

    ! Constants
    real(8), parameter :: PI = 3.1415926535897932d0
    
    ! Variable definitions for main program
    real(8) :: radius, &
                        area
    
    ! Main program statements
    print *, 'What is the radius of the circle?'
    read *, radius
    if ( radius >= 0 ) then
        area = PI * radius * radius
        print *, 'The area is ', area
    else
        write(error_unit,*) 'The radius cannot be negative.'
    endif
end program


Fortran was originally designed as a line-oriented language, which means that the end of a line marks the end of a statement. Most newer languages, in contrast, are free-format, so that a single statement can span many lines, or multiple statements may be on the same line. Languages such as C, C++, and Java use a semicolon to mark the end of each statement, and line structure is completely ignored.

Fortran 90 introduced a more flexible source code format than previous versions, but still uses the end of a line to mark the end of a statement. If a particular statement is too long to fit on the screen, it can be continued on the next line by placing an ampersand (&) at the end of the line to be continued, the same way we use a backslash (\) in a shell script:

print *, 'This message is too long to fit on a single line, ', &
         'so we use the continuation character to break it up.'

Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What are the components of a Fortran program?

  2. What is a line-oriented language? Can a statement span more than one line in a line-oriented language?