No Slide Title

Download Report

Transcript No Slide Title

Elementary FORTRAN
Elementary FORTRAN 77
All FORTRAN programs consist of data
that is manipulated by a set of control
structures to produce a result.
Control structures are statements that
implement the algorithm steps you have
chosen when you designed the program.
Data + algorithms = programs
Command structure rules
FORTRAN 77 (and earlier versions) had a
fixed-column method of structuring
commands.
Later versions of FORTRAN allow freeformat.
Since the fixed format is so common in
FORTRAN we will start out writing our
programs that way.
Column-based (fixed)
structure (f77)
12345678901234567890123456789012345678901234567890123456789012345678901234567890
FORTRAN programs were originally punched on
cards. Modern FORTRAN still supports the conventions
that were used in that day. For example, every FORTRAN
command must obey the following set of rules.
Column 1: reserved for comment marks only. Valid comment
marks are c, C or * in f77, f90 adds !
Columns 2-5: reserved for statement labels. These are integers
used to mark a line so that other statements can get back to
it. They are labels, not line numbers.
Column 6: reserved for a continuation mark (either a + or a
single digit integer 1,2,3,4..etc. These indicate that the line
is a continuation of the previous one.
Columns 7-72: Your executable FORTRAN statements go here
Columns 73-80: For line sequence numbers. Not used any more.
Column-based structure (f77)
12345678901234567890123456789012345678901234567890123456789012345678901234567890
c this is a comment line, comments start in column 1
c
* Either a c, C or * may be used to indicate a comment
c
***********************************************************************
INTEGER i
PRINT *, “This long line continues on the next one. To indicate
+ this I place a + in column 6 (the continuation column)”
DO 10 (i=1,10)
PRINT*, “Hello world!”
10
CONTINUE
END
Elementary FORTRAN 77
All FORTRAN programs consist of data
that is manipulated by a set of control
structures to produce a result.
Control structures are statements that
implement the algorithm steps you have
chosen when you designed the program.
Data + algorithms = programs
Program structure
First you should put in comments
Then specify to the compiler what data
items (variables) you program will need.
Give each a name
Tell what type of data it is
Specify how many (if more than 1)
Then perform the executable statements
that act on the data to produce results.
Program structure
Comments
Specification
(variable declaration)
Execution
c
c
c
This is a demo program
by me
integer num
print*, “Enter a number”
read*, num
print*, “The number you entered is:”
print*, num
end
Basic data types
These are the data types supported by
standard FORTRAN
integers
real numbers
double precision (f77 only)
complex (f90 only)
character
logical
Integers
NOT intergers!
Integers consist of positive or negative
whole numbers or 0
…,-2, -1, 0, 1, 2, …
Declared as
 INTEGER num
(in f77 or f90)
 INTEGER :: num
(in f90, preferred)
Binary representation of
integers
128
64
32
16
8
4
2
1
0 1 0 0 0 0 0 1
64 + 1 = 65
This is an 8-bit byte
most PCs use 32 bit words (4 bytes)
Often the first bit is a sign bit.
Sign bits
128
64
32
16
8
4
2
1
0 1 0 0 0 0 0 1
The first bit may be used as a sign bit and
therefore unavailable to represent integers.
This cuts the capacity for representing large
integers in half (from 256 to 128).
Real numbers
Any number that might have a decimal
point.
3.14159, 4.0, -234.56
If you enter a real number without a
decimal point, one will be inserted
automatically. (4 becomes 4.0)
Binary representation of
real numbers
100101000100001001001110000010010 00101101011000100110000100100
exponent
7,324,645,336 x 10
mantissa
31,254,355,218
Scientific notation
Often called exponential notation
12345.6789 becomes
12.3456789E3 (x 1000)
1.23456789E4 (x 10000)
0.123456789E5 (x 100000)
123456789E-4 (x 0.0001)
For all numeric data
DO NOT include punctuation in input
Please enter a number
1,234 is incorrect
$1234 is also incorrect
Real numbers can take integers but not
vice versa.
Please enter a real number
1234 is OK
Please enter an integer
123.45 is incorrect
Double precision
Doubles the representational size of a real
number.
Not used under FORTRAN 90 but common
under FORTRAN 77 for some applications.
We will probably not need it.
Complex numbers
Contain both a real and an imaginary
part.
This is not a standard data type in any
other computer language.
Not supported in f77
More on this later.
Character data
Much easier to handle in FORTRAN than in
most other languages (Pascal, C, C++, etc.)
Valid characters are all standard ASCII and
UNICODE characters
Character strings are enclosed in “”
“This is a line”
Above string has length of 14 (spaces count)
Special cases
Apostrophes work the same as quotes
‘This is a sentence’
but you cannot mix them:
‘This is a sentence”
How do you handle embedded
apostrophes or quotes?
‘don’’t’
“I said “”Hi”””
use two sets to produce one character
Character declarations
In FORTRAN 77
Character *10 name
Character fname*10, lname*20
In FORTRAN 90
Character(10) :: name
Character(10) :: name, lname*20
Logical data
Logical means true or false
We will use logical data later in the course
and spend more time on it then.
Mixed types
Some types can be mixed
REAL num1
INTEGER num2
num2 = 5
num1 = num2
Others cannot
character*10 name
num1 = name
Variable declarations
When a variable is declared you give the
name and data type of the variable.
The compiler figures out the size that will
be required.
If you use a variable in your program that
you forgot to declare, the compiler has
assigned it a type: integer or real
This assignment may not be appropriate
Implicit data type rule
Any variable that has not been declared
and begins with the letters i through n
automatically becomes an integer.
Variables beginning with any other
character automatically become real
numbers.
Implicit data typing problem
INTEGER sum, n
… program reads data, stores the count of
how many in n and the total of them in
sum
mean = sum / n
Since mean was not declared it becomes
an integer. This is probably not what you
want here.
Uses for implicit data typing
Loop control variables are variables that
only exist to count the number of time a
loop has executed.
They should be integers
A very common convention is to use the
undeclared variables i, j, k, l, m and n for
loop control variables because implicit
typing makes them integers by default.
Turning off implicit typing
Most programming languages regard
implicit typing as dangerous.
If it is turned off, then all variables must
be explicitly declared by you.
f77 does not allow you to turn this off but
f90 does. Like this…
IMPLICIT NONE
This command is placed at the top of the
executable program statements.
The important points
When a variable is declared, three things
happen.
1. Space to store your data is allocated in
memory
2. That space is assigned a data type
3. That space is assigned a name
Memory allocation
Memory cells
REAL length, angle, period
Variable declaration first must
find available memory cells to store
this data in.
It then allocates them for the
program and assigns your
identifier names to them.
1345243
1345244
1345245
1345246
1345247
1345248
1345249
1345250
1345251
1345252
1345253
1345254
1345255
Memory allocation
Memory cells
REAL length, angle, period
length
angle
period
1345243
1345244
1345245
1345246
1345247
1345248
1345249
1345250
1345251
1345252
1345253
1345254
1345255
Identifiers
So, now that we are familiar with the
built-in data types of this language, what
do we do with them?
We will solve problems using data items
that are of these basic types.
These items will be given names.
In fact, we will have to give names to
many things in our programs.
Names are called identifiers
Naming conventions
Identifiers
must begin with a letter
cannot be longer than 31 characters (8 is the
common standard practice in f77)
Only letters, digits or underscores (_) are
allowed.
Valid and invalid identifiers
Valid identifiers
number, s1, name, speed_of_light
Invalid identifiers
1stnum, soc-sec-num
A good rule of thumb is to keep the
identifier names short and concise.
name, employee, id_num (good)
employee_name
(too much typing?)
the_first_number_entered_by_the_user
Variable initialization
Initialization refers to the act of assigning a
value to a variable.
Example:
integer num
num = 10
The = sign is called the ‘assignment operator’
Do not think of it as ‘equal to’. It really means
assign the right-hand value to the left-hand
variable
Constants
A constant is a data item whose value
never changes after initialization.
Use the parameter statement
f77
parameter (pi = 3.14159, g = 980)
f90
real, parameter :: pi = 3.14159, g = 980
Mathematical expressions
FORTRAN comes from the phrase
FORmula TRANslation
Coding mathematical formulas is an
important part of the language.
Example:
y = a * x + b
The expression on the right is evaluated
and the result is assigned to the variable
on the left.
Arithmetic operators
In order to carry out mathematical
expressions the computer must
understand what operations to perform.
This means it needs to know a set of
arithmetic symbols, what operations they
stand for and which ones should be done
before others.
Arithmetic Operators
** exponentiation
* multiplication
/ division


+ addition
- subtraction
a = 2**3
a=2*3
a=2/3
a = 2 / 3.0
a = 2 / real(3)
a=2+3
a=2-3
Mixed mode expressions
Mixed mode expressions combine more
than one data type.
Example:
a = 4 + 7 / 2 * 3 - 7
a = 14/5.0 + 4
Watch out for integer division!
Group expressions using parentheses
rather than guessing about what will
happen.
Integer division
An integer divided by an integer IS AN
INTEGER
integer a
a = 14 / 3
PRINT*, a
The output from this is 4
not 4.666667 as you might expect
Precedence (priority) rules
Exponentiation is performed first.
Multiple exponentiation is performed right
to left.
A = 2 ** 3 ** 2 is same as a = 2 ** 9
a = 5 - 3 ** 3 a becomes -22
Multiplication and division are next.
If more than one, go left to right.
Addition and subtraction are last.
If more than one, go left to right.
Examples
2 + 4 ** 2 / 2
2 + 16 / 2
2 +
8
10
Example
5 * 11 - 5 ** 2 * 4 + 9
5 * 11 - 25 * 4 + 9
 55
- 25 * 4 + 9
 55
100 + 9

-45
+9

-36
Example with parentheses
(5 * (11 - 5) ** 2) * 4 + 9
(5 * (6) ** 2) * 4 + 9
(5 * 36) * 4 + 9
(180) * 4 + 9
720 + 9
729
Expression trees
4 - 7 ** 2 / 4 * 3 + 2
49
12
36
-32
-30
Functions
INT( arg )
NINT ( arg )
REAL ( arg )
ABS ( arg )
IABS ( arg )
SQRT ( arg )
integer - drops fraction
integer - rounds arg
converts to real
absolute value - real
absolute value - integer
square root
Functions
EXP (arg)
ALOG (arg)
ALOG10 (arg)
SIN (arg)
COS (arg)
TAN (arg)
natural exponent e^arg
natural logarithm
logarithm
arg in radians
arg in radians
arg in radians
Functions
MOD (A1, A2)
MAX0 (A1,...An)
AMAX1 (A1,...An)
MIN0 (A1,...An)
AMIN1 (A1,...An)
remainder of A1/A2
largest value - integer
largest value - real
smallest value - integer
smallest value - real
Examples of function use
Calculate the volume of an oblate
spheroid. The formula is:
2
V = (4/3)a b
Fortran version
parameter (pi = 3.14159)
v = (4/real(3))*pi*a**2*b
Other examples
Algorithm
if num goes into 100 evenly then …
Fortran version
if (MOD(100, num) .eq. 0) then
MOD
MOD stands for modulo
It is a mathematical term used to denote
the integer remainder from integer division.
In other words, mod takes two integer
arguments. It then divides the first one by
the second and finds the integer remainder.
This integer remainder is what MOD sends
back to the program.
MOD in action
PRINT*, MOD(14,3)
will print the value 2
3 goes in to 14 four times with 2 left over
2 is the integer remainder from integer
division.
4r2
3
14
12
2
Examples continued
a = SQRT(b) b cannot be negative
t = TAN(angle) angle must be in radians
i = INT(4.7) sets i to 4
i = NINT(4.7) sets i to 5
Note: to use SIN, COS, TAN, you must
convert the angle from degrees to
radians. This is done by multiplying the
angle by pi and then dividing by 180.
Integer division and MOD
This example will construct a program to
determine the smallest number of coins to
dispense as change. Useful if you are a
vending machine.
Rules:
amount of change is always < $1.00
valid coins are quarters, dimes, nickels, pennies
Alogorithm
1.
2.
3.
4.
5.
6.
Declare variables
Prompt for amount of change to give back
Read amount
Figure out how many quarters can be taken out of it
Subtract the quarters from the amount
Figure out how many dimes can be taken out of
the remaining amount
7. Subtract the dimes from the amount
8. Figure out how many nickels can be taken out of
the remaining amount
9. Subtract the nickels from it and all you have left
are the number of pennies
10. Add up the number of quarters, dimes, nickels and
pennies you took out to get the number of coins
11. Print out the number of coins.
12. END
Program example:
Vending machine change
c
c
This program figures out the fewest number of coins
to dispense as change in a vending machine
INTEGER amount, coins, numq, numd, numn, nump
PRINT*, “How much change should you give? <$1”
READ*, amount
numq = amount / 25
amount = MOD(amount, 25)
numd = amount / 10
amount = MOD(amount, 10)
numn = amount / 5
nump = MOD(amount, 5)
coins = numq + numd + numn + nump
PRINT*, “The machine will dispense”, coins, “coins”
END
Trace of vending machine
program: statement numbering
1
2
3
4
5
6
7
8
9
10
11
12
INTEGER amount, coins, numq, numd, numn, nump
PRINT*, “How much change should you give? <$1”
READ*, amount
numq = amount / 25
amount = MOD(amount, 25)
numd = amount / 10
amount = MOD(amount, 10)
numn = amount / 5
nump = MOD(amount, 5)
coins = numq + numd + numn + nump
PRINT*, “The machine will dispense”, coins, “coins”
END
Trace of 99 cents
1
2
3
4
5
6
7
8
9
10
11
12
Declare vars.
Prompt for amount
Read amount
Compute # of quarters
Compute new amount
Compute # of dimes
Compute new amount
Compute # of nickels
Compute # of pennies
Add up coins
print results
END
amount coins numq numd numn nump
?
?
?
?
?
?
99
3
24
2
4
0
4
9
Assignment statements
Assignment statements are the very heart
of this, and all, computer languages.
They assign a value to a variable
Example:
angle = angle * pi / 180
The assignment operator (=)
Assigns the value on the right hand side
of the = to the location on the left.
Do not think of it as ‘equals’
Think of it as ‘assigns’ or ‘is set to’
Example:
count = count + 1
(see next slide)
The nature of assignment
The rvalue is put into the left-hand
location (a variable)
UMDid = 2123456
UMDid
2123456
The nature of assignment
DO NOT read = as ‘equals’ or you will
encounter algebraic nonsense.
Count = Count + 1
5
=
5
+ 1
Count
5
Count
6
6
Mixed mode assignments
If an integer is assigned to a real variable
it becomes a real
If a real is assigned to an integer you will
get an error message.
Be careful to only assign data of the
correct type
Input statements: READ
The READ statement gets it’s input from
the keyboard.
Later in the semester we will learn how to
read data from files.
The format is
READ*, var1, var2, var3
The * simply means ‘use the default
method of getting data from input
Output statements: PRINT
To print a message on the screen use the
PRINT statement.
To write your output to a file use the
WRITE statement (covered later in the
semester)
PRINT*, var1, var2, var3
The *, indicates that you are printing to
the default output device
PRINT considerations
You may print the contents of a variable or
character strings or both.
PRINT*, “Please enter an integer”
READ*, num
PRINT*, num
PRINT*, “You entered”, num
PRINT*, “num is: “, num, “cm”
Output control
Unfortunately, right now we cannot
control what happens with our output
very well.
Num is 4.00000
Later we will learn how to control
everything (like the number of decimal
points, etc.)
Files
Chapter 2, section 10 deals with files.
We will not do this until much later in the
course.