Understanding FORTRAN: A Simple Programming Language, Study notes of Earth Sciences

An introduction to the fortran programming language, focusing on its syntax, compiling process, and basic concepts such as expressions and assignment statements. It covers the layout of a fortran source code, the difference between constants and variables, and the use of arithmetic operators. The document also explains the importance of meaningful variable names and the use of named constants.

Typology: Study notes

Pre 2010

Uploaded on 08/30/2009

koofers-user-eys-1
koofers-user-eys-1 🇺🇸

5

(1)

10 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 2
The Baby Steps
Computers can do arithmetic, logical operation, storing and retrieving data, and
communicate with users via its input/output ports. A program is needed to coordi-
nate these elementary operations so that useful tasks can be performed. A program
is then a list of directions that tells the machine what operation to perform next.
In procedural languages such as FORTRAN, the directions are executed one at a
time in the order they are encountered.
2.1 The notorious “Hello World”
A very simple program to get us started is listed below, the textbook lists in the
F77 version and here it is in its F90 glory:
! Anything after an exclamation mark is a comment
! This is a simple code
program hello_world ! start and name of program, optional in F77
print *,’Hello World!’ ! print command
stop ! program terminates
end program hello_world ! end of program , F77 accepts "end" only
The programs simply prints the sentence ”Hello World!” and stops. Here are some
remarks about the code:
The program is just text entered with an editor such as emacs. The text is
referred to as source code.
Any text after an exclamation mark is a comment and is not processed by
the compiler. It is there for documentation purposes. The fixed
The other lines of codes are FORTRAN statements. Some of them, such as
print and stop are executable statements in that they direct the computer
to do something such as print or stop the program and return control to the
11
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Understanding FORTRAN: A Simple Programming Language and more Study notes Earth Sciences in PDF only on Docsity!

Chapter 2

The Baby Steps

Computers can do arithmetic, logical operation, storing and retrieving data, and communicate with users via its input/output ports. A program is needed to coordi- nate these elementary operations so that useful tasks can be performed. A program is then a list of directions that tells the machine what operation to perform next. In procedural languages such as FORTRAN, the directions are executed one at a time in the order they are encountered.

2.1 The notorious “Hello World”

A very simple program to get us started is listed below, the textbook lists in the F77 version and here it is in its F90 glory:

! Anything after an exclamation mark is a comment ! This is a simple code program hello_world! start and name of program, optional in F print *,’Hello World!’! print command stop! program terminates end program hello_world! end of program , F77 accepts "end" only

The programs simply prints the sentence ”Hello World!” and stops. Here are some remarks about the code:

  • The program is just text entered with an editor such as emacs. The text is referred to as source code.
  • Any text after an exclamation mark is a comment and is not processed by the compiler. It is there for documentation purposes. The fixed
  • The other lines of codes are FORTRAN statements. Some of them, such as print and stop are executable statements in that they direct the computer to do something such as print or stop the program and return control to the

12 CHAPTER 2. THE BABY STEPS

operating system. Other statements, such as program and end program are non-executable and are needed by the compiler to process the source code.

  • Each line not beginning with a comment sign is a statement. The end of a line denotes the end of a statement unless the line is continued with a continuation sign; in F90 that is a & sign at the end of the line. Comment lines cannot be continued and must start with a comment sign.
  • The text shown has been entered in free-form as opposed to the fixed form required by F77. The old dialect required that the first 6 spaces be reserved for statement labels (the first 5 columns), for a continuation character (the 6 th column). The line also had to end on column 72.
  • The F77 standard required that all characters be capitalized. Many compiler permitted lower case characters, however, the requirement has been dropped since the F90 revision to the standard.
  • The Stop statement causes the program to terminate and control is handed back to the operating system.
  • The print statement causes the string constant “Hello World!” to be printed. The * instructs the compiler to use default formatting to print the string. Syntax rules have to be followed for the compiler to recognize the fields within a statement. The main focus here is on the semantics and meaning of the statements; and on how best to use it to structure your calculation.

2.2 Compiling the code

The next step is to translate the FORTRAN source code into a machine language native to the computer’s processor. The machine language calls on the processor’s instruction set to do the low level operations needed to carry out the execution of the program, like adding add two numbers. A compiler translates the FORTRAN source code into object files containing the machine language instructions. In general programs must interact with the operating system to carry out the tasks (like taking input from the keyboard) and printing output on the screen. This interaction takes place via system libraries, essentially low level machine in- structions, that must be inserted before the program is ready for execution. This insertion is called the linkage editing and is done with a program called the loader, Linux command ld. On most unix machine the compiler takes care of calling the loader automatically to link the object files and the system libraries. At this point an executable file is produced; its name default defaults to a.out on Linux ma- chines. Notice that you cannot “read” the object files nor the executable as they are store machine language instructions.

14 CHAPTER 2. THE BABY STEPS

Chapter 3

Expressions and Assignment

Statements

