You are on page 1of 28

2.

Basic Elements of Fortran

Structure of a Fortran Program


must be in the
1st line if present

31 characters

declaration
section

program my_first_program
! Declare variables
integer :: i, j, k ! i, j, k are integer
! Interactive input
write(*,*) 'Enter the numbers'
read(*,*) i, j

execution
section

comment after
exclamation point

! Multiply the numbers


k = i*j
! Interactive output
write(*,*) 'i*j = ', k

termination
section

(optional) stop running program,


present before end program

stop
end program
tell compiler no
more statement

Goto the folder \GNU_emacs_Fortran

Click CMD_emacs_Fortran.bat to open command prompt console and Emacs editor


>dir
>mkdir examples
>cd examples
In Emacs editor, create a new file named 2-2.f90 in the folder \examples
Copy the program from course webpage and paste on the Emacs editor, and save it.
>gfortran 2-2.f90
>dir
>a.exe
Enter the numbers
2
4
i*j =
8
>a.exe
Enter the numbers
2.
At line 7 of file 2-2.f90 (unit = 5, file = 'stdin')
Fortran runtime error: Bad integer for item 1 in list input

Fortran Character Set


A
a
0
_
+
(

(uppercase) 26
(lowercase) 26
(numbers) 10
(underscore) 1
- * / ** (arithmetic symbols) 5
) . = , ' $ : ! " % & ; < > ? blank (miscellaneous symbols) 17
~ Z
~ z
~ 9

Total 86 characters can be used in Fortran 95


Upper case and lowercase letters are equivalent in Fortran,
i.e. Fortran is case insensitive.
But C++ and Java are case sensitive, i.e., A and a are different characters.

Fortran Statement
Executable statement
Non-executable statement :
provide information necessary for the proper operation of the program
Free-source form statement (90/95/2003)
Fixed-source form statement (77 and earlier version)
But backward compatible,
i.e., you can use fixed-source form in 90/95, but cannot use free-source form in 77.

Free-source form statement


132 characters
statement number
which gives name of a
statement to refer to
(1~99999)

12

x = y+z

12

x = y &
+z

12
&

x = y &
+z

12
&

x = y
+z

! summation of x and y

continuation indicator

40 lines

syntax error

Fixed-source form statement


Do not use!! Just to show you in case your professor is still using Fortran 77.
continuation
indicator column

statement
label column
1

instructions column
5

9 2

9 10 11 12 13 14 15

card identification field


71 72 73 74 75 76 77 78 79 80

x = y + z
2 4

w r i t e
1

( * , * )

A Hollerith card that, when punched, will contain one Fortran statement.

Punching machine

Card reader

What computer (IBM 704) looked like when Fortran was introduced.

Constants and Variables


legal variables:
Time
z01234567
I_LOVE_you
31 characters; legal characters: a~z, A~Z, 0~9, _
illegal variables:
This_is_a_too_long_variable_name
3days

(cannot begin with a digit)

money$

(cannot use $)

(too many characters)

Fortran has 5 intrinsic (built in) types of constants and variables:


integer
real
complex
character
logical

Integer Constant
legal integer constants:

illegal integer constants:


-100.
1,357,076

0
-9999
+18
14

Real Constant
legal real constants:
10.
-99.9
+1.0E-3
124.8E20
0.15E+1

(=1 x 10-3)
(=1.248 x 1022)

illegal real constants:


1,000,000
10E3
10.E1.5

A real value is stored in two parts: the mantissa and the exponent

3.14159265
+1.0E-3
(=1.0 x 10-3)
124.8E20
(=1.248 x 1022)
0.15E+1

mantissa : precision (number of significant digits)


exponent : range
The precision and range of a real value are determined by number of bits allocated.
computer

bits per default


bits in mantissa
real number

precision in
decimal digits

bits in exponent

range in
exponent

old Intel 32-bit


PC (Pentium)

32

24

