Category Archives: Fortran lessons

Fortran: Lesson 2

Lesson topics

View Demos
# 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10
Download Demos
# 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10

We look at more of the commonly used features and commands of Fortran.

Logical Expressions

A logical expression is a relation between variables or expressions that can have a value of TRUE or FALSE. Such expressions are used in "if Ö then" constructions and in loops, when testing whether to execute certain steps of a program. Relations and connectives appearing in logical expressions are listed in the following table; you will see how some of these are used in later examples.

Relation/Connective   Meaning
.lt. less than
.gt. greater than
.le. less than or equal to
.ge. greater than or equal to
.eq. equals
.ne. not equal to
.and. and
.or. or
.not. not
.xor. "exclusive" or (i.e., only one is true)
.eqv. equivalent (i.e., same truth values)
.neqv. not equivalent

If ... Then ... Else Constructions

"If … Then … Else" constructions in Fortran are pretty much like those in Basic, with but a few minor modifications. First, instead of using in the tests symbols like "=", "<", ">=", etc., as in Basic, you must use the abbreviations in the preceding table. Also, tests must be enclosed in parentheses, and "else if" may be two words. Here are several examples:

  1. if (x .gt. 0) print *, "x is positive"
  2. if (x .ge. y .and. x .ge. z) go to 40
  3. 											if (x .ge. 0) then
    												y = sqrt(x)
    												print *, y, " squared = ", x
    											end if
  4. 											if (x .ge. 0) then
    												y = sqrt(x)
    												print *, y, " squared = ", x
    												print *, "x has no square root"
    											end if
  5. 											if (x .ge. 0) then
    												print *, "x is positive"
    												y = sqrt(x)
    											else if (x .lt. 0) then
    												print *, "x is negative"
    												go to 60
    											else if (x .eq. 0) then
    												print *, "x is zero"
    												y = 0
    											end if

Observe that, as in examples 1) and 2), the one-line "if" statement does not use "then". Moreover, "else" appears on a line by itself, while "else if" shares the line with the test condition and "then".


A stop statement stops the execution of a program. For instance, the sequence of statements below terminates the program whenever n is less than zero:

									if (n .lt. 0) then
										print *, "Error - your age cannot be negative!"
									end if

Do not confuse stop and end. Use end only as the very last statement in the program, and use stop only to terminate the program before this last statement. Violating these rules will fatally confuse the compiler - it regards an end statement as the program's physical end.

Labels and Go To

Labels and the "go to" statement work as in Basic, except that a label must be a number, and it must be typed in columns 2-5. Here is an example of a go to command directing the action to a labeled statement:

									if (x .lt. 0) go to 10
									print *, "The square root of x is ", sqrt(x)
								10	print *, "x is negative and has no square root"

Character Variables

A character variable is analogous to a string variable in Basic. A character variable must be declared at the beginning of the program, and attached to it in the declaration must be a number following an asterisk "*"; this number indicates the maximum number of symbols in the string. For example, the declaration statement
character name*20, ans*1

indicates that "name" is a character variable holding no more than 20 symbols, while "ans" is a character variable holding only one symbol.

A string in Fortran may be enclosed in either double quotes, as in "hello", or in single quotes, as in 'goodbye'.

Do Loops

"For … Next" loops in Basic become "Do Loops" in Fortran. Such a loop begins with a do statement, and ends with either end do, or a labeled continue statement. Here are two loops that add the squares of the integers from 1 to 10:

										sum = 0
										do i = 1, 10
											sum = sum + i ** 2
										end do
										print *, "The sum is", sum
									sum = 0
									do 5 i = 1, 10
									sum = sum + i ** 2
								5	continue
									print *, "The sum is", sum

The end do and continue statements serve only to identify the end of the loop. The limits of the loop may be variables as well as numbers (e.g.: do i = m, n). As in Basic you may indicate a step size, which can be positive or negative. For example, the statement

do i = 1, 9, 2
specifies that the loop variable i run over the odd numbers 1, 3, 5, 7, 9.
Loops can be nested, and nested loops can end on the same continue statement (but not on the same end do statement). Here are two instances of nested loops assigning the entries of a 10 x 10 matrix:
										do i = 1, 10
											do j = 1, 10
												a(i,j) = i + j
											end do
										end do
									do 5 i = 1, 10
									do 5 j = 1, 10
									a(i,j) = i + j
								5	continue

Fortran: Lesson 1

Lesson topics

View Demos
# 1
Download Demos
# 1


Fortran is one of the oldest programming languages devised, but it is also still one of the most popular, especially among engineers and applied scientists. It was developed in the 1950's at IBM. Part of the reason for Fortran's durability is that it is particularly well-suited for mathematical programming; moreover, there are millions of useful programs written in Fortran, created at considerable time and expense, and understandably people are reluctant to trash these old programs and switch to a new programming language.

