0% found this document useful (0 votes)
55 views35 pages

Fortran Lecture 5

The document discusses what a computer program is and provides details about the Fortran programming language. It defines a computer program as a set of instructions for the computer to execute sequentially. It then provides information on Fortran program structure, data types, variables, declaration statements, and variable attributes.

Uploaded by

Manozer Mensah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views35 pages

Fortran Lecture 5

The document discusses what a computer program is and provides details about the Fortran programming language. It defines a computer program as a set of instructions for the computer to execute sequentially. It then provides information on Fortran program structure, data types, variables, declaration statements, and variable attributes.

Uploaded by

Manozer Mensah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

What is computer program?

A computer program is a set of instructions for the computer to execute


sequentially. The particular set of rules for coding the instructions to a
computer is called a programming language.
Steps involve -
Initially the program source code is written in plain text by the
programmer using text editor (eg emacs, gedit, kwrite, etc) and
then saved. Fortran 90 files typically have extension (.f90).
This file is then compiled (by existing application, called the
compiler) to translate the plain text of the source code to binary
code for the processor. The executable files have extension (.exe).
The binary executable file is then run to get the output/results in
plain text.
Fortran Background

Fortran (FORmula TRANslator) was the first high-level programming


language proposed in 1953 by John Backus and the first program was run
in April 1957. Fortran is use mainly within the scientific community for
solving problems that has a significant arithmetic content.

Versions/Standards
Fortran 66 - first standard
Fortran 77 - character handling
Fortran 90 - array and modular programming
Fortran 95 - functional programming
Fortran 2003 - object-oriented and generic programming
Fortran 2008 - concurrent programming.
Fortran 2015 - is under development
Fortran Program Structure without subprograms

Everything in square brackets [ ] is


optional. However, it is good
[PROGRAM name ] programming practice to put the
name of the program in both header
[IMPLICIT NONE] and END statements.

[Declaration statements]
name (program name) must:
[Execution statements]
Begin with a letter
END [ PROGRAM name] (upper/lower case)
It contains letters, digits 0-9,
and underscore characters
Maximum of 31 characters.
names are case-insensitive.
Fortran Program Structure with internal subprograms

[PROGRAM name ] The subprogram can be a function,


subroutine and module.
[IMPLICIT NONE] The structure of a subprogram is
similar to that of the main program
[Declaration statements]
but with some keywords.
[Execution statements]

[CONTAINS] The subprogram(s)/procedures


appear in the program after the
[Subprogram-part] keyword contains.
Contains marks the end of the main
END [ PROGRAM name]
code of the program and indicates
the start of the definition of the
subprogram(s)
Fortran Program Structure with external subprograms

Subprogram(s)/procedures can
[PROGRAM name ] appears after the end of the main
program.
[IMPLICIT NONE]
Subprograms that are not contained
[Declaration statements] in the main program are called
external subprograms/procedures.
[Execution statements]

END [ PROGRAM name] External procedures/subprograms


can be in the same file as the main
[Subprogram-part] program or in a different file.
If in different file, they are compiled
independently of other procedures
and program units.
Features of Fortran Program 1/14

IMPLICIT NONE

This is very important non-executable fortran statement used to


disable the default typing provisions of Fortran.

When this statement is used in the program, any variable that does
not appear in an explicit type declaration statement is considered
error.

If omitted, fortran uses implicit declaration where a variable is


considered INTEGER if the first letter of its names lies in the range
of I - N and will be declared as a REAL variable otherwise.

IMPLICIT NONE should appear after the Program name


statement and before any type declaration statement.

IMPLICIT NONE will be use in this course to write safe programs.


Features of Fortran Program 3/14

Fortran Data type

A Fortran 90 data type may be an INTEGER, REAL, LOGICAL,


COMPLEX, and CHARACTER or STRING

An integer data type is a string of digits with an optional sign: 12,


-20, 0, +2333

A real data type has two forms decimal and exponential

The decimal form consist of string of digits with exactly one decimal
point. e.g 1.4, -13.5, +0.04, 33333.5

In the exponential form, start with an integer/real. followed by a


E/e, followed by an integer (i.e., the exponent). e.g 15E3 (15x103 ),
equivalent to 15e3 (15x103 )
Features of Fortran Program 4/14

Fortran Data type cont.

A logical data type is either .TRUE. or .FALSE.


Note that the periods (dots) surrounding TRUE and FALSE are
required!

A complex data type consists of two numeric constants separated


by comma and enclosed in parentheses. e.g (1.,0.) equivalent to 1
+ 0i and (0.7071,0.7071) equivalent to 0.7071 + 0.7071i

A character/string data type is a string of characters enclosed