10-38 ~ 1038

current Intel
64-bit PC

32

24

10-38 ~ 1038

declared as
double precision

64

53

15

11

10-308 ~ 10308

64

49

14

15

10-2465 ~ 102465

Cray
(supercomputer)

Character Constants and Variables


legal character variables:
'This is a test'
"This is a test"
"3.14159265"
"Dog is man's best friend"
'"Who cares? "'
illegal variables:
'This is a test"
'This is a test''

Logical Constants
(Logical constants are rarely used)
.TRUE.
.FALSE.

Default and Explicit Variables Typing


Default (not specified): (i,j,k,l,m,n) + other characters are integer variables
num
i38
Others are real variables
vel
q2
The type of a variables can also be explicitly declared by type declaration statements.
integer :: var1, var2, var3
real :: var4, var5
logical :: var6
complex :: var7, var8
optional, but is preferable

Character variables must be declared by:


optional
character(len=10) :: var1, var2
character(15) :: var3

PROGRAM my_first_program
! Purpose:
! To illustrate some of the basic features of a Fortran program.
!
! Declare the variables used in this program.
INTEGER :: i, j, k ! All variables are integers
! Get the variables to multiply together.
WRITE(*,*) 'Enter the numbers to multiply: '
READ(*,*) i, j
! Multiply the numbers together.
k = i * j
! Write out the result.
WRITE(*,*) 'Result = ', k
! Finish up.
STOP
END PROGRAM

Assignment Statements and Arithmetic Calculations


Assignment Statements
variable = arithmetic expression
store the value of expression
into the variable location
i = i+1

If original i is 3,
after the assignment statement i is 4

Arithmetic Operators: + - * / **
a*-b
wrong
operation a**-2

a*(-b)
a**(-2)

2**((8+2)/5) = 2**(10/5)
= 2**2
= 4

Integer Arithmetic
i = 3/4
4/4
5/4
6/4
7/4
8/4
9/4

0 is assigned to i
1
1
1
1
2
2

Real Arithmetic (or floating-point arithmetic)


x = 3./4.
1./3.

0.75
0.333333...

(precision depends on computers)

On some computer, 3.*(1./3.) 1


but 2.*(1./2.) = 1

Hierarchy of Operators (order of arithmetic operators)


same as the rules of algebra
distance = 0.5*accel*time**2
= 0.5*accel*(time**2)
(0.5*accel*time)**2
a*b+c*d+e/f**g = (a*b)+(c*d)+(e/(f**g))
a*(b+c)*d+(e/f)**g = (a*(b+c)*d)+(e/f)**g
a*(b+c)*(d+e)/f**g = ((a*(b+c))*(d+e))/(f**g)

a**b**c = a**(b**c)
(a**b)**c

43 = 49 = 262144
642 = 4096

Mixed-mode arithmetic (Do NOT use whenever possible)

The computer converts the integers into real numbers, and real arithmetic is used.
3/2
3./2.
3./2
3/2.

1
1.5
1.5
1.5

integer (= 0)
1+1/4

1.+1/4

1.

1+1./4
real (=0.25)

1.25

Mixed-mode exponentiation (This, however, is preferable!)


var = y**n = y*y*y*...*y
n times

But

var = y**x = e**(x*LOG(y))


(-2.0)**2

(-2.0)**2.0

some compiler will result in runtime error

Intrinsic Functions (some)


Function name & argument
SQRT(X)

(X 0)

ABS(X)

Argument type Result type


R

R/I

R/I

SIN(X)

(X in radians)

COS(X)

(X in radians)

TAN(X)

(X in radians)

EXP(X)

ALOG(X)

ALOG10(X)

INT(X)

NINT(X)

REAL(I)

MOD(A,B)
MAX(A,B)
MIN(A,B)
MIN(A,B)
ASIN(X)
ACOS(X)
ATAN(X)