The name Fortran originally referred to "Formula Translation", but it has long since taken on its own meaning. There are several versions of Fortran around, among them Fortran 77, Fortran 90, and Fortran 95. (The number denotes the year of introduction.) Fortran 77 is probably still the most used, and it is the version installed on UHUNIX and in the UH math lab. Even though this semester we have thus far studied Basic, at the same time we have studied Fortran, because commands and procedures are very similar in the two languages. Moving from QuickBasic to Fortran is more a matter of change of terminology than anything else.

Editing Fortran

Unlike in Basic, a Fortran program is not typed in a "Fortran window". Instead, a program is typed and saved with an editor (i.e., a word processor), and the program is then turned into an executable file by a Fortran compiler. To begin the process of creating a Fortran program in the math lab, you must open an editor. It is preferable to use a simple editor - such as Notepad or the DOS editor - because fancy word processors might add extraneous formatting notation that will hang up Fortran.

A most peculiar feature of Fortran 77 is its line structure, which is a carryover from the old days when programs were typed on punch cards. A punch card had 80 columns, and so does a line of Fortran code. A "c" in column 1 indicates a comment (similar to REM in Basic). Columns 2-5 (usually left blank) are reserved for line numbers. Column 6 is used only to indicate a continuation of a line too long to fit on the card. Columns 7-72 contain the instructions of the program. Columns 73-80 were originally used for numbering the punch cards, but are rarely used nowadays - leave them blank and the compiler will ignore them.

Fortran is case insensitive - that is, it does not distinguish between capital and small letters. Thus x and X refer to the same variable. Many programmers for simplicity use all small letters, but you may do as you like. Also, after column six Fortran does not recognize spaces (except for spaces inside quotations as in print statements). In general, spaces are mostly for the purpose of making code more readable by humans. When you type a Fortran program with an editor, make certain the editor indents more than six spaces; then if you begin every line with an indent you do not have to worry about counting six spaces at the beginnings of lines.

Let us go through the steps of editing, compiling, and running a short program. First open Notepad under Windows, or type "edit" (and return) under a DOS prompt to open the DOS editor. (When you double-click the Fortran icon on a math lab computer, you get a DOS prompt.) Beginning each line with an indent (except for the fourth line, where the "c" must be placed in the first column), type the program exhibited below; the program computes the area of a circle of radius r, as input by the user. The resulting file that you save is called the source file for the program.

									program circlearea
									real r, area, pi
									parameter (pi = 3.14159)
								c	This program computes the area of a circle.
									print *, "What is the radius?"
									read *, r
									area = pi * r ** 2
									print *, "The area is", area
									print *, "Bye!"

The first statement above gives the program name, the second declares that "r", "area", and "pi" will be single precision real quantities, and the third announces that pi has the value 3.14159. The fourth statement, beginning with "c" in column 1, is a comment describing what the program does; such comments are for the benefit of the programmer and are ignored by Fortran. The fifth statement prompts the user for the radius of the circle, and the sixth accepts this input. The seventh statement computes the area and the eighth informs the user of this area. Finally, the last two statements bid goodbye and terminate the program.

The name for a source file in Fortran must end with the extension ".f" before the compiler recognizes it. After you have typed the above program, save the file as area.f. (If you type the file in Notepad, include the whole name in quotes when you save it, as otherwise the extension .txt will be added to the name.) The file will be saved to your h directory in the math lab. Under a DOS prompt you can view the files in this directory by typing dir and enter; under Windows you can double-click "My Computer" and then the icon for the h drive.


After you have created and saved a source file, you next must compile this file. Open a Fortran window and enter

g77 name.f

where in place of name you insert the name of your source file. (If the source file resides in a directory different from that of the Fortran program, you will have to include also the directory path of the file.) To compile the file of our example above, in the math computer lab you just enter g77 area.f.

If your program has mistakes (which usually happens on the first attempt at compiling), instead of a compiled file you will get Fortran error messages pointing out problems. Some of these messages can be hard to decipher, but after reading hundreds of them you will get better at it. If your program has no mistakes Fortran will simply return a DOS prompt - that is good news because it means Fortran has successfully created a compiled file. By default this new file is given the name a.exe. (You can give the compiled file a name of your own choosing by typing g77 area.f -o name.exe to compile the program - but usually there is no reason not to accept the default name.) Your compiled file, also located in the h directory, is now executable - that means the program is ready to run.

Running a Program

If your compiled file has the default name a.exe, you simply type a and return to run it (or name and return if you gave the file another name). After you run the program and see how it works, you can return to your editor and revise it as you wish. It is perhaps better to keep two windows open - both the Fortran window and the editing window - so that you can quickly switch from one to the other with a mouse-click. After revising a program, you must save and compile it again before changes take effect.

If you do enough Fortran programming, sooner or later you will err and create and run a program that never stops. In such a situation, type "Control-C" to interrupt the execution of the program.

