Skip to content

1.3 Programming Basics

1. Hello World Program

Terminal window
program HelloWorld
print *, 'Hello, World!'
end program HelloWorld

To compile and run this program, you can use a Fortran compiler like gfortran. Save the code in a file with a .f90 extension, for example, helloworld.f90, and then use the following commands in your terminal:

Terminal window
gfortran -o helloworld helloworld.f90
./helloworld

This will compile the Fortran code and execute the resulting program, displaying the message “Hello, World!” on the screen.

2. COMMON keyword

In Fortran 77, the COMMON keyword is used to define and share variables among different program units (such as functions, subroutines, or the main program). This allows for global variables that can be accessed and modified by multiple parts of the program.

Here is an example to illustrate the use of the COMMON keyword in Fortran 77:

Example

PROGRAM Main
COMMON /SharedVars/ A, B, C
A = 1.0
B = 2.0
C = 3.0
CALL PrintSharedVars
END
SUBROUTINE PrintSharedVars
COMMON /SharedVars/ A, B, C
PRINT *, 'A = ', A
PRINT *, 'B = ', B
PRINT *, 'C = ', C
END

Explanation

  1. Main Program:

    • The COMMON /SharedVars/ A, B, C statement declares a common block named SharedVars that includes the variables A, B, and C.
    • The variables A, B, and C are assigned values 1.0, 2.0, and 3.0 respectively.
    • The CALL PrintSharedVars statement calls the subroutine PrintSharedVars.
  2. Subroutine PrintSharedVars:

    • The COMMON /SharedVars/ A, B, C statement declares the same common block SharedVars and the same variables A, B, and C.
    • The PRINT * statements print the values of A, B, and C.

Compilation and Execution

Save the code in a file with a .f extension, for example, common_example.f, and then use the following commands in your terminal:

Terminal window
gfortran -o common_example common_example.f
./common_example

The output will be:

A = 1.000000
B = 2.000000
C = 3.000000

This demonstrates that the variables A, B, and C are shared between the main program and the subroutine through the common block SharedVars.