PROGRAM my_first_program
! Purpose:
! To illustrate some of the basic features of a Fortran program.
!
! Declare the variables used in this program.
INTEGER :: i, j, k ! All variables are integers
! Get the variables to multiply together.
WRITE(*,*) 'Enter the numbers to multiply: '
READ(*,*) i, j
! Multiply the numbers together.
k = i * j
! Write out the result.
WRITE(*,*) 'Result = ', k
! Finish up.
STOP
END PROGRAM

List-directed Input and Output


read (io_unit, statement_no_format)
write(io_unit, statement_no_format)
*, means to read from
standard input device

*, means free-format input


(or list-directed input)

The types of the variables in the input variable list determine the required
format of the input data.
read(*,*) i, j
begin to read another line of data
read(*,*) k, l
write(*,*) " Output: ", i, j, k, l

> 1, 2, 3, 4
> 5, 6, 7
> Output: 1 2 5 6

input in console
output in console

Initialization of Variables
3 ways to initialize a variable:
integer :: i
i = 1

real :: pi
pi = acos(-1.)

integer :: i
read(*,*) i

real :: pi
read(*,*) i

integer :: i = 1

real :: pi = acos(-1.)

To get the initialized variable as a constant throughout the program,


use named constant as:
real, parameter :: pi = acos(-1.)
real, parameter :: pi = acos(-1.)
pi = 3.14
real, parameter :: pi = 3.14
pi = acos(-1.)

These are not allowed since pi


has been assigned as a constant
parameter.

IMPLICIT NONE Statement


Disable the default typing provisions of Fortran.
If you use implicit none statement, you must explicitly declare every variable in
the program otherwise it is considered as an error.
Good reasons to use implicit none statement:
catch typos at compilation time, and make the code more manageable
program test_1
real :: time =10.0
write (*,*) 'Time = ', tmie
end program test_1

Program test_1 will be compiled successfully, and produce output:


Time = 0.000000E+00.
program test_2
implicit none
real :: time =10.0
write (*,*) 'Time = ', tmie
end program test_2

In contrast, program test_2 will be compiled with error!

Program Example:

5
T t 32 273.15
9
Convert temperature T in degrees of Fahrenheit (F) to an absolute
temperature t in Kelvin (K).
5
=
32 + 273.15
9
program temp_conversion
! Purpose: To convert an input temperature from degrees
!
Fahrenheit to an output temperature in kelvins.
implicit none
! Force explicit declaration of variables
! Declare variables, and define each variables when it is declared
real :: temp_f
! Temperature in degrees Fahrenheit
real :: temp_k
! Temperature in kelvins
! Prompt the user for the input temperature.
write(*,*) 'Enter the temperature in degrees Fahrenheit: '
read (*,*) temp_f
! Convert to kelvins.
temp_k = (5./9.)*(temp_f-32.)+273.15
! Write out the result.
write(*,*) temp_f, ' degrees Fahrenheit = ', temp_k, ' kelvins '
! Finish up.
end program

In Emacs editor, create a new file named 2-6.f90 in the folder \examples
Copy the program from course webpage and paste on the Emacs editor, and save it.
>gfortran 2-6.f90
>dir
>a.exe
Enter the temperature in degrees Fahrenheit:
38.
38.000000

degrees Fahrenheit =

276.48334

kelvins

>
>gfortran 2-6.f90 -o 2-6.out
>dir
>2-6.out
Enter the temperature in degrees Fahrenheit:
80.
80.000000
>

degrees Fahrenheit =

299.81665

kelvins

Homework 1
Write a Fortran program which prompts to input your name (in English) and ID as in the
example program, and output as follow:
My name is your name.
My student ID is your id.

Homework 2
Write a Fortran program to computer the area of a triangle determined by jointing the
three points (x1,y1), (x2,y2) and (x3,y3) given by a user who executes the program.
Use implicit none statement in your program.

Ask to receive a return receipt when mailing your homework as shown in the figure.

You might also like