1.3 Programming Basics
1. Hello World Program
program HelloWorld print *, 'Hello, World!'end program HelloWorldTo 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./helloworldThis 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 ENDExplanation
-
Main Program:
- The
COMMON /SharedVars/ A, B, Cstatement declares a common block namedSharedVarsthat includes the variablesA,B, andC. - The variables
A,B, andCare assigned values1.0,2.0, and3.0respectively. - The
CALL PrintSharedVarsstatement calls the subroutinePrintSharedVars.
- The
-
Subroutine
PrintSharedVars:- The
COMMON /SharedVars/ A, B, Cstatement declares the same common blockSharedVarsand 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_exampleThe output will be:
A = 1.000000 B = 2.000000 C = 3.000000This demonstrates that the variables A, B, and C are shared between the main program and the subroutine through the common block SharedVars.