Last Updated:

What is fortran programming language?

fortran programming language

Fortran Language Basics

Fortran is a general-purpose programming language designed for mathematical calculations, such as mechanical engineering. Fortran is an abbreviation for translating formulas, and it was originally capitalized as FORTRAN. However, following the current trend of using only a capital letter in abbreviations, everyone calls it Fortran.

Fortran was the first high-level programming language in history. Work on Fortran began in the 1950s at IBM, and there have been many versions since then. By convention, the Fortran version is designated by the last two digits of the year in which the standard was proposed. Thus, we have:

  • Fortnan 66
  • Fortnan77
  • Fortnan90 (95)

The most common version of Fortran today is still the Fortran 77, although the Fortran 90 is gaining more and more popularity. The Fortran 95 is a revised version of the Fortran 90. There are also several versions of Fortran designed for parallel computers. The most important of these is the high-performance Fortran (HPF), which is the de facto standard.

Users should be aware that most Fortran 77 compilers allow a superset of Fortran 77, that is, they allow non-standard extensions. In this tutorial, we'll highlight the ANSI Fortran 77 standard.

Why study Fortran?


Fortran is a popular programming language used in engineering applications. Therefore, it is important for graduates of engineering specialties to be able to read and change the Fortran code. From time to time, so-called experts predict that Fortran will quickly fade in popularity and soon disappear. These predictions have always failed. Fortran is the most durable programming language in history. About

One of the main reasons why Fortran has survived and will survive is software inertia. After a company has spent many man-years and possibly millions of dollars on a software product, it is unlikely to try to translate the software into another language. Reliable software translation is a very difficult task.

