1.3 Programming Basics
1. Hello World Program
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:
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
-
Main Program:
- The
COMMON /SharedVars/ A, B, C
statement declares a common block namedSharedVars
that includes the variablesA
,B
, andC
. - The variables
A
,B
, andC
are assigned values1.0
,2.0
, and3.0
respectively. - The
CALL PrintSharedVars
statement calls the subroutinePrintSharedVars
.
- The
-
Subroutine
PrintSharedVars
:- The
COMMON /SharedVars/ A, B, C
statement declares the same common blockSharedVars
and the same variablesA
,B
, andC
. - The
PRINT *
statements print the values ofA
,B
, andC
.
- The
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:
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
.