Document 10834094

advertisement
CSE 305 Introduc0on to Programming Languages Lecture 5 CSE @ SUNY-­‐Buffalo Zhi Yang Courtesy of School of Aerospace Engineering at Georgia Ins0tute of Technology Courtesy of Google No0ce Board •  In homework2, in addi0on to original problem, the output format of binary file is posted. No0ce the preferred MIPS assembly language instruc0on set and System call is also posted. Quiz •  Quiz1 will be given on June 6, 2013, during the recita0on 0me. Introduc0on of IBM 704 The IBM 704, the first mass-­‐produced computer with floa0ng point arithme0c hardware, was introduced by IBM in 1954.[1] The IBM 704Manual of opera,on states:[2] The type 704 Electronic Data-­‐Processing Machine is a large-­‐scale, high-­‐speed electronic calculator controlled by an internally stored program of the single address type. The 704 was a significant improvement over the earlier IBM 701 in terms of architecture and implementa0on. Like the 701, the 704 used vacuum tube logic circuitry. Changes from the 701 included the use of core memory instead of Williams tubes and the addi0on of three index registers. To support these new features, the instruc0ons were expanded to use the full 36-­‐bit word. The new instruc0on set, which was not compa0ble with the 701, became the base for the "scien0fic architecture" subclass of the IBM 700/7000 series computers. History (Courtesy of Wikipedia) •  The 704 could execute up to 4,000 opera0ons per second[1] and IBM sold 123 type 704 systems between 1955 and 1960. •  The programming languages FORTRAN[3] and LISP[4] were first developed for the 704. MUSIC, the first computer music program, was developed on the IBM 704 by Max Mathews. In 1962 physicist John Larry Kelly, Jr created one of the most famous moments in the history of Bell Labs by using an IBM 704 c o m p u t e r t o s y n t h e s i z e s p e e c h . K e l l y ' s v o i c e r e c o r d e r synthesizer vocoder recreated the song Daisy Bell, with musical accompaniment from Max Mathews. Author Arthur C. Clarke was coincidentally visi0ng friend and colleague John Pierce at the Bell Labs Murray Hill facility at the 0me of this speech synthesis demonstra0on, and Clarke was so impressed that he used it in the climac0c scene of his novel and screenplay for 2001: A Space Odyssey,[5] where the HAL 9000 computer sings the same song.[6][contradictory] Achievement(Landmarks? Milestones? ~~~~~~~ ) • 
• 
Edward O. Thorp, a math instructor at MIT, used the IBM 704 as a research tool to inves0gate the probabili0es of winning while developing his blackjack gaming theory.[7][8] He used FORTRAN to formulate the equa0ons of his research model. The IBM 704 was used as the official tracker for the Smithsonian Astrophysical Observatory Opera0on Moonwatch in the fall of 1957. See The M.I.T. Computa0on Center and Opera0on Moonwatch. IBM provided four staff scien0sts to aid Smithsonian Astrophysical Observatory scien0sts and mathema0cians in the calcula0on of satellite orbits: Dr. Giampiero Rossoni, Dr. John Greenstadt, Thomas Apple and Richard Hatch. Early Years (when and where current programming languages paqern came from •  hqps://www.youtube.com/watch?v=fRhLP9WKESg Statement Format •  FORTRAN before 90 requires a fixed format PROGRAM MAIN
C COMMENTS ARE ALLOWED IF A C IS PLACED IN COLUMN
DIMENSION X(10)
READ(5,*) (X(I),I=1,10)
WRITE(6,1000) X
1000 FORMAT(1X, THIS IS A VERY LONG LINE OF TEXT TO SHOW HOW TO CONTINUE
*
THE STATEMENT TO A SECOND LINE ,/,10F12.4)
1-­‐5 6 Label 7-­‐72 Statements Any character: con;nua;on line •  Based on the punch card in use when Fortran was created #1
73-­‐80 Op;onal Line #s Statement Format •  IBM punch card Statement Format • 
FORTRAN fixed format –  C in column 1 indicates that line is a comment –  columns 1-­‐5 are reserved for statement labels •  statement labels are not required unless the statement is the target of a goto •  labels are numeric values only –  column 6 is the con0nua0on flag •  any character in column 6, other than space or 0 , indicates that this line is a con0nua0on of the previous line •  there is usually a limit of 19 on the number of con0nua0ons –  columns 7-­‐72 are contain Fortran statements –  columns 73-­‐80 is for sequence informa0on •  only of any use when using punch cards Fortran Literals INTEGER A
A = 34
REAL A(20)
A(1) = 31.4159E-1
ITERM = -10.3
COMPLEX Z
Z = (10,-10.5)
REAL_PART = REAL(Z)
AIMAG_PART = AIMAG(Z)
Z = CMPLX(REAL_PART * 2,AIMAG_PART)
Fortran Literals(the words we can use ?~~~~~) •  Literals are constants that appear in a Fortran program •  Number –  integers -­‐ 1, -­‐34 –  real -­‐ 1.0, 4.3E10, 5.1D-­‐5 –  complex – (5.2,.8) •  Other –  logical -­‐ .true., .false. –  character – 0tle line •  Obsolete but s0ll lurking in code –  Hollerith – 4Habcd, 8Habcdef Code Genera0on FORTRAN Assembler FORTRAN Compiler FORTRAN Program Source Code Make Changes in Source Code Link with Libraries Object Code Test & Debug Program Executable File Executable Code Libraries Execute Program Hey, tell me a liqle about FORTRAN versions • 
~~~~~
One of the oldest computer languages –  created by John Backus and released in 1957 –  designed for scien0fic and engineering computa0ons •  Version history – 
– 
– 
– 
– 
– 
– 
– 
FORTRAN 1957 FORTRAN II FORTRAN IV FORTRAN 66 (released as ANSI standard in 1966) FORTRAN 77 (ANSI standard in 1977) FORTRAN 90 (ANSI standard in 1990) FORTRAN 95 (ANSI standard version) FORTRAN 2003 (ANSI standard version) •  Many different dialects produced by computer vendors (Digital VAX Fortran, now Intel Fortran) •  Large majority of exis0ng engineering sovware is coded in FORTRAN (various versions) A Sample of Common Program Organiza0on program circle real r, area c This program reads a real number r and prints c the area of a circle with radius r. write (*,*) 'Give radius r:' read (*,*) r area = 3.14159*r*r write (*,*) 'Area = ', area stop end program name declara;ons statements stop end Structure of a Fortran Program •  Fortran consists of program units –  program –  func0on –  subrou0ne –  block data •  The program unit contains the main code and the point where execu;on starts (Recall Similarity with MIPS? ~~~ ) –  in Fortran 77 a program begins with the program statement –  earlier versions of Fortran did not have a program statement unless a vendor dialect provided one –  the end statement terminates the program unit –  a program unit may contain internal sub-­‐programs •  internal func0ons •  internal subrou0nes Fortran Subrou0ne SUBROUTINE MULT(A,B,C)
C = A * B
RETURN
END
CALL MULT(5.0,X,VALUE)
• 
• 
• 
The subrou0ne unit contains Fortran code that can be called from other Fortran code a subrou0ne begins with a subroutine statement –  contains a name for the subrou0ne –  a list of formal arguments subrou0nes may be internal or external –  an internal subrou0ne is included in the code of program unit and is only callable by the program –  an external subrou0ne is created outside of a program unit and is callable from everywhere Fortran Func0on (MIPS Label?~~~) REAL FUNCTION MULT(A,B)
MULT = A * B
RETURN
END
• 
• 
• 
VALUE = MULT(5.0,X)
• 
The func0on unit contains Fortran code that can be called from other Fortran code It differs from a subrou0ne in that it returns a value a subrou0ne begins with a function statement –  contains a name for the func0on –  a list of formal arguments –  specifies a return type func0ons may be internal or external –  an internal func0on is included in the code of program unit and is only callable by the program –  an external func0on is created outside of a program unit and is callable from everywhere Fortran Variables and Subrou0nes •  All arguments to a Fortran subrou0ne are passed by reference –  the subrou0ne receives the address of the variable –  any changes made by the subrou0ne are seen by the caller –  most other languages pass by value (the subrou0ne receives a copy) –  passing an array as an argument with just the name will pass the address of the first element •  On entry to a subrou0ne its local variables are not guaranteed to have any known value –  the save statement introduced in 77 will ensure that a variable will have on entry the value that it had on its last exit from the subrou0ne Fortran Expressions (MIPS R-­‐type?~~~) •  The simplest non-­‐constant expressions are of the form operand operator operand
•  The simplest non-­‐constant expressions are of the form x + y
•  The result of an expression is itself an operand, hence we can nest expressions together like x + 2 * y
•  This raises the ques0on of precedence: Does the last expression mean x + (2*y) or (x+2)*y? The precedence of arithme0c operators in Fortran 77 are (from highest to lowest): ** {exponen;a;on} *,/ {mul;plica;on, division} +,-­‐ {addi;on, subtrac;on} Fortran Expressions •  Expressions are the heart of Fortran (Formula Translator) •  There are two types of expressions –  numeric •  2 * 3.14159 * RADIUS**2 •  SIN(PI) –  logical •  IBOOL = .TRUE. •  I .EQ. 10 .AND. ISTOP –  note: LOGICAL ISTOP Fortran Numerical Operators •  The numerical operators –  ** (exponen0a0on) –  * / •  unary + -­‐ “As an extension, GNU Fortran allows unary plus and unary minus operators to appear as the second operand of binary arithme0c operators without the need for parenthesis X = Y * -­‐ Z “ –  binary + -­‐ •  Parentheses are used to alter the order of evalua0on •  For binary operators, if the types do not match an implicit conversion is performed to the most general type •  integer -­‐> real -­‐> double precision •  anything -­‐> complex Fortran Numerical Operators •  WARNING: division of an integer by an integer will produce a truncated result •  5 / 2 => 2 not 2.5 •  FLOAT(5)/2 => 2.5 •  The type-­‐conversion intrinsic func0ons can be used to get the desired results Fortran Variable (MIPS .data direc0ves? ~~~) •  Variables represent the memory of the program •  Fortran variables –  Fortran IV numbers and leqers, at least 6 characters –  Fortran 77 numbers and leqers and _ , at least 16 characters –  must start with a leqer •  Up through 77, spaces in a Fortran program are ignored –  IVALUE and I VAL UE are the same –  using strange spacing, while acceptable, is bad prac0ce •  Fortran variables are typed •  Fortran is case insensi0ve –  ivar is the same as IVAR or IvAr Ques;ons: is it a local or global variable ??? ~~~~~~~ Block Data(Well, it’s more like a .data direc0ve ~~~~~~~ ) The data statement is another way to input data that are known at the 0me when the program is wriqen. It is similar to the assignment statement. The syntax is: data list-­‐of-­‐variables/ list-­‐of-­‐values/, ... where the three dots means that this paqern can be repeated. Here is an example: data m/10/, n/20/, x/2.5/, y/2.5/ We could also have wriqen this data m,n/10,20/, x,y/2*2.5/ We could have accomplished the same thing by the assignments m = 10 n = 20 x = 2.5 y = 2.5 The data statement is more compact and therefore oven more convenient. No0ce especially the shorthand nota0on for assigning iden0cal values repeatedly. The data statement is performed only once, right before the execu0on of the program starts. For this reason, the data statement is mainly used in the main program and not in subrou0nes. Ini0aliza0on of Data Statement
(Courtesy of Stanford Univ.) The data statement can also be used to ini0alize arrays (vectors, matrices). This example shows how to make sure a matrix is all zeros when the program starts: real A(10,20) data A/ 200 * 0.0/ •  Some compilers will automa0cally ini0alize arrays like this but not all, so if you rely on array elements to be zero it is a good idea to follow this example. Of course you can ini0alize arrays to other values than zero. You may even ini0alize individual elements: data A(1,1)/ 12.5/, A(2,1)/ -­‐33.3/, A(2,2)/ 1.0/ Or you can list all the elements for small arrays like this: integer v(5) real B(2,2) data v/10,20,30,40,50/, B/1.0,-­‐3.7,4.3,0.0/ The values for two-­‐dimensional arrays will be assigned in column-­‐first order as usual. • 
Common Blocks(Courtesy of Wiki) •  Fortran 77 has no global variables, i.e. variables that are shared among several program units (subrou0nes). The only way to pass informa0on between subrou0nes we have seen so far is to use the subrou0ne parameter list. Some0mes this is inconvenient, e.g., when many subrou0nes share a large set of parameters. In such cases one can use a common block. This is a way to specify that certain variables should be shared among certain subrou0nes. But in general, the use of common blocks should be minimized. Fortran Common Blocks •  Two types of common –  blank common – unnamed –  named common •  Most systems do not allow blank common to be ini0alized •  Blank common can some0mes be used to allocate unused memory (depends on OS) COMMON A,B(10),C
COMMON/SET1/A,B(50,5),C
Problem of Common Blocks •  Problems –  each program unit that declares access to a common block defines it s own view •  type of each variable in the block •  size of each array in the block –  when views between units differ there can be problems – some linkers will warn of size differences PROGRAM TEST
COMMON/A/A,B(10),C
END
SUBROUTINE DOIT
COMMON/A/I,J(5),K(20)
END
OK, Block Data The data statement cannot be used for variables contained in a common block. There is a special "subrou0ne" for this purpose, called block data. It is not really a subrou0ne, but it looks a bit similar because it is given as a separate program unit. Here is an example: BLOCK DATA
block data COMMON/MEM/A,B
integer nmax DATA A,B/10.0,-3.14/
parameter (nmax=20) real v(nmax), alpha, beta END
common /vector/v,alpha,beta data v/20*100.0/, alpha/3.14/, beta/2.71/ end Just as the data statement, block data is executed once before the execu0on of the main program starts. The posi0on of the block data "subrou0ne" in the source code is irrelevant (as long as it is not nested inside the main program or a subprogram). What if data is declared without a type? •  A feature of Fortran – implicit typing –  when a variable appears that has not been declared previously it is created (at compile 0me) –  it is assigned a type based on the first character of the name •  A-­‐H,O-­‐Z is type REAL •  I-­‐N is type INTEGER –  a typo can cause the crea0on of a new variable – not an error •  Star0ng with 77 the implicit statement was added –  allowed changing the first leqer assignments –  most 77 compilers include the implicit none statement that requires that all variables be explicitly typed – prevents the typo problem •  It is good prac0ce to use implicit none
Type Conversion –  When different data types occur in the same expression, type conversion has to take place, either explicitly or implicitly. Fortran will do some type conversion implicitly. For example, real x
x = x + 1
–  will convert the integer one to the real number one, and has the desired effect of incremen0ng x by one. However, in more complicated expressions, it is good programming prac0ce to force the necessary type conversions explicitly. For numbers, the following func0ons are available: int
real
dble
ichar
char
Fortran Variable Typing •  All Fortran variables are typed –  INTEGER –  REAL –  DOUBLE PRECISION –  COMPLEX –  LOGICAL –  CHARACTER (77+) Type Conver0ng Example How to mul0ply two real variables x and y using double precision and store the result in the double precision variable w: w = dble(x) * dble(y)
Note that this is different from w = dble( x*y )
Fortran Variable Typing •  The types presented earlier are the default types •  The range of both INTEGER and REAL are dependent on the computer architecture –  one computer may have a 32 bit integer while another may use 16 bit as its default •  An aqempt to deal with this lead to types such as –  REAL*8, INTEGER*4 –  the number aver the * indicates the number of bytes used –  most computers have 8 bit bytes –  not every architecture will have every combina0on –  not a prac0cal problem in an Intel world –  but knowledge of the architecture of the system where a legacy Fortran program was developed is needed to convert to Intel Fortran Variable Typing •  Fortran 90+ uses a different method to deal with number ranges that is architecture independent (we will cover this issue in later lectures ) . Fortran Variable Typing •  The CHARACTER type was introduced in 77 •  The * nota0on is used to specify the maximum number of characters the variable can hold CHARACTER*20 TITLE
•  Before 77 the Hollerith nota0on was used –  common in older Fortran code, even in some 77 code –  normally placed characters into INTEGER arrays –  required knowledge of byte length of the variable –  portability problem INTEGER*4 TITLE(5)
DATA TITLE/4Habcd,4Hefgh,…/
Fortran Arrays •  Many scien0fic computa0ons use vectors and matrices. The data type Fortran uses for represen0ng such objects is the array. A one-­‐dimensional array corresponds to a vector, while a two-­‐dimensional array corresponds to a matrix. To fully understand how this works in Fortran 77, you will have to know not only the syntax for usage, but also how these objects are stored in memory in Fortran 77. •  The type of an array element can be any of the basic data types. Examples: integer i(10) logical aa(0:1) double precision x(100) •  Each element of an array can be thought of as a separate variable. You reference the i'th element of array a by a(i). Here is a code segment that stores the 10 first square numbers in the array sq: One-­‐dimensional arrays •  The simplest array is the one-­‐dimensional array, which is just a sequence of elements stored consecu0vely in memory. For example, the declara0on real a(20) •  declares a as a real array of length 20. That is, a consists of 20 real numbers stored con0guously in memory. By conven0on, Fortran arrays are indexed from 1 and up. Thus the first number in the array is denoted by a(1) and the last by a(20). However, you may define an arbitrary index range for your arrays using the following syntax: real b(0:19), weird(-­‐162:237) •  Here, b is exactly similar to a from the previous example, except the index runs from 0 through 19. weird is an array of length 237-­‐(-­‐162)+1 = 400. Two-­‐dimensional arrays • 
• 
• 
• 
• 
• 
Matrices are very important in linear algebra. Matrices are usually represented by two-­‐
dimensional arrays. For example, the declara0on real A(3,5) defines a two-­‐dimensional array of 3*5=15 real numbers. It is useful to think of the first index as the row index, and the second as the column index. Hence we get the 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 may also have indices in an arbitrary defined range. The general syntax for declara0ons is: name (low_index1 : hi_index1, low_index2 : hi_index2) The total size of the array is then size = (hi_index1-­‐low_index1+1)*(hi_index2-­‐low_index2+1) Two-­‐dimensional arrays example •  It is quite common in Fortran to declare arrays that are larger than the matrix we want to store. (This is because Fortran does not have dynamic storage alloca0on.) This is perfectly legal. Example: real A(3,5) integer i,j c We will only use the upper 3 by 3 part of this array. do 20 j = 1, 3 do 10 i = 1, 3 a(i,j) = real(i)/real(j) 10 con0nue 20 con0nue •  The elements in the submatrix A(1:3,4:5) are undefined. Do not assume these elements are ini0alized to zero by the compiler (some compilers will do this, but not all). Storage of Mul0ple Dimensional Arrays • 
Fortran stores higher dimensional arrays as a con0guous sequence of elements. It is important to know that 2-­‐dimensional arrays are stored by column. So in the 3 by 5 matrix, array element (1,2) will follow element (3,1). Then follows the rest of the second column, thereaver the third column, and so on. • 
Consider again the example where we only use the upper 3 by 3 submatrix of the 3 by 5 array A(3,5). The 9 interes0ng elements will then be stored in the first nine memory loca0ons, while the last six are not used. This works out neatly because the leading dimension is the same for both the array and the matrix we store in the array. However, frequently the leading dimension of the array will be larger than the first dimension of the matrix. Then the matrix will not be stored con0guously in memory, even if the array is con0guous. For example, suppose the declara0on was A(5,3) instead. Then there would be two "unused" memory cells between the end of one column and the beginning of the next column (again we are assuming the matrix is 3 by 3). Why? ~~~~~~~ •  This may seem complicated, but actually it is quite simple when you get used to it. If you are in doubt, it can be useful to look at how the address of an array element is computed. Each array will have some memory address assigned to the beginning of the array, that is element (1,1). The address of element (i,j) is then given by addr[A(i,j)] = addr[A(1,1)] + (j-­‐1)*lda + (i-­‐1) •  where lda is the leading (i.e. row) dimension of A. Note that lda is in general different from the actual matrix dimension. Many Fortran errors are caused by this, so it is very important you understand the dis0nc0on! Array Storage program order
implicit none
integer i,j
integer a(5,5), b(25)
equivalence (a(1,1),b(1))
do i=1,5
do j=1,5
a(i,j) = i*100 + j
enddo
enddo
write(6,9000) ((a(i,j),j=1,5),i=1,5)
write(6,9010) b
write(6,9020) a
9000 format(/,'a(i,j): ',/,(5(1x,i4.4)))
9010 format(/,'b:',/,(15(1x,i4.4)))
9020 format(/,'a:',/,(5(1x,i4.4)))
end
a(i,j):
0101 0102
0201 0202
0301 0302
0401 0402
0501 0502
0103
0203
0303
0403
0503
0104
0204
0304
0404
0504
0105
0205
0305
0405
0505
b:
0101 0201 0301 0401 0501 0102 0202 0302 0402 0502 0103 0203 0303 0403 0503
0104 0204 0304 0404 0504 0105 0205 0305 0405 0505
a:
0101
0102
0103
0104
0105
0201
0202
0203
0204
0205
0301
0302
0303
0304
0305
0401
0402
0403
0404
0405
0501
0502
0503
0504
0505
Dimension Statement •  There is an alternate way to declare arrays in Fortran 77. The statements real A, x dimension x(50) dimension A(10,20) are equivalent to real A(10,20), x(50) This dimension statement is considered old-­‐fashioned style today. INTEGER B
DIMENSION B(0:10,0:10)
OK, one more 0p ~~~ There are nine kinds of specifica0on statements: • 
• 
• 
• 
• 
• 
• 
• 
• 
DIMENSION EQUIVALENCE COMMON INTEGER, REAL, DOUBLE PRECISION, COMPLEX, LOGICAL, and CHARACTER type-­‐
statements IMPLICIT PARAMETER EXTERNAL INTRINSIC SAVE OK, what is Equivalence ? •  An EQUIVALENCE statement is used to specify the sharing of storage units by two or more en00es in a program unit. This causes associa0on of the en00es that share the storage units. •  If the equivalenced en00es are of different data types, the EQUIVALENCE statement does not cause type conversion or imply mathema0cal equivalence. If a variable and an array are equivalenced, the variable does not have array proper0es and the array does not have the proper0es of a variable. INTEGER A(100)
EQUIVALENCE (INCREMENT,A(4))
–  Takes advantage of no index checking COMMON A(10000)
INTEGER IA(1)
EQUIVALENCE (IA(1),A(1))
So in fact, I am checking upon another exis;ng data? ~~~ That’s correct ! ~~~ Fortran Parameter The PARAMETER statement is used to give a constant a symbolic name. The form of a PARAMETER statement is: PARAMETER (p=e [,p=e]...) PARAMETER (MAX=20)
•  where: p is a symbolic name e is a constant expression If the symbolic name p is of type integer, real, double precision, or complex, the corresponding expression e must be an arithme0c constant expression. If the symbolic name p is of type character or logical, the corresponding expression e must be a character constant expression or a logical constant expression, respec0vely. • 
• 
• 
Each p is the symbolic name of a constant that becomes defined with the value determined from the expression e that appears on the right of the equals, in accordance with the rules for assignment statements PARAMETER (MAX=1000)
INTEGER A(MAX)
Fortran Assignment •  The simple assignment statement stores the result of computa0ons into a variable DIMENSION A(10,10)
…
A(I,10) = 2.0 * PI * R**2
INTEGER A
A = A + 1
Fortran Branching(MIPS Branching ~~~ ) •  Fortran includes a GOTO statement •  In modern languages this is considered very IF (I .EQ. 0) GO TO 100
bad –  its use was essen0al in Fortran 66 its predecessors –  Fortran 77 introduced control statements that lessened the need for the GOTO A = 4.0 * AINIT
GOTO 200
100 B = 52.0
…
200 C = B * A
Fortran Branching •  The Fortran GOTO always branched to a Fortran statement that contained a label in columns 1-­‐5 •  The labels varied from 1 to 99999 •  Varia0ons of the go to statement are –  assigned goto –  computed goto •  Spaces are ignored in Fortran code before 90 –  GOTO and GO TO are equivalent •  Excessive use of the goto (required in 66 and before) leads to difficult to understand code Fortran Branching •  Assigned goto ASSIGN 100 TO TARGET
…
GOTO TARGET
…
100 CONTINUE
Fortran Branching •  Computed goto •  Operates much like a case or switch statement in other languages GOTO (100,200,300,400),IGO
…
100 CONTINUE
…
GOTO 500
200 CONTINUE
…
GOTO 500
…
500 CONTINUE
Fortran IF •  The IF statement is used to perform logical decisions •  The oldest form is the 3-­‐way if (also called arithme0c if) •  The logical if appeared in Fortran IV/66 •  The more modern if-­‐then-­‐else appeared in Fortran 77 Fortran 3-­‐way If •  The 3-­‐way if statement tested a numerical value against zero •  It branched to one of three labels depending on the result 10
20
30
100
IF (RADIUS) 10,20,30
CONTINUE
…
GOTO 100
CONTINUE
…
GOTO 100
CONTINUE
…
GOTO 100
CONTINUE
IF (ABS(RADIUS-EPS)) 10,10,20
10 CONTINUE
…
GOTO 100
20 CONTINUE
…
GOTO 100
100 CONTINUE
Fortran Logical If •  The logical if statement performed a test using the logical operators –  .EQ., .NE., .LT., .LE., .GT., .GE. –  .AND., .OR., .NOT. •  If result is true then a single statement is executed IF (ISTART .EQ. 50) GOTO 100
…
100 CONTINUE
IF (IMODE .EQ. 2) A = SQRT(CVALUE)
…
LOGICAL QUICK
QUICK = .TRUE.
IF (QUICK) STEP=0.5
IF (.NOT. QUICK) STEP = 0.01
Fortran Logical If LOGICAL QUICK
QUICK = .TRUE.
IF (QUICK) STEP=0.5
IF (.NOT. QUICK) STEP = 0.01
…
IF (QUICK .AND. (ABS(XVALUE – EPS) .LT. 0.005)) GOTO 1000
Fortran Modern If •  Fortran 77 introduced the modern if statement (so-­‐called structured programming) •  The test operated the same as the logical if •  Greatly reduced the need for using the goto statement •  Includes –  then clause –  else clause –  else if clause Fortran Modern If •  This form eliminates the goto statements from the previous example LOGICAL QUICK
QUICK = .TRUE.
IF (QUICK) THEN
STEP=0.5
ELSE
STEP = 0.01
ENDIF
…
IF (QUICK .AND. (ABS(XVALUE – EPS) .LT. 0.005)) THEN
…
END IF
Fortran Modern If •  This form reduces the need for the computed goto IF (MODE .EQ. 0) THEN
…
ELSE IF (MODE .EQ. 1) THEN
…
ELSEIF (MODE .EQ. 2) THEN
…
ELSE
…
END IF
Fortran Looping •  The DO statement is the mechanism for looping in Fortran •  The do loop is the only official looping mechanism in Fortran through 77 DO 100 I=1,10,2
…
100 CONTINUE
•  Here I is the control variable –  it is normally an integer but can be real –  1 is the start value –  10 is the end value –  2 is the increment value –  everything to the 100 label is part of the loop Fortran Looping •  The labeled statement can be any statement not just con0nue •  Loop may be nested –  nested loops can share the same label – very bad form DO 100 I=1,10,2
DO 100 J=1,5,1
…
100 A(I,J) = VALUE
DO 200 I=1,10,2
DO 100 J=1,5,1
…
A(I,J) = VALUE
100 CONTINUE
200 CONTINUE
Fortran Looping •  Before Fortran 77 a do loop would always execute at least once – despite the parameters •  The increment may be nega0ve, if not specified it is assumed to be 1 Fortran Looping •  WARNING: Through Fortran 77 there is an extended do loop –  can jump out of loop to code outside the loop –  that code can jump back into the loop –  valid as long as code does not modify the control variable –  no need to ever use it – use a subrou0ne instead DO 100 I=1,100
…
GOTO 1000
…
99 CONTINUE
…
100 CONTINUE
…
1000 CONTINUE
…
GOTO 99
DO 100 I=1,100
…
CALL XYZ
…
100 CONTINUE
…
OK, jump back to Do, I See ~~~ Fortran Looping •  Fortran 77 introduced a form of the do loop that does not require labels DO I=1,100
DO J=1,50
A(I,J) = I*J
END DO
ENDDO
•  The indented spacing shown is not required DO I=1,100
…
ENDDO
Fortran Looping •  A variant of Fortran 77 known as MIL-­‐STD 1753 introduced a new loop construct – the while loop •  While not part of the Fortran standard it is available in almost all Fortran 77 compilers DO WHILE (I .LT. 1000)
…
ENDDO
•  This form is an infinite loop and would require an addi0onal test in the loop to exit DO WHILE (.TRUE.)
…
END DO
Fortran Looping •  Finally, there is a form of the do loop called the implied do loop •  It is used on READ, WRITE, and DATA statements READ(5,8000) (A(I),I=1,10)
WRITE(6,8000) ((A(I,J),I=1,10),J=1,10)
DATA ((IX(I,J),I=1,10),J=1,10)/1,2,3…/
Fortran I/O Statements •  Fortran contains an extensive input/output capability •  The relevant statements are – 
– 
– 
– 
– 
– 
– 
– 
– 
READ WRITE OPEN CLOSE INQUIRE REWIND BACKSPACE ENDFILE FORMAT •  Fortran I/O is based on the concept of a unit number –  5 is generally input – stdin on Unix –  6 is usually output – stdout on Unix –  other unit numbers can be created as needed Fortran I/O Statements •  Management of unit numbers was not specified in any system independent way before Fortran 77 –  older programs will just use a unit without any declara0on – the linkage to a file was performed by the OS –  the following usage is common PROGRAM MAIN(INPUT,OUTPUT,TAPE5=INPUT,TAPE6=OUTPUT)
–  this is non-­‐standard and can only be used as a guide when conver0ng Fortran program to a modern OS (Linux, Unix, or Windows) Fortran I/O Statements •  There are two types of I/O in Fortran –  formaqed –  unformaqed or binary •  There are two modes of opera0on –  sequen0al –  random •  Formaqed I/O uses a format statement to prepare the data for output or interpret for input •  Unformaqed I/O does not use a format statement –  the form of the data is generally system dependent –  usually faster and is generally used to store intermediate results Fortran I/O Statements •  The FORMAT statement is the heart of the Fortran formaqed I/O system •  The format statement instructs the computer on the details of both input and output –  size of the field to use for the value –  number of decimal places •  The format is iden0fied by a statement label WRITE(6,9000) A,B,C,D,E
9000 FORMAT(1X,4F8.5,2x,E14.6,//)
•  A format can be used any number of 0mes •  The label number must not conflict with goto labels Fortran I/O Statements •  The Fortran I/O statements have a common form with a common set of parameters stmt(UNIT=n,FMT=label,IOSTAT=int-variable,ERR=label,END=label) list
•  The UNIT and FMT keywords can be omiqed, in which case the unit and format are the first two parameters stmt(n,label,IOSTAT=int-variable,ERR=label,END=label) list
•  The other parameters are all op0onal •  The list is the list of variables or expressions to be converted to or from •  Fortran IV/66 only uses a unit number and a format label, some implementa0ons allow END
stmt(n,label) list
Fortran I/O Statements •  The UNIT keyword is used to specify the device on which to perform the I/O –  the keyword may be omiqed – the unit must be the first parameter •  The FMT keyword is used to specify a format label that will be used to control the I/O –  the keyword may be omiqed – the format label must be the second parameter –  an unformaqed I/O opera0on does not use a format –  a character string may be used instead (77 only) •  The NML keyword is used to specify a namelist group –  NML and FMT are mutually exclusive Fortran I/O Statements •  The IOSTAT keyword is used to specify an integer variable that will, upon comple0on, contain a value that indicates how the I/O completed –  = 0 – there was no error or EOF condi0on, OK –  > 0 – the value is the error that occurred, this is implementa0on dependent –  < 0 – and EOF, end of file, was encountered •  The ERR keyword is used to specify a statement label that will be jumped to if an error occurs –  of specified, IOSTAT will contain the error code •  The END keyword is used to specify a statement label that will be jumped to if an EOF condi0on exists •  The END and ERR keywords are not required, the programmer can just test the value of IOSTAT
•  If IOSTAT or the END/ERR keywords are not used the Fortran library will invoke a standard error response – usually terminate the program Fortran I/O List •  The I/O list is the list of variables or expressions that are to be processed by an I/O statement •  Formaqed I/O will perform conversions between internal binary format and external character format •  Unformaqed I/O does not conversion •  There are three forms of formaqed I/O –  the standard form –  list directed –  namelist directed An Example This piece of Fortran code x = 0.025 write(*,100) 'x=', x 100 format (A,F) write(*,110) 'x=', x 110 format (A,F5.3) write(*,120) 'x=', x 120 format (A,E) write(*,130) 'x=', x 130 format (A,E8.1) • 
•  produces the following output when we run it: x=0.0250000 x=0.025 x=0.2500000E-­‐01 x=0.3E-­‐01 Note how blanks are automa0cally padded on the lev and that the default field width for real numbers is usually 14. We see that Fortran 77 follows the rounding rule that digits 0-­‐4 are rounded downwards while 5-­‐9 are rounded upwards. In this example each write statement used a different format statement. But it is perfectly fine to use the same format statement for many different write statements. In fact, this is one of the main advantages of using format statements. This feature is handy when you print tables for instance, and want each row to have the same format. •  ACCESS Other I/O Features –  SEQUENTIAL – process each record in order (default for formaqed io) –  DIRECT – access the file randomly (access record by number REC=) •  BLANK – determines how blanks are processed by a format –  NULL – blanks are ignored – all blank field is zero –  ZERO – blanks are treated as zeros –  al BZ and BN format specifiers can be used •  STATUS – 
– 
– 
– 
– 
OLD – file must currently exist NEW – file cannot currently exist, it is created SCRATCH – an unnamed file that is created then destroyed on close REPLACE – if file exists then delete and re-­‐create before opening UNKNOWN – if file does not exist create it otherwise open it Other I/O Features •  The CLOSE statement will close a unit •  Keywords include –  UNIT – unit to close –  STATUS – KEEP | DELETE –  ERR – label –  IOSTAT – integer variable CLOSE(7)
CLOSE(7,STATUS= DELETE )
Other I/O Features •  The BACKSPACE statement will posi0on a sequen0al record back to the beginning of the previous record –  re-­‐read a line •  The ENDFILE statement will write an end of file marker then posi0on a sequen0al file aver it –  most useful with magne0c tape files •  The INQUIRE statement will retrieve informa0on about a file or logical unit •  The REWIND statement will posi0on a sequen0al file back to the beginning of the file Sub Programs(Courtesy of Wiki) There are two types of Fortran sub-­‐programs •  the subrou0ne •  the func0on ~~~~~ We have seen that ~~~ ~~~~~ Yes you have ~~~ • 
• 
• 
• 
Func0ons return a value in an expression Subrou0nes are called as a stand-­‐alone statement Sub-­‐programs communicate with the caller using arguments Common blocks are also used –  reduce the flexibility of the rou0ne –  faster, lower overhead Sub Programs •  When a sub-­‐program is declared, formal or dummy arguments are specified SUBROUTINE SUB1(A,B,I,J)
REAL J
DIMENSION A(5,5)
INTEGER B
•  Func0ons return a value REAL FUNCTION SINE(ANGLE)
…
SINE = …
RETURN
END
Sub Programs •  The formal arguments of a sub-­‐program define the variables within that sub-­‐program •  When the sub-­‐program is called, the variables used in the call are the actual arguments •  The actual arguments are expected to match the formal arguments •  Fortran before 90 does not check type •  For a func0on, the return value is placed in a variable of the same name before return. Sub Programs •  Arguments in Fortran are passed by reference –  the address of the memory loca0on is given to the sub-­‐program –  changes made to the formal variable are reflected in the actual variable –  most other computer languages pass by value where a copy is made for use by the sub-­‐program •  For array variables –  supplying only the name will pass the address of the start of the array –  with indices supplied, the address of that element is passed –  missing indices are assumed to be 1 DIMENSION A(5,5)
CALL SUB(A,A(3,2))
SUBROUTINE SUB(X,Y)
DIMENSION X(5,5)
REAL Y
…
END
Sub Programs •  When arrays are used –  the shape of the array must match in both the caller and the called units –  the shape is the number of dimensions and extent of each dimension, 5x5 –  a mis-­‐match will generally result in incorrect calcula0ons and results DIMENSION A(5,5)
CALL SUB(A)
SUBROUTINE SUB(X)
DIMENSION X(5,5)
…
END
Sub Programs •  A common sight for formal array declara0ons is the use of 1 as a dimension extent •  This works only for the right-­‐most index •  This works because the mapping from mul0-­‐
dimensional to one-­‐dimensional form DIMENSION A(5,5)
CALL SUB(A)
SUBROUTINE SUB(X)
DIMENSION X(5,1)
…
END
Sub Programs •  Arguments can be used to define the shape of the array INTEGER A(5,5)
…
CALL SUB(A,5,5)
…
END
SUBROUTINE SUB
(J,IROW,ICOL)
DIMENSION J(IROW,ICOL)
…
END
•  This only works for formal arguments •  Frequently used with the PARAMETER statement Sub Programs •  A program using common blocks to communicate •  The INCLUDE statement is used to ensure that all the parts of the program use the same defini0ons •  A makefile is shown –  it checks the current state of all the source files –  if common.f is changed it will ensure that the other files that reference it are re-­‐compile to reflect changes –  sample is the first target and therefore the default Sub Programs PART1.F
program sample
include 'common.f
write(*,*) 'a=',a,', b=',b,', c=',c
call modify
write(*,*) 'a=',a,', b=',b,', c=',c
end
COMMON.F
common/test/a,b,c
integer a,b,c
PART2.F
block data
include 'common.f
data a,b,c/7,42,70/
end
PART3.F
subroutine modify
include 'common.f
integer total
total = a + b + c
write(*,*) "Total=",total
a = a / 2
b = b / 2
c = c / 2
return
end
MAKEFILE
sample: part1.o part2.o part3.o
g77 -o sample part1.o part2.o part3.o
part1.o: part1.f common.f
g77 -c part1.f
part2.o: part2.f common.f
g77 -c part2.f
part3.o: part3.f common.f
g77 -c part3.f
Statement Func0ons •  The statement func0on is a special case of the func0on It is defined and used in the calling program …
F(X,Y) = X**2 + Y
…
A = 3.245 * F(4.3,B) - C
…
END
•  It is a macro for a simple computa0on It is defined in the declara0ons It has been removed as of Fortran 95 Miscellaneous Statements •  There are several other Fortran statements –  RETURN will cause a sub program to return to the caller at that point – the END statement contains an implied RETURN
–  a number on a RETURN statement indicates that an alternate return be taken –  STOP will cause a program to terminate immediately – a number may be included to indicate where the stop occurred, STOP 2
–  PAUSE will cause the program to stop with a short message – the message is the number on the statement, PAUSE 5 Math Func0ons •  there are also similar func0ons for –  arcsine, arccosine, arctangent (ASIN, ACOS, ATAN) –  hyperbolic sine, cosine, tangent (SINH, COSH, TANH) –  complex conjugate (CONJ) –  base10 logarithms (LOG10) Fortran Subrou0ne Invoca0on •  There are two methods by which a sub program can be called in Fortran –  use the CALL statement for subrou0nes –  as part of a numerical expression for a func0on CALL XX(A,B,C)
…
VALUE = 4.3 * ROOT(X)
…
SUBROUTINE XX(X,Y,Z)
…
END
REAL FUNCTION ROOT(A)
…
END
Fortran Subrou0ne Invoca0on •  The variables on the invoca0on are the actual arguments •  The variables in the declara0on are the formal arguments •  More about sub programs will be covered later Useful links for Fortran Materials A Tutorial from Stanford university: hqp://www.stanford.edu/class/me200c/tutorial_77/10_arrays.html How Fortran Teams Formed?(to find a job ?.......) hqps://www.youtube.com/watch?v=xQtT2sRkOEw 
Download