between two double or two single quotes. e.g “abc” produces abc
The length of a character string is the number of characters
between the quotes including blank space.
Features of Fortran Program 5/14

Variables

A variable is an entity that is used to store a value, comparable to


the use of variable in algebra.
Must be between 1 and 31 characters in length. The first character
must be a letter and the remaining if any, may be letters, digits or
underscore.
The variables are case insensitive and therefore NAME and naMe
are the same.
Fortran 90 does not have reserved words and therefore Fortran
keywords can be used as variable names but avoid it.
The type of a variable is declared in the declaration statement.
Variable can be given a value during the execution of the program -
by assignment or by a READ statement.
Features of Fortran Program 6/14

Valid Variables names


x
my variable
Results17
STUDENT
my20 NaMe

Invalid Variables names


1x first character is a number
my$variable ’$’ is not letter, numeral or underscore
my really really long variable name more than 31 characters
Features of Fortran Program 7/14

Declaration of Variables

Fortran 90 uses the following for variable declaration, where


type-specifier is one of the fortran following keywords: INTEGER,
REAL, LOGICAL, COMPLEX and CHARACTER, and list is a
sequence of identifier separated by commas.
type-specifier :: list
Example:
INTEGER :: x, total ! x and total holds integer data type
REAL :: avg, z ! avg and z holds real data type
CHARACTER variables require the string length
The keyword CHARACTER must be followed by the length attribute
(LEN = integer value), where integer value is an integer value that
holds the length of the string.
Features of Fortran Program 8/14

Declaration of Variables cont

If the length of the string is 1 then the CHARACTER can be


declared without the LEN attribute.
EXAMPLE:
CHARACTER (LEN = 20) :: answer, name
Variables answer and name can hold up to 20 characters.
CHARACTER :: phy
Variable phy can hold only ONE character ( i.e length is 1)
There is another way of declaring CHARACTER length when
PARAMETER attribute is used. The compiler assumed the length
from the parameter and you do not have to state the length. The
symbol * is used for the length of character.
EXAMPLE ::
CHARACTER (LEN = *), PARAMETER :: dir = “my program”
Features of Fortran Program 9/14

Variables Attributes
Various Fortran attributes may be specified for variables in their
type-declaration statement.
The PARAMETER attribute dictates that a constant is being
defined. A variable declared with this attribute may not have its
value changed within the program unit.
The PARAMETER attribute is used after the data type keyword,
followed by variable name followed by an = and then value for the
variable.
EXAMPLE :
REAL, PARAMETER :: PI = 3.143
! PI will be equal to 3.14 throughout the program
INTEGER, PARAMETER :: TOTAL = 10
! TOTAL will be equal to 10 throughout the program
Features of Fortran Program 10/14

Variable Initialization

A variable receives its value with


Initialization: It is done once before the program runs.
Assignment: It is done when the program executes an assignment
statement.
Input: It is done with a READ statement.
The variable can be initialized in their type-declaration statement
EXAMPLE:
REAL :: x = 0.05
! x can be assigned different value within the program
INTEGER :: gravity = 10
! gravity can be assigned different value within the program
It can also be initialized before execution statement.
Features of Fortran Program 11/14

Standard input/output (I/O) statement

Fortran uses the READ * as standard input statement to read data


into variable from the keyboard.
Read statement is of the form: READ *, input list
If READ * has n variables in its list, there must be n Fortran
declared constants.
Each entered constant must have the type of the corresponding
variable.
Data items are separated by spaces and may spread into multiple
lines.
The asterisk * can be change to specify the data format. The
format is of the form READ “(input format)”, input list
Features of Fortran Program 12/14

Standard input/output (I/O) statement cont

Fortran uses the PRINT * as standard output statement to display


data output on the screen.

Print statement is of the form: PRINT *, output list

To print undeclared string in your program put the string statement


in between double quotes. e.g PRINT*,“This is fortran class”
displays This is fortran class

PRINT*, without output list produces a blank line

A formatted PRINT statement is of the form: PRINT


“(output format)”, output list
Features of Fortran Program 13/14

Program Comments

Comments start with a exclamation mark (!)


Everything following (!) will be ignored by the compiler
Always comment your code so you can understand it later and also
for others to understand when reading your code.
Example :
output = input1 + input2 ! sum the inputs
PROGRAM first program
! This program tries to illustrate some basic features of fortran
INTEGER :: x, y
Features of Fortran Program 14/14

Cases and Indentation

Except within character strings, Fortran is completely


case-insensitive.

Fortran keywords such as REAL, DO, END, IF and intrinsic


functions such as SIN, COS , TAN should be in “UPPER CASE“
letters and user created entities such as variable names should be in
lower case.