The main advantage of Fortran is that it is standardized by ANSI and ISO (see footnotes). Therefore, if your program is written in ANSI Fortran 77 without using anything outside the standard, it will run on any computer that has a Fortran 77 compiler. Thus, Fortran programs are portable to different machine platforms. (If you'd like to see some of the documents on Fortran standards, click here.)

Fortran Basics 77

Fortran is simply a sequence of lines of text. The text must follow a specific structure to be a valid Fortran program. Let's start with a simple example:

program circle
real r, area
with This program reads the real number r
with prints the circumference area with radius r.

write (*,*) ‘Give radius r:’
read (*,*) r
area = 3.14159*r*r
write (*,*) ‘Area = ‘, area


Lines beginning with the letter "c" are comments and have no other purpose than to make the program more readable for people. Initially, all programs on Fortran had to be written in capital letters. Most people now write in lowercase letters, as it's more legible, and so do we. You can mix case, but Fortran is not case sensitive, so "X" and "x" are the same variable.

Organization of the program


A Fortran program usually consists of a main program (or driver) and possibly several subroutines (procedures or subroutines). For now, we'll put all the approvals in the main program; subprogrammes will be reviewed later. The structure of the main programme is as follows:

  • program name
  • Declaration
  • Statements
  • stop
  • The end

In this textbook, words in italics should not be taken as literal text, but rather as a description of what is in their place.

The stop statement is optional and may seem redundant because the program will still stop when it reaches the end, but it is recommended that you always end the program with a stop statement to emphasize that the execution thread stops there. Note that you cannot have a variable with the same name as the program.

Column layout rules

Fortran 77 is not a free-format language, but has a very strict set of source code formatting rules. The most important rules are the rules for arranging columns:

  • Column 1 : Empty, or the letter "c" or » * » for comments
  • Column 1-5 : Label Statement (Optional)
  • Column 6 : Continuation of the previous line (optional)
  • Column 7-72 : Statements
  • Column 73-80: Serial number (optional, rarely used today)

Most rows in Fortran 77 start with 6 spaces and end before column 72, which means that only the operator field is used.


A string that begins with a "c" or an asterisk in the first column is a comment. Comments can appear anywhere in the program. Well-written comments are crucial to the readability of the program. Commercial Fortran codes often contain about 50% of the comments.

You may also encounter Fortran programs that use an exclamation point (!) for comments. This is not the standard part of Fortran 77, but is supported by several Fortran 77 compilers and is explicitly allowed in Fortran 90. When understood, the exclamation point can appear anywhere in the string (except for positions 2-6).


Sometimes an operator does not fit into the 66 available columns of a single row. You can then split the statement into two or more lines and use the continuation label at 6. Example:

c23456789 (This shows the position of the column!)

c The following statement follows two physical lines
area = 3.14159265358979
+ * r * r

Any character can be used instead of the plus sign as a continuation symbol. A good programming style is to use a plus sign, an ampersand, or numbers (2 for the second line, 3 for the third, and so on).

Source code, object code, compilation, and linking

The Fortran program consists of simple text that follows certain rules (syntax). This is called source code. You need to use the editor to write (edit) the source code. The most common editors on Unix are emacs and vi, but they can be a bit complicated for novice users. You might want to use a simpler editor, such as xedit, that runs on X-windows.

When you have written a Fortran program, you should save it in a file with an .f or .for extension. Before you can execute a program, you must convert it into a machine-readable form. This is done using a special program called a compiler. Fortran 77 compilers are commonly referred to as f77.

Exiting the default compilation has a somewhat cryptic name a.out, but you can choose a different name if you want. To run the program, simply enter the name of the executable file, such as a.out. (This explanation is somewhat simplified. In fact, the compiler translates the source code into object code, and the linker/loader turns it into an executable.)


In the class directory, there is a small Fortran program called circle.f. You can compile and run it by following these steps:

cp /usr/class/me390/circle*.f .
f77 circle.f

(Note that there are a few dots out there that are easy to miss!) If you need to have multiple executable files at the same time, it's a good idea to give them descriptive names. This can be done using the -o option.

For example, f77 circle.f -o circle.out will compile the circle.f file and save the executable file in the circle.out file. Note that object code and executable files take up a lot of disk space, so you should delete them when you're not using them. (The remove command in Unix is rm.)

In the previous examples, we did not distinguish between compilation and binding. These are two different processes, but the Fortran compiler executes both, so the user usually doesn't need to know about it. But in the following example, we'll use two source code files.

f77 circle.f -o circle.out

This will create three files, two object code files, circle1.o and circle2.o, and an a.out executable. What really happened here is that the Fortran compiler first compiled each of the source code files into object files (ending in .o) and then linked the two object files together into an a.out executable. You can separate these two steps by using the -c option to tell the compiler to compile only the source files:

f77 -c circle1.f circle2.f
f77 circle.f -o circle.out

Compiling individual files like this can be useful if there are many files and only some of them need to be recompiled. Unix has a useful make command that is commonly used to handle large software packages with a large number of source files. These packages come with a makefile, and all the user has to do is enter make. Writing makefiles is a bit complicated, so we won't discuss it in this tutorial.

Variables, Types, and Declarations

Variable names

Variable names in Fortran must be 1-6 characters (valid letters a-z and numbers 0-9). In addition, the first character must be a letter. Fortran 77 does not distinguish between upper and lower case, in fact, it assumes that all inputs are uppercase. However, almost all Fortran 77 compilers accept lowercase. If you ever come across a Fortran 77 compiler that insists on uppercase, it's usually easy to convert source code to all uppercase cases.

The words that make up the Fortran language are called reserved words and cannot be used as variable names. Some of the reserved words we've seen so far are "program," "real," "stop," and "end."

Types and declarations

Each variable must be defined in the declaration. This sets the type of the variable. The most common declarations are:

  • integer list of variables(integer)
  • real list of variables(real)
  • double-precision variable list (doubleprecision)
  • complex variable list (complex)
  • logical list of variables
  • variable symbol list (character)

The list of variables should consist of variable names separated by commas. Each variable must be declared exactly once. If the variable is not declared, Fortran 77 uses a set of implicit rules to establish the type. This means that all variables starting with the letters i-n are integers, and all others are real numbers.

Many older Fortran 77 programs use these implicit rules, but you shouldn't! The probability of errors in your program increases dramatically if you do not consistently declare your variables.

Integers and floating-point variables

Fortran 77 has only one type for integer variables. Integers are usually stored as 32-bit (4 bytes) variables. Therefore, all integer variables must accept values in the range [-m, m], where m is approximately equal to 2*10^9.

Fortran 77 has two different types of floating-point variables called real and double precision. Although the real is often adequate, some numerical calculations require very high accuracy, and double precision should be used.

Usually, real is a 4-byte variable, and double precision is 8 bytes, but this depends on the machine. Some non-standard versions of Fortran use the syntax real*8 to denote 8-byte floating-point variables.

Parameter Operator

Some constants appear many times in the program. Therefore, it is often advisable to identify them only once, at the beginning of the program. That's what the parameter operator is for. It also makes programs more readable. For example, the circlearea program should have been written something like this:

program circle
real r, area, pi
parameter (pi = 3.14159)
c This program reads the actual number r and prints
c the circumference of the circle with radius r.

write (*,*) ‘Give radius r:’
read (*,*) r
area = pi*r*r
write (*,*) ‘Area = ‘, area


The syntax of the parameter operator is as follows

parameter (name = constant, ... , name = constant)

The rules for the parameter operator are as follows:

  • The name defined in the parameter statement is not a variable, but a constant. (You cannot change its value at a later stage of the program.)
  • The name can appear in no more than one parameter statement.
  • Parameter operator(s) must precede the first executable statement.

Here are some good reasons to use the parameter operator:

  • This helps reduce typos.
  • This makes it easier to change a constant that appears many times in the program.
  • This increases the readability of your program.

Expressions and assignment


The simplest form of expression is a constant. There are 6 types of constants corresponding to 6 data types. Here are some integer constants:


Then we have real constants:

3,333 E-1

The notation E means that you must multiply the constant by 10 raised to the power following the letter "E". Hence, 2.0E6 is two million and 3.333 E-1 is about one-third.

For constants that are greater than the highest allowable real value or require high precision, double precision should be used. The designation is the same as for real constants, except that "E" is replaced by "D". Examples:

2.0 D-1

Here, 2.0 D-1 is double the accuracy of one-fifth, while 1D99 is one followed by 99 zeros. The next type is complex constants. This is indicated by a pair of constants (integer or real) separated by a comma and enclosed in parentheses. Examples include:

(2, -3)
(1., 9.9 E-1)

The first number denotes the actual part, and the second is the imaginary part. The fifth type is logical constants. They can have only one of two values:


Note that the dots enclosing the letters are required. The last type is character constants. They are most commonly used as an array of characters called a string. They consist of an arbitrary sequence of characters enclosed in apostrophes (single quotation marks):

-Everything is coming!
"Today is a good day.

Strings and character constants are case-sensitive. The problem arises if you want to have an apostrophe in the string itself. In this case, you should double the apostrophe:

"Today is a good day.


The simplest non-constant expressions are operandoperatoroperand and an example:

x + y

The result of the expression is itself an operand, so we can nest the expressions together, for example:

x + 2 * y

This raises the question of priority: does the last expression mean x + (2*y) or (x+2)*y? Priority of arithmetic operators in Fortran 77 (from highest to lowest):

  • ** {exponentiation}
  • *,/ {multiplication, division}
  • +,- {addition, subtraction}

All of these operators are evaluated from left to right, with the exception of the exponentiation operator **, which has a right-to-left priority. If you want to change the default rating order, you can use parentheses.

All of the above operators are binary operators.there is also an unary operator - for negation, which takes precedence over others. Therefore, an expression of type-x+y means what you expect.

Extreme caution must be exercised when using the division operator, which has a completely different meaning for integers and real numbers. If both operands are integers, integer division is performed, otherwise valid arithmetic division is performed. For example, 3/2 equals 1 and 3./2. equal to 1.5 (note the decimal points).


The task is as follows:

variable_name = expression

The interpretation is as follows: Calculate the right side and assign the resulting value to the variable on the left. The expression on the right may contain other variables, but they never change values! For example, the area = pi * r**2 does not change the values of pi or r, only the area.

Type Conversion

When different data types occur in the same expression, type conversion must occur explicitly or implicitly. Fortran will perform some type conversion implicitly. For example

x = x + 1

converts an integer one to a valid number one and has the desired effect of increasing x by one. However, in more complex expressions, a good programming practice is to explicitly force the conversion of the required types. The following functions are available for numbers:

int real


The first three make obvious sense. ichar takes a symbol and converts it to an integer, while char does the exact opposite.

Example: How to multiply two real variables x and y using double precision and store the result in a double-precision variable w:

w = dble(x)*dble(y)

Note that this is different from

w = dble(x*y)

Boolean expressions

Boolean expressions can only have the value . TRUE. or. FALSE.. A Boolean expression can be formed by comparing arithmetic expressions using the following relational operators:

.. LT. stands for <. LE. <=». GT.» >
. GE.>=
. EQ. =
.NE. /=

Therefore, you cannot use characters such as Boolean expressions, which can be combined by logical .I. or .NE. operators that have an obvious meaning.

Boolean variables and assignment

True values can be stored in Boolean variables. The task is similar to the arithmetic task. Example:

logical a, b
a = . TRUE.
b = a . AND. 3 .LT. 5/2

Priority order is important, as the last example shows. The rule is that arithmetic expressions are evaluated first, then relational operators, and finally logical operators. Therefore, b will be assigned . FALSE. in the example above. Among logical operators, the priority (in the absence of parentheses) is that . NOT. is performed first, then . AND., then .OR. is done last.

Boolean variables are rarely used in Fortran. But Boolean expressions are often used in conditional statements, such as the if statement.

If Statements

An important part of any programming language is conditional operators. The most common such statement in Fortran is the if statement, which actually has several forms. The simplest of these is the logical statement if:

if (Boolean expression) executable statement

This should be written in one line. In this example, the absolute value of x is found:

if (x .LT. 0) x = -x

If more than one statement must be executed inside if, the following syntax should be used:

if (Boolean expression) then operators

and if

The most general form of the if statement is as follows:

if (Boolean expression) then operators

elseif (Boolean expression)
, then operators

The execution thread goes from top to bottom. Conditional expressions are evaluated sequentially until one of them is true. The corresponding statements are then executed and the control resumes after the end if.

Nested if statements

if statements can be nested in multiple levels. To ensure readability, it is important to use proper indentation. Here's an example:

if (x . GT. 0), then
if (x . GE. y), then
write(*,*) ‘x is positive and x >= y’
write(*,*) ‘x ispositivebut x

You should avoid nesting many layers of if statements, as they become difficult to follow.


Loops are used to do these things again. If you're familiar with other programming languages, you've probably heard of for-loops, while-loops, and until-loops. Fortran 77 has only one cycle construct, called a do-loop. The do loop corresponds to what in other languages is called a for loop. Other loop constructs must be constructed using the if and goto operators.

Do loop

A do-loop is used for simple counting. Here is a simple example that derives cumulative sums of integers from 1 to n (suppose n has been assigned a value elsewhere):

integer i, n, sum

integer i, n, sum

sum = 0
do 10 i = 1, n
sum = sum + i
write(*,*) ‘i =’, i
write(*,*) ‘sum =’, sum
10 continue

The number 10 is the operator's label. Typically, one program will have many loops and other operators that require an operator label. The programmer is responsible for assigning a unique number to each label in each program (or subroutine).

Recall that column positions 1-5 are reserved for operator labels. The numeric value of operator labels does not matter, so you can use any integer in any order. As a rule, most programmers use consecutive multiples of 10.

The variable defined in the do statement is incremented by 1 by default. However, you can define a step as any number other than zero. This segment of the program prints even numbers from 1 to 10 in descending order:

integer i

do 20 i = 10, 1, -2
write(*,*) ‘i =’, i
20 continue

The general form of the do loop is as follows:

do label var = expr1, expr2, expr3

var is a loop variable (often called a loop index) that must be an integer. expr1 specifies the initial value of var, expr2 specifies the final boundary, and expr3 specifies the increment (step).

Note: The do-loop variable should never be changed by other statements within the loop! This will cause a lot of confusion.

A loop index can be of type real, but due to rounding errors, it may not accept the exact sequence of values that you expect.

Many Fortran 77 compilers allow you to close do loops using the enddo operator. The advantage of this is that the operator label can be omitted because it is assumed that the enddo closes the nearest previous do statement. The enddo design is widely used, but it is not part of the ANSI Fortran 77.

It should be noted that unlike some programming languages, Fortran evaluates the start, end, and step expressions only once, before the first loop body passes. This means that the next do-loop will multiply non-negative j by two (the hard way), rather than running forever like an equivalent loop in another language.


read (*,*) j
do 20 i = 1, j
j = j + 1
20 continue
write (*,*) j

while loops

The most intuitive way to write a while loop is:

while (logical expr) do
or alternatively,

dowhile (Boolean expression)
and do

The program will alternate between testing the condition and executing statements in the body as long as the condition in the while statement is true. Although this syntax is accepted by many compilers, it is not ANSI Fortran 77. The correct way to use if and goto is:

label if (logical expr) then
the statement

Here is an example that calculates and prints all the powers of two that are less than or equal to 100:


n = 1
10 if (n .le. 100), then
write (*,*) n
n = 2*n
goto 10
end if

Cycle until


If the completion criterion is at the end rather than at the beginning, it is often referred to as the cycle before. The pseudocode looks like this:


Again, this should be implemented in Fortran 77 using if and goto:

label continue
if (logicalexpr) gotolabel

Note that the Boolean expression in the latest version must be a negation of the expression given in the pseudocode!



Many scientific calculations use vectors and matrices. The data type used by Fortran to represent such objects is an array. A one-dimensional array corresponds to a vector and a two-dimensional array corresponds to a matrix. To fully understand how this works in Fortran 77, you need to know not only the syntax of usage, but also how these objects are stored in memory in Fortran 77.

One-dimensional arrays


The simplest array is a one-dimensional array, which is simply a sequence of elements stored sequentially in memory. For example, the declaration reala(20) declares a as a real array of length 20. That is, a consists of 20 real numbers continuously stored in memory.

By convention, Fortran arrays are indexed from 1 and above. Thus, the first number in the array is denoted by a(1) and the last-a(20). However, you can define an arbitrary range of indexes for your arrays using the following syntax:

realb(0:19), weird(-162:237)

Here, b is exactly similar to a from the previous example, except that the index runs from 0 to 19. weird is an array of length 237-(-162)+1 = 400. The type of an array element can be any of the basic data types. Examples:


Each element of an array can be thought of as a separate variable. You refer to the i-th element of array a through a(i). Here is a code segment that stores the first 10 square numbers in an array sq:

integeri, sq(10)

do 100 i = 1, 10
sq(i) = i**2
100 continue

A common mistake in Fortran is that a program tries to access array elements that are outside the boundaries or undefined. This is the responsibility of the programmer, and the Fortran compiler will not detect such errors!

Two-dimensional arrays

Matrices are very important in linear algebra. Matrices are usually represented by two-dimensional arrays. For example, the declaration Real A(3,5) defines a two-dimensional array of 3*5=15 real numbers. It's helpful to think of the first index as a row index and the second as a column index. From here we get a graphical picture:

(1,1) (1,2) (1,3) (1,4) (1,5)
(2,1) (2,2) (2,3) (2,4) (2,5)
(3,1) (3,2) (3,3) (3,4) (3,5)

Two-dimensional arrays can also have indexes in an arbitrary specific range. The general syntax of the declarations is as follows:

name (low_index1 : hi_index1, low_index2 : hi_index2)
Then the total size of the array will be equal to
size = (hi_index1-low_index1+1)*(hi_index2-low_index2+1)

In Fortran, it is quite common to declare arrays that are larger than the matrix we want to store. (This is because Fortran does not have dynamic memory allocation.) It's perfectly legal.


Real A(3.5)
Integer i,j
c We will only use the top of this 3 by 3 array.
do 20 j = 1, 3
do 10 i = 1, 3
a(i,j) = real(i)/real(j)
10 continue
20 continue

The elements of sub-matrix A(1:3,4:5) are not defined. Do not assume that these elements are initialized by the compiler to zero (some compilers will do this, but not all).

Storage format for 2D arrays


Fortran stores multidimensional arrays as a continuous sequence of elements. It is important to know that 2-dimensional arrays are stored in columns. Thus, in the example above, the array element (1,2) will follow the element (3,1). This is followed by the rest of the second column, then the third column, and so on.

Let's consider again an example where we use only the upper submatrix 3 by 3 arrays 3 by 5 A (3.5). 9 interesting elements will then be stored in the first nine memory cells, while the last six are not used. This works neatly because the master dimension is the same for both the array and the matrix we store in the array.

However, often the lead dimension of the array will be larger than the first dimension of the matrix. Then the matrix will not be stored continuously in memory, even if the array is continuous. For example, suppose the ad was A(5,3) instead. Then there will be two "unused" memory cells between the end of one column and the beginning of the next (again, we assume that the matrix is 3 by 3).

This may sound complicated, but it's actually pretty simple once you get used to it. If in doubt, it can be useful to look at how the address of an array element is calculated. Each array will have some memory address assigned to the beginning of the array, that is, element (1,1). The address of the element (i,j) is then set to addr[A(i,j)] = addr[A(1,1)] + (j-1)*lda + (i-1) where lda is the leading (i.e., string) dimension A. Note that lda is generally different from the actual matrix dimension. Many of Fortran's mistakes are caused by this, so it's very important that you understand the difference!

Multidimensional Arrays

Fortran 77 allows arrays of up to seven dimensions. The syntax and format of the storage are similar to a two-dimensional case, so we won't waste time on it.

There is an alternative way to declare arrays in Fortran 77.

realA, x
dimensionA(10,20) equivalent

Real Sociedad(10,20), X(50)

This statement of measurement is considered an old-fashioned style today.


In this article, you have learned the basics of the Fortnan language! All novice programmers good luck in writing to