Post on 15-Jan-2016
11
CS 415: Programming CS 415: Programming LanguagesLanguages
FortranFortran
Aaron BloomfieldAaron Bloomfield
Fall 2005Fall 2005
22
The IBM 704The IBM 704
33
Standard Fortran jokeStandard Fortran joke
““GOD is REAL (unless declared INTEGER)." GOD is REAL (unless declared INTEGER)."
55
Fortran I program controlFortran I program control
IF (arithmetic expression) N1, N2, N3IF (arithmetic expression) N1, N2, N3
DO N1 variable = first_value, last_valueDO N1 variable = first_value, last_value
66
Punch cardsPunch cards
77
Fortran history referenceFortran history reference
http://www.ibiblio.org/pub/languages/fortran/ch1-1.htmlhttp://www.ibiblio.org/pub/languages/fortran/ch1-1.html
88
Installing Fortran on WindowsInstalling Fortran on Windows
We’ll use Fortran 77 for this courseWe’ll use Fortran 77 for this course The compiler has “some” Fortran 90 featuresThe compiler has “some” Fortran 90 features
Install Cygwin: Install Cygwin: http://www.cygwin.com/http://www.cygwin.com/ It’s a Unix-like shell for WindowsIt’s a Unix-like shell for Windows In particular, when you install it:In particular, when you install it:
Install the gcc-g77 package in the Devel sectionInstall the gcc-g77 package in the Devel sectionWe may use Ocaml – if so, then you will need to install the ocaml We may use Ocaml – if so, then you will need to install the ocaml package (also in Devel)package (also in Devel)
This can be done later, tooThis can be done later, too
Install a good editorInstall a good editor I like Emacs: I like Emacs: http://www.gnu.org/software/emacs/emacs.htmlhttp://www.gnu.org/software/emacs/emacs.html
Quite a learning curve, but the best editor out thereQuite a learning curve, but the best editor out thereBinaries at Binaries at http://ftp.gnu.org/pub/gnu/emacs/windows/http://ftp.gnu.org/pub/gnu/emacs/windows/ You can also install and use it as part of CygwinYou can also install and use it as part of CygwinTutorials can be found onlineTutorials can be found online
99
Compiling a Fortran programCompiling a Fortran program
Edit the program using your favorite editorEdit the program using your favorite editor All program code must start on the 7All program code must start on the 7thth column! column!
In Cygwin, change to that directoryIn Cygwin, change to that directory The c drive is at /cygdrive/c, etc.The c drive is at /cygdrive/c, etc.
Enter the command:Enter the command: g77 –ff90 file.fg77 –ff90 file.f
Then run the file:Then run the file: ./a.exe./a.exe
1010
Hello world in FortranHello world in Fortran
PROGRAM HelloWorldPROGRAM HelloWorld
PRINT *,'Hello world!'PRINT *,'Hello world!'
END PROGRAM HelloWorldEND PROGRAM HelloWorld
Column 7Column 1
1111
Fortran syntaxFortran syntax
Lines can only be 72 characters longLines can only be 72 characters long
Comments start with a !Comments start with a !
First 6 columns must be spacesFirst 6 columns must be spaces Unless it’s a commentUnless it’s a comment
No semi-colons after each lineNo semi-colons after each line A newline is a statement terminatorA newline is a statement terminator
1212
Variable declarationVariable declaration
The types are real, integer, etc.The types are real, integer, etc.
real :: x, y, zreal :: x, y, z
integer :: a, b, cinteger :: a, b, c
character :: gcharacter :: g
Always put ‘implicit none’ at the beginningAlways put ‘implicit none’ at the beginning Right after the ‘program’ lineRight after the ‘program’ line Prevents implicit variable declarationPrevents implicit variable declaration
1313
Input and outputInput and output
Output statement:Output statement: print *, "(", tri1x, ", ", tri1y, ")“print *, "(", tri1x, ", ", tri1y, ")“
Input statement:Input statement: read *, tri3xread *, tri3x
There are ways to do nicely formatted outputThere are ways to do nicely formatted output We aren’t going over themWe aren’t going over them
1414
OperatorsOperators
Boolean operators: .and., .or., .not., etc.Boolean operators: .and., .or., .not., etc. Basically the name of the operation in periodsBasically the name of the operation in periods Boolean values are .true. and .false.Boolean values are .true. and .false.
Relational operators: <, >, <=, >=, ==, /=Relational operators: <, >, <=, >=, ==, /=
1515
Built-in functionsBuilt-in functions
sqrt()sqrt()
log()log()
sin()sin()
cos()cos()
exp()exp()
etc.etc.
1616
If statementsIf statements
Forms are (exp is a Boolean expression):Forms are (exp is a Boolean expression):
if (if (exp exp ) then) then ......endifendif
if ( if ( exp exp ) then) then ......elseelse ......endifendif
if ( exp ) thenif ( exp ) then ......else if ( exp ) thenelse if ( exp ) then ......else if ( exp ) thenelse if ( exp ) then ......endifendif
1717
Case statementCase statement
Form is:Form is:
select case ( expr )select case ( expr )
case ( value )case ( value )
......
case ( value )case ( value )
......
case ( value )case ( value )
......
case defaultcase default
......
end caseend case
Where value can be:Where value can be: A single valueA single value
(300:)(300:) A range of valuesA range of values
(200:400)(200:400)
Case default is not Case default is not requiredrequired
1818
LoopingLooping
Form is:Form is:
do i = 1, 10do i = 1, 10
......
end doend do
do i = 1, 10, 2do i = 1, 10, 2
......
end doend do
The first loops from 1 to The first loops from 1 to 1010
The second loops from 1 The second loops from 1 to 10, but odd numbers to 10, but odd numbers onlyonly
1919
Loop controlLoop control
ExitExit Exits the loop, not the programExits the loop, not the program
CycleCycle Similar to next or continue in other languagesSimilar to next or continue in other languages Starts the next iteration of the loopStarts the next iteration of the loop
2020
Demo Demo programprogram
! This program allows the user to input the number of degrees in an angle! This program allows the user to input the number of degrees in an angle! and then computes the cosine, sine, and tangent. It continues until the! and then computes the cosine, sine, and tangent. It continues until the! user inputs "n" or "N".! user inputs "n" or "N". PROGRAM anglePROGRAM angle IMPLICIT noneIMPLICIT none! Type variables.! Type variables. REAL :: cosine, sine, tangent, degreesREAL :: cosine, sine, tangent, degrees REAL :: pi = 3.141592REAL :: pi = 3.141592 CHARACTER :: choiceCHARACTER :: choice DODO! Enter and read the number of degrees in the angle.! Enter and read the number of degrees in the angle. PRINT *, "Enter the number of degrees in the angle."PRINT *, "Enter the number of degrees in the angle." READ *, degreesREAD *, degrees! Convert number of degrees in angle to radians.! Convert number of degrees in angle to radians. degrees = degrees*(pi/180)degrees = degrees*(pi/180)! Use intrinsic functions to compute values.! Use intrinsic functions to compute values. cosine=cos(degrees)cosine=cos(degrees) sine=sin(degrees)sine=sin(degrees) tangent=tan(degrees)tangent=tan(degrees)! Print results.! Print results. PRINT *, "cosine=", cosine, " sine=", sine, " tangent=", tangentPRINT *, "cosine=", cosine, " sine=", sine, " tangent=", tangent! Give user chance to exit program.! Give user chance to exit program. PRINT *PRINT * PRINT *, "Would you like to do this again?"PRINT *, "Would you like to do this again?" PRINT *,"(Press n to exit - any other key to continue.)"PRINT *,"(Press n to exit - any other key to continue.)" READ *, choiceREAD *, choice! Exit loop if the value in choice is N or n.! Exit loop if the value in choice is N or n. IF (choice == "N" .or. choice == "n") EXITIF (choice == "N" .or. choice == "n") EXIT END DOEND DO STOPSTOP END PROGRAM angleEND PROGRAM angle
Computes Computes the sin, the sin, cos, tan, cos, tan, etc.etc.
2121
Demo Demo programprogram
! This program averages a series of numbers input ! This program averages a series of numbers input ! from the keyboard.! from the keyboard. PROGRAM averagePROGRAM average IMPLICIT noneIMPLICIT none! Type variables.! Type variables. REAL :: data, sum, avgREAL :: data, sum, avg INTEGER num, iINTEGER num, i! Prompt for and enter number of numbers to average.! Prompt for and enter number of numbers to average. PRINT *,"Enter the number of numbers to average."PRINT *,"Enter the number of numbers to average." READ *,numREAD *,num sum = 0.0sum = 0.0! Loop goes from 1 to number of values to average.! Loop goes from 1 to number of values to average. DO i = 1, numDO i = 1, num! Prompt for and enter a number.! Prompt for and enter a number. PRINT *,"Enter a value for the number"PRINT *,"Enter a value for the number" READ *,dataREAD *,data! Add number to total.! Add number to total. sum = sum + datasum = sum + data END DOEND DO! Calculate average.! Calculate average. avg = sum/real(num)avg = sum/real(num)! Print results.! Print results. PRINT *,"The average = ",avgPRINT *,"The average = ",avg STOPSTOP ENDEND
Computes Computes the the averageaverage
2222
Demo Demo programprogram
! This program uses a function to find the average of three numbers.! This program uses a function to find the average of three numbers. PROGRAM func_avePROGRAM func_ave! Type variables in main program (a, b, and c are local variables).! Type variables in main program (a, b, and c are local variables). REAL :: a,b,c,averageREAL :: a,b,c,average! Prompt for and get numbers to be averaged.! Prompt for and get numbers to be averaged. PRINT *,"Enter the three numbers to be averaged."PRINT *,"Enter the three numbers to be averaged." READ *, a,b,cREAD *, a,b,c! Invoke function average! Invoke function average PRINT *,"The three numbers to be averaged are ",a,b,cPRINT *,"The three numbers to be averaged are ",a,b,c PRINT *,"The average of the three numbers is ", average(a,b,c)PRINT *,"The average of the three numbers is ", average(a,b,c) STOPSTOP END PROGRAM func_aveEND PROGRAM func_ave! Function average! Function average REAL FUNCTION average(x,y,z)REAL FUNCTION average(x,y,z)! Type variables in function (x, y, and z are local varialbes).! Type variables in function (x, y, and z are local varialbes). REAL :: x,y,zREAL :: x,y,z! Function name contains the average the function calculates and returns.! Function name contains the average the function calculates and returns. average = (x + y + z)/3.0average = (x + y + z)/3.0 RETURNRETURN END FUNCTION averageEND FUNCTION average
Computes Computes the the average average via a via a defined defined functionfunction
2323
Fortran gotchasFortran gotchas
All variables must be declared at the beginningAll variables must be declared at the beginningRemember line limit of 72 characters!Remember line limit of 72 characters! Consider:Consider:
The 8The 8thth variable is named ‘ei’ variable is named ‘ei’ There is no 9There is no 9thth variable declared variable declared
No continuation lines in Fortran 77No continuation lines in Fortran 77== is comparison for if's== is comparison for if'sCan’t seem to be able to change the values of Can’t seem to be able to change the values of parameters in functionsparameters in functions
integer :: first, second, third, fourth, fifth, sixth, seventh, eighth, ninthinteger :: first, second, third, fourth, fifth, sixth, seventh, eighth, ninth
Column 72!
2525
John BackusJohn Backus
Chemistry major at UVA Chemistry major at UVA (entered 1943)(entered 1943)Flunked out after second Flunked out after second semestersemesterJoined IBM as programmer in Joined IBM as programmer in 19501950Developed Fortran, first Developed Fortran, first commercially successful commercially successful programming language and programming language and compilercompiler
2626
IBM 704 Fortran manual, 1956
2727
Fortran issues…Fortran issues…Fortran language was described using EnglishFortran language was described using English
ImpreciseImprecise Verbose, lots to readVerbose, lots to read Ad hocAd hoc
DO 10 I=1.10DO 10 I=1.10Assigns Assigns 1.101.10 to the variable to the variable DO10IDO10I
Early Fortrans didn’t care about spaces!Early Fortrans didn’t care about spaces!
DO 10 I=1DO 10 I=1,,1010Loops for Loops for I = 1I = 1 to to 1010
(Often incorrectly blamed for loss of Mariner-I)(Often incorrectly blamed for loss of Mariner-I)