Now that we have discussed the basic nuts and bolts of creating and running a Fortran program, we discuss some terminology and commands. You will probably find that most of these remind you of similar things in Basic.


Every Fortran program must begin with a program line, giving the name of the program. Here are examples:

									program quadratic
									program mortgage
									program primes

Variables, Declarations, Types

After the program name come the declaration statements, stating the types of the variables used in the program. A variable name consists of characters chosen from the letters a-z and the digits 0-9; the first character of the name must be a letter. You are not allowed to use your program name as a variable, nor are you allowed to use words reserved for the Fortran language, such as "program", "real", "end", etc.
The variable types in Fortran are
1)  integer (in the range from about - 2 billion to + 2 billion)
2)  real (single precision real variable)
3)  double precision (double precision real variable)
4)  character (string variable)
5)  complex (complex variable)
6)  logical (logical variable)
As illustration, the declaration statements
										real r, area
										integer M, N
										double precision a, b

declare that r and area are single precision real variables, that M and N are integers, and that a and b are double precision real variables.

If you do not declare the type of a variable, Fortran will by default make it an integer if it starts with one of the letters i through n, and will make it a single precision real variable otherwise. However, it is normal (and good) programming practice to declare the type of every variable, as otherwise mistakes are easily made.

The implicit quantifier before a type declaration makes all variables starting with the listed letters of the specified type. For example, the declarations

									implicit integer (i-m)
								    implicit real (r-t)

make variables starting with i, j, k, l, m integers, and those starting with r, s, t real. However, the implicit quantifier is probably best avoided, as programmers with short memories will make mistakes.

A declaration statement is nonexecutable - that is, it provides information but does not instruct Fortran to carry out any action. Declarations must appear before any executable statement (a statement that does tell Fortran to take some action).


The equals sign "=" assigns the variable on the left side the value of the number or expression on the right side (exactly as in Basic).


The parameter statement works like CONST in Basic - it specifies a value for a constant. The syntax is
parameter (name = constant expression)

where name is replaced by the name of the constant, and constant expression by an expression involving only constants. Thus
parameter (pi = 3.14159)

specifies a value for the constant pi, while the succeeding statement
									parameter (pi = 3.14159)
									parameter (a = 2* pi, b = pi/2)

fixes values of new constants a and b in terms of the old constant pi. Remember that once a constant is defined you are not allowed to change its value later.

All parameter statements must appear before the first executable statement.


A comment is similar to an REM statement in Basic. You can indicate a comment by placing a "c" in column 1 and then the comment in columns 7-72. Alternatively, you can use an exclamation point "!" to indicate a comment; it may occur anywhere in the line (except columns 2-6). Everything on a line after an exclamation point becomes a comment.

Print *

The command "print *" is analogous to PRINT in Basic; it instructs Fortran to print items to the screen. Examples are

									print *, x
									print *, "The solution is ", x
									print *, 'The radius is', r, 'and the area is', area

Note that a comma follows "print *", and that commas (instead of semicolons as in Basic) appear between successive items to be printed. Observe also that either double or single quotes may enclose strings. The command "print *" on a line by itself (without a comma) serves as a line feed.

Read *

The command "read *" is analogous to INPUT in Basic. Examples are

								read *, radius
								read *, A, B, C

In the first example the program pauses to allow the user to enter the radius. In the second example the user types the values of A, B, and C, separated by returns; alternatively, the user can type A, B, and C separated only by commas, and then one final return.


The end statement marks the end of the main Fortran program or of a subprogram. (It cannot be used in the middle of the program, as in Basic.)

Operations of Arithmetic

Here are the common arithmetical operations in Fortran:

Additionx + y
Subtractionx - y
Multiplicationx * y
Divisionx / y
Exponentiationx ** y

Fortran performs exponentiations first, then multiplications and divisions, and lastly additions and subtractions. (When in doubt, use parentheses!)

Be careful with division. If m and n are integers, then m/n is truncated to its integer part. Thus 3/4 is evaluated as 0, and 25/6 as 4. When working with constants rather than variables you can avoid this problem by using periods after integers. For example 3./4. is evaluated in the standard way as .75, as Fortran treats 3. and 4. as real variables rather than as integers.

Intrinsic Functions

Many standard mathematical functions are built into Fortran - these are called intrinsic functions. Below is a table of some of the functions most commonly used in mathematical programming. All trig functions work in radians. (Note that arguments of functions must be enclosed in parentheses.)

								c	absolute value of x

								c	arccosine of x

								c	arcsine of x

								c	arctangent of x

								c	cosine of x

								c	hyperbolic cosine of x

								c	converts x to double precision type

								c	exponential function of x (base e)

								c	natural logarithm of x (base e)

								c	remainder when n is divided by m

								c	converts x to real (single precision) type

								c	changes the sign of x to that of y

								c	sine of x

								c	hyperbolic sine of x

								c	square root of x

								c	tangent of x

								c	hyperbolic tangent of x