Elementary FORTRAN. Elementary FORTRAN 77 zAll FORTRAN programs consist of data that is manipulated...
-
Upload
howard-stanley-carson -
Category
Documents
-
view
233 -
download
3
Transcript of Elementary FORTRAN. Elementary FORTRAN 77 zAll FORTRAN programs consist of data that is manipulated...
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 free-format.
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 oncards. Modern FORTRAN still supports the conventionsthat were used in that day. For example, every FORTRANcommand 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 hereColumns 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 1c* Either a c, C or * may be used to indicate a commentc*********************************************************************** 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 commentsThen 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 This is a demo programc by mec
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
0 1 0 0 0 0 0 1128 64 32 16 8 4 2 1
64 + 1 = 65
This is an 8-bit bytemost PCs use 32 bit words (4 bytes)Often the first bit is a sign bit.
Sign bits
0 1 0 0 0 0 0 1128 64 32 16 8 4 2 1
The first bit may be used as a sign bit andtherefore unavailable to represent integers.This cuts the capacity for representing largeintegers in half (from 256 to 128).
Real numbers
Any number that might have a decimal point.
3.14159, 4.0, -234.56If 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 mantissa
7,324,645,336 x 1031,254,355,218
Scientific notation
Often called exponential notation12345.6789 becomes12.3456789E3 (x 1000)1.23456789E4 (x 10000)0.123456789E5 (x 100000)123456789E-4 (x 0.0001)
For all numeric dataDO 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 f77More 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 falseWe 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 / nSince 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 integersA 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 typingMost 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 NONEThis 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 mustfind available memory cells to storethis data in.
It then allocates them for theprogram and assigns your identifier names to them.
1345243134524413452451345246134524713452481345249134525013452511345252134525313452541345255
Memory allocation Memory cells
REAL length, angle, period 1345243134524413452451345246134524713452481345249134525013452511345252134525313452541345255
length
angle
period
IdentifiersSo, 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 identifiersValid identifiers
number, s1, name, speed_of_lightInvalid identifiers
1stnum, soc-sec-numA 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 statementf77
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 a = 2**3* multiplication a = 2 * 3/ division a = 2 / 3 a = 2 / 3.0 a = 2 / real(3)+ addition a = 2 + 3- subtraction 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 divisionAn integer divided by an integer IS AN
INTEGER
integer aa = 14 / 3PRINT*, a
The output from this is 4not 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 / 22 + 16 / 22 + 810
Example
5 * 11 - 5 ** 2 * 4 + 95 * 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 + 9720 + 9729
Expression trees
4 - 7 ** 2 / 4 * 3 + 2
49
12
36
-32
-30
Functions
INT( arg ) integer - drops fractionNINT ( arg ) integer - rounds argREAL ( arg ) converts to realABS ( arg ) absolute value - realIABS ( arg ) absolute value - integerSQRT ( arg ) square root
Functions
EXP (arg) natural exponent e^arg
ALOG (arg) natural logarithmALOG10 (arg) logarithmSIN (arg) arg in radiansCOS (arg) arg in radiansTAN (arg) arg in radians
Functions
MOD (A1, A2) remainder of A1/A2MAX0 (A1,...An) largest value -
integerAMAX1 (A1,...An) largest value - realMIN0 (A1,...An) smallest value -
integerAMIN1 (A1,...An) smallest value - real
Examples of function use
Calculate the volume of an oblate spheroid. The formula is:
V = (4/3)a bFortran version
parameter (pi = 3.14159) v = (4/real(3))*pi*a**2*b
2
Other examples
Algorithmif num goes into 100 evenly then …
Fortran versionif (MOD(100, num) .eq. 0) then
MOD
MOD stands for moduloIt 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 23 goes in to 14 four times with 2 left over2 is the integer remainder from integer
division.
3 14
12
4 r 2
2
Examples continueda = SQRT(b) b cannot be negativet = TAN(angle) angle must be in radiansi = INT(4.7) sets i to 4i = 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. Declare variables2. Prompt for amount of change to give back3. Read amount4. Figure out how many quarters can be taken out of it5. Subtract the quarters from the amount6. Figure out how many dimes can be taken out of the remaining amount7. Subtract the dimes from the amount8. Figure out how many nickels can be taken out of the remaining amount9. Subtract the nickels from it and all you have left are the number of pennies10. Add up the number of quarters, dimes, nickels and pennies you took out to get the number of coins11. Print out the number of coins.12. END
Program example:Vending machine change
c This program figures out the fewest number of coinsc 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 INTEGER amount, coins, numq, numd, numn, nump2 PRINT*, “How much change should you give? <$1”3 READ*, amount4 numq = amount / 255 amount = MOD(amount, 25)6 numd = amount / 107 amount = MOD(amount, 10)8 numn = amount / 59 nump = MOD(amount, 5)10 coins = numq + numd + numn + nump11 PRINT*, “The machine will dispense”, coins, “coins”12 END
Trace of 99 cents
amount coins numq numd numn nump1 Declare vars. ? ? ? ? ? ?2 Prompt for amount3 Read amount 994 Compute # of quarters 35 Compute new amount 246 Compute # of dimes 27 Compute new amount 48 Compute # of nickels 09 Compute # of pennies 410 Add up coins 911 print results12 END
Assignment statements
Assignment statements are the very heart of this, and all, computer languages.
They assign a value to a variableExample:
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
Count
5 + 15=
65
6
Count
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 isREAD*, var1, var2, var3The * 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, var3The *, 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*, numPRINT*, numPRINT*, “You entered”, numPRINT*, “num is: “, num, “cm”
Output control
Unfortunately, right now we cannot control what happens with our output very well.
Num is 4.00000Later 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.