The “Hello World” program was used to illustrate the layout of a FORTRAN source code. Here is another example that is more numerical in character to illustrate additional concepts found in FORTRAN.

! ! find the hypotenuse of a right triangle ! program hypotenuse implicit none

!.Variable declaration real :: a! length of one side real :: b! length of perpendicular side real :: hyp! length of hypotenus

a = 4.0! assignment of input data b = 3.0! assignment of input data

hyp = sqrt(a2+b2)! calculation print *,hyp! output

stop end program hypotenuse

Notice the layout of the program. First is the declaration of variables and the input, then comes the calculations and finally the output. Comments are used to document the meaning of the different variables and the task of the code hy- potenuse. Finally indenting the code is a good practice to delineate visually the

3.3. NAMED CONSTANTS 17

Traditional fortran has relied on implicit typing rules whereby variables whose name starts with the letter, i, j, k, l, m, or n, otherwise they are real variables. This practice of implicit typing rules is actually discouraged as countless bugs are introduced by simply mistyping the name of a variable. Instead programmers are urged to use implicit none to override the default typing behavior and force the programmer to declare every single variable used in the code. Undeclared variables will be caught at compile time and flagged, instead of the user tripping on these bugs at run time. Programmers are urged to pick meaningful names for their variables to help in documenting their program. Finally notice that every new variables must be assigned a value before using it in a calculation. The hypotenuse code declares 3 real variables at the beginning; two of these are input data and one is an output. The a and b variables are assigned constant real values while the hyp is assigned its value after a calculation. A traditional variable declaration takes the form

intrinsic_data_type variable_name

For example

integer e real pi

Fortran 90 allows additional properties to be assigned to a variable, these are attributes, and the declaration takes the form

intrinsic_data_type, attribute_list :: variable_name

3.3 Named Constants

A simple example of an attribute is to declare named constants using the parameter keyword. Parameters are variables whose value does not change throughtout the calculations. For example

real, parameter :: gravity=9.810! gravitational acceleration in m/s^

One reason you may want to use a named constant is that

  • Avoid mistakes by not having to type long numbers multiple times, e.g. like the constant π.
  • Inform the compiler that the address cannot be written to and to crash if such an attempt is made. Also some beneficial optimization can be performed.
  • If we need to change the value of the constant we need retype once only and minimizing the chances of introducing bugs.

18 CHAPTER 3. EXPRESSIONS AND ASSIGNMENT STATEMENTS

Hence if for some reasons the units of the code need to be changed the gravity declaration would become:

real, parameter :: gravity=32.2! gravitational acceleration in ft/s^

3.4 Arithmetic Operators

The example, aside from constants and variables, uses arithmetic operators like addition + and exponentiation **. Here is a complete list of numerical operators: Addition + Subtraction or negation - Multiplication * Division / Exponentiation ** The minus sign - can be a unary operator when it is used to indicate a negative quantity: only one input is required as in -3.1415. All others are binary operators and require two inputs to carry out the calculation. The quantities involved in a binary operation should be of the same type in general except that a whole number exponent should always be an integer. Here are some side effects that we need to watch for when coding:

  • Integer division. When one integer is divided by another the result is the integer part of the quotient, obtained by chopping off and throwing away the fractional part (not by rounding).
  • Real exponents are more costly to calculate then integer exponent. For ex- ample x2.0 is more expensive then x
  • Occasionally the compiler will “upgrade” the variable when it sees mixed mode operations. So 3+1.2 will be calculated as 3.0 + 1.2.
  • The order in which the operations are written makes a difference. The order of precedence will be visited soon.

3.5 Function References

In addition to constants, variables and operators, the program contains a function reference to sqrt, which returns the positive square root of its argument. Many mathematical functions are built into FORTRAN and programmers can build their own. The syntax of the function is meant to recall the standard mathematical

20 CHAPTER 3. EXPRESSIONS AND ASSIGNMENT STATEMENTS

3.8 Input/Output

The print statement here prints a real variable hyp. Several constants and vari- ables of different types can be printed with a single print statement. Usually it is a good idea to confirm the input so the code could have been printed as:

print *,’a= ’, a, ’ b=’,b

The unformatted input statement read serves to read input from the keyboard. Actually in linux it is taking input from standard input or stdin. It defaults to the keyboard unless the input is redirected from a file. So for example, the values of a and b can be obtained at run time and do not have to be “hardcoded” (so no recompiling is needed in case different values for a and b need to be put in). Here is the code:

program hypotenuse implicit none real :: a,b,hyp

read *, a,b print *,’a=’,a,’ b=’, b

hyp = sqrt(a2+b2)! calculation print *,hyp! output

stop end program hypotenuse

3.9 Summary

Fortran statement consists of operation acting on constants, variables, and func- tions. Syntax rules govern the relationship between the different fields within a statement. A number of issues have not been mentioned yet, including other FORTRAN data type, the different representation of integer and reals, and the attributes that can be assigned to variables.