’Indentation’, this is essential for program readability. It is common


to indent a program’s content by 2 spaces from its header and END
statement, and also indent the statements contained within, for
example, Fortran keywords such as IF constructs or DO loops by a
similar amount.
Operators in Fortran 1/13
There are four types of operators in Fortran 90:
arithmetic, relational, logical and character.

Arithmetic Operator

Order of Precedence Operator Meaning


[1] ** Exponentiation operator
[2] / Division operator
[2] * Multiplicative operator
[3] + additive operator
[3] - Minus operator
Within the same level of precedence, evaluation will proceed from
left to right for all the operators with the exception of
exponentiation where evaluation proceeds from right to left.
Parentheses (...) can be used to change the default order of
precedence.
Data Type Conversions 2/13
If an operator has two operands of the same data type (single
mode) then the result has the same type.
- Operations involving only reals yield a type real result.
- Operations involving only integers yield a type integer result.
If the operands have different data types (mixed mode) then an
implicit type conversion is applied to one of them to bring it to the
type of the other. When integers and reals are mixed in arithmetic
operations the result is a real.
Exponentiation is an exception to the type conversion rule:
- when the exponent is an integer it does not have to be converted
to the type of the other operand and the result is evaluated as if by
repeated multiplication.
- But if the exponent has any other data type the calculation is
performed by implicit use of the LOG and EXP functions
-If the exponent has a negative value the result is simply the
reciprocal of the corresponding positive power.
Data Type Conversions - example 3/13

10.0 / 2.0 * 5.0 evaluates as (10.0 / 2.0) × 5.0 = 25.0


5.0 * 2.0 ** 3 evaluates as 5.0 × (2.03 ) = 40.0
A −3 will be worked out as 1 / (A × A × A)
Repeated exponentiation is the single exception to the left-to-right
rule for equal precedence:
C
A ** B ** C evaluates as AB
For non-integer powers (which includes whole-number powers if a
decimal point is used) the result will be worked out by using the fact
that
ab = (elna )b = eblna
A3.0 will be worked out as e3.0lnA
Integer Division 4/13
If one integer divides another in a subexpression then the results of the
subexpression will be an INTEGER.
In short, division of two integers produces an integer result by truncation
(towards zero).
Consider,
REAL :: a, b, c, d, e
a = 1999/1000
a is (about) 1.000. The integer expression 1999/1000 is evaluated and
then truncated towards zero to produce an integral value, 1.
d = 1999.0/1000
e = 1999/1000.0
d and e are (about) 1.999 because both RHS’s are evaluated to be real
numbers, in 1999.0/1000 and 1999/1000.0 the integers are promoted to
real numbers before the division.
The Assignment Statement 5/13

The assignment statement has a form of

variable = expression
where variable has been declared and therefore has a type
If the type of variable and expression are identical, the result is
saved to variable.

If the type of variable and expression are not identical, the result of
expression is converted to the type of variable.

If expression is REAL and variable is INTEGER, the result is


truncated.
Mixed Type Assignment 6/13

When the RHS expression of a mixed type assignment statement has


been evaluated it has a specific type, this type must then be converted to
fit in with the LHS.
For example,

1 INTEGER = REAL
The RHS is evaluated and then the value is truncated (all the
decimal places lopped off ) then assigned to the LHS.

2 REAL = INTEGER
The INTEGER is evaluated as REAL. The RHS expression is simply
stored (approximately) in the LHS.
Mixed Type Assignment - example 7/13

REAL :: a = 1.1, b = 0.1 ! A real declaration with assignment


INTEGER :: i, j, k ! An integer declaration

i = 3.9 ! assigning a constant to i


i will be 3, the value 3.9 is truncated to an integer
j = -0.9 ! assigning a constant to j
j will be 0, value -0.9 is truncated to an integer
k=a-b ! assigning a variable to value of an expression
k will be 1 or 0, the result of a- b would be close to 1.0 (it could be
1.0000001 or it could be 0.999999999), so, because of truncation, k
could contain either 0 or 1.
Operators in Fortran 8/13

Relational Operator

Relational operators are used to test the relationship between two


numeric operands for that specific operator.
Expression involving these operators will reduce to either ’.TRUE.’
or ’.FALSE.’.

Operator Meaning
< or .LT. Less than
> or .GT. Greater than
== or .EQ. Identically equal to
/ = or .NE. Not equal to
<= or .LE. Less than or equal to
>= or .GE. Greater than or equal to
Operators in Fortran 9/13

Logical Operator

Logical operators act on logical expressions to create a largest


logical expression.
Parentheses (...) can be used to change the default order of
precedence.
Logical operators and relational operators may be combined into
logical expressions using the following operators:
Order Operator Meaning
[1] .NOT. Negative the following operand
[2] .AND. .TRUE. if both operands are .TRUE.
[3] .OR. .TRUE. if at least one operand is .TRUE.
[4] .EQV. .TRUE. if both operands reduce to the same
[4] .NEQV. .TRUE. if both operands are different
Operators in Fortran - example 9/13
PROGRAM logic examp
IMPLICIT NONE
LOGICAL :: test, try, phy !declaring a logical variables
LOGICAL:: student=.TRUE. !declaring and initialise logical variable

INTEGER:: age=20 !integer declaration and initialisation


test = .NOT. (age==20) !negating the result of the expression
PRINT*, test !result is False
try = (student) .AND. (age==20) !using the AND operator
PRINT*, try !result is TRUE because both statements are true
phy = .NOT. (student) .OR. (age==20) !using the OR operator
PRINT*, phy !result is TRUE because one statement is true
END PROGRAM logic examp
Operators in Fortran 10/13

Character Operator

There is only one character operator, concatenation symboled //.


If strings A and B have lengths m and n, then concatenation A // B
is a string of length m+n
It is use to join two separate characters.

Example:
’Man’ // ’chester’ gives ’Manchester’
CHARACTER(LEN = 7) :: word 1 =“missing”
CHARACTER(LEN = 3) :: word 2 = “you”
CHARACTER(LEN = 10) :: ans
ans = word 1 // word 2 ! missingyou
Operators in Fortran 11/13

Character substrings

A consecutive portion of a string is a substring.


To use substrings, one may add an extent specifier to the
CHARACTER variable.
An extent specifier has the following form:
(integer exp1 : integer exp2)
The first and the second expressions indicates the start and end: (3
: 8) means 3 to 8.
If A = “abcdefg”, then A (3 : 5) means A’s substring from position
3 to position 5 (i.e., “cde”)
If the first extent specifier is missing, the substring start from the
first character, and if the second extent specifier is missing, the
substring ends at the last character.
Fortran Intrinsic Function 12/13
Function Meaning Data type
SQRT(x) square root of x Real
COS(x) cosine of x Real in radian
SIN(x) Sine of x Real in radian
TAN(x) Tangent of x Real in radian
ASIN(x) Sine inverse Real
ACOS(x) Cosine inverse Real
ATAN(x) Tangent inverse Real
EXP(x) ex Real
ALOG(x) loge (x) Real
ALOG10(x) log10 (x) Real
ABS(x) Absolute value of x Real, Integer
MAX(x1,x2 .... ) Maximum value of x vector Real, integer
MIN(x1,x2 ....) Minimum value of x vector Real, integer
MODULO(x, y) x modulo y Real, integer
MOD(x, y) remainder when x is divided by y Real
Data type Conversions 13/13

Function Meaning
INT(x) Truncate a real number to an integer
NINT(x) Round a real number to the nearest integer
REAL(x) Convert to real
CEILING(x) Nearest integer greater than or equal to x
FLOOR(x) Nearest integer less than or equal to x
CMPLX(x) Real to complex
FRACTION(x) Fractional part of real
Write and Run fortran program 1/3

Creating a fortran program

Either open a pre-existing source code or create it and save using


text editor and should have a name that ends in .f90.
A text editor is a type of program used for editing plain text files.
Examples of some text editors are (emacs, gvim, vi, gedit, kile,
xemacs etc)
On command line and inside your program directory, open the file by
typing:
emacs prog1.f90 where prog1 is the filename and emacs text editor
Emacs shows blank page since prog1 is a new file.
Write and Run fortran program 2/3

Compiling fortran program

The role of fortran compilers is to translate the plain text of the


source code to binary code for the processor.
Some free available compilers are (g95, gfortran, f95, etc )
During compilation the program is checked for syntax errors and, if
none are found, an executable file is created
The default name for the executable file will be a.out but you can
also specify a name with different extension.
In the same directory containing the program file type of one these
commands:
1. g95 -o prog1.exe prog1.f90 this produces executable file called
prog1.exe
2. g95 prog1.f90 this produces executable file called a.out
Write and Run fortran program 3/3
Please note that the above compilation syntax is applicable only when
the main program and subprograms/procedures are in the same file.
When we get to Fortran subprograms part of the course, we will use
different compilation syntax whe the subprogram and main program are
in different files.

Running fortran program

If compilation step is carried out successfully, then the executable


prog1.exe or a.out will appear when the files are listed with ls.
You can then run the program with the command ./prog1.exe or
./a.out
The ./ before the file name tells the computer that the executable
file is in the current directory.

You might also like