SlideShare ist ein Scribd-Unternehmen logo
1 von 116
Skill Enhancement Course
Computational Physics :
FORTRAN
Dr. Manamohan Prusty
(Asst. Prof. in Physics)
P.G. Dept. of Physics,
Government (Autonomous)College,
Angul
PLAN
•PART I – Computers and Linux
•PART II – FORTRAN History and structure
•PART III – Control statements and Programming
Compiled By : Dr. Manamohan Prusty
PART I : COMPUTER and LINUX COMMANDS
• Computer Hardware
• Components
• Motherboard
• CPU
• RAM
• Hard disk and Giant MagnetoResistance
• UNIX/LINUX File System
• Shells and UNIX/LINUX commands
• Shell Utilities and text editor
Compiled By : Dr. Manamohan Prusty
Computer Hardware - Components
Source : wikipedia
Compiled By : Dr. Manamohan Prusty
Motherboard
Source : wikipedia
Compiled By : Dr. Manamohan Prusty
Central Processing Unit (CPU)
Source : www.intel.com
Compiled By : Dr. Manamohan Prusty
Central Processing Unit
CPU Components
1) Core
2) Branch predictor
3) Floating Point Unit
4) Level 1 Cache
5) Bus Interface
Compiled By : Dr. Manamohan Prusty
RANDOM ACCESS MEMORY
Random access memory (RAM) is a form of
computer data storage that stored data and
machine code currently being used. It allows
data items to be read and written in almost
the same amount of time irrespective of the
physical location of data inside the memory.
In today’s technology it takes the form of ICs.
It is normally associated with volatile type of
memory, where the stored information is lost
if power is removed.
Source : wikipedia
Compiled By : Dr. Manamohan Prusty
HARD DISK
A hard disk is a data storage device that uses
magnetic storage to store and retrieve digital
information using one or more rapidly rotating
disks coated with magnetic material. In hard
disks data is accesses in a random-access manner,
meaning that individual blocks of data can be
stored or retrieved in any order. Hard disks are
type of non-volatile storage, retaining stored
data even when powered off.
Physics Nobel Prize 2007 –
Jointly awarded to Albert Fert andPeter
Grünberg “for discovery of GiantMagnetoresistance”.
Source : wikipedia
Compiled By : Dr. Manamohan Prusty
Physics Nobel Prize – 2007 (GMR)
AlbertFert
PeterGrünberg
Nanotechnology gives sensitive read-out heads for compact harddisks
This year's physics prize is awarded for the technology that is used to read data on hard disks. It is thanks to this
technology that it has been possible to miniaturize hard disks so radically in recent years. Sensitive read-out heads
are needed to be able to read data from the compact hard disks used in laptops and some music players, for instance.
In 1988 the Frenchman Albert Fert and the German PeterGrünberg each independently discovered a totally new
physical effect – Giant Magnetoresistance or GMR.Very weak magnetic changes give rise to major differences in
electrical resistance in a GMR system.A system of this kind is the perfect tool for reading data from hard disks when
information registered magnetically has to be converted to electric current. Soon researchers and engineers began
work to enable use of the effect in read-out heads. In 1997 the first read-out head based on the GMR effect was
launched and this soon became the standard technology. Even the most recent read-out techniques of today are
further developments ofGMR.
A hard disk stores information, such as music, in the form of microscopically small areas magnetized in different
directions.The information is retrieved by a read-out head that scans the disk and registers the magnetic changes.
The smaller and more compact the hard disk, the smaller and weaker the individual magnetic areas. More sensitive
read-out heads are therefore required if information has to be packed more densely on a hard disk. A read-out head
based on theGMR effect can convert very small magnetic changes into differences in electrical resistance and there-
fore into changes in the current emitted by the read-out head.The current is the signal from the read-out head and its
different strengths represent ones and zeros.
TheGMR effect was discovered thanks to new techniques developed during the 1970s to produce very thin layers of
different materials. If GMR is to work, structures consisting of layers that are only a few atoms thick have to be
produced. For this reasonGMR can also be considered one of the first real applications of the promising field of
nanotechnology.
Source :: www.nobelprize.org
Compiled By : Dr. Manamohan Prusty
Operating Systems
• It is a system software that
• Manages computer hardware and softwareresources
• Acts as a resource manager for various components
• Acts as an intermediary between hardware functions such as various I/O devices,
memory allocations and the computer programs
• Provides common services for computer programs
• Various type of operating systems are
• Microsoft windows by Microsoft corp.
• MacOS by AppleInc.
• Varieties of Linux (these are dominant in the server and supercomputing sectors)
Source :wikipedia
Compiled By : Dr. Manamohan Prusty
Unix/Linux OS – DevelopmentHistory
Source : wikipedia
Compiled By : Dr. Manamohan Prusty
Unix/Linux OS -History
Source : wikipedia
Compiled By : Dr. Manamohan Prusty
Unix/Linux OS – Filesystem
Source : wikipedia
/home (saved personal files)
/proc (virtual file system providing process and kernel information)
/bin (Essential command libraries – ls, cp, …)
/root (home for root user)
/boot (Boot loader files - kernel, initrd etc)
/run (info on running system)
/dev (Essential device files)
/sbin (Essential system binaries)
/etc (system-wide configuration files)
/srv (site specific data forservers)
/sys (contains info on devices, drivers etc)
/lib (files essential for /bin and /sbin)
/tmp (temporary files)
/media (mount points for removable media)
/usr (user utilities and applications)
/mnt (Temporary mounted file system)
/var (variable files which change frequently)
/opt (Optional application packages)
Primary
root
Compiled By : Dr. Manamohan Prusty
Unix/Linux Commands - Specialcharacters
• . present working directory
• .. directory above the present directory
• / divider between directories
• * a wild card that matches any sequence of characters
• ? a wild card that matches any single character
• ; separates Linux commands on a single line
• ! related to history (past typed) commands
• ~ location of main home directory
• & causes a command to run in background
• | routes the output from a command to the next command
• > routes the output from a command to create a new specified file
• >! same as above but if file already exists then replaces the file
• >> routes the output from a command to append to a specified file
• < routes a specified file to be input to a command
• SPACE acts as field separators
Compiled By : Dr. Manamohan Prusty
Unix/Linux Commands - Moving around (cd)
• cd
• cd ~
• cd ../
• cd ~/dir
• cd ../../
• cd ../dir
change directory to home directory
same as above
change directory one level up
change to directory dir below your home directory
change directory two level up
go up one directory and then down into directory dir
Compiled By : Dr. Manamohan Prusty
Unix/Linux Command – Exploring around (ls - list)
• ls
• ls -a
• ls -l
• ls -s
• ls –la
list - location and/of filename info
list all entries including normally hidden files (that starts with a .)
list in long format (it include time of last modification, size,
group, owner etc)
give size in blocks
it combines the above flags –l and –a (In fact you can combine as
many flags as possible)
Compiled By : Dr. Manamohan Prusty
Unix/Linux Command – ls –l and ls examples
• ls –l
type : d (directory) - (0rdinary) l (link) permissions : r (read) w (write) x (execute)
size in byte and name is the name of the file
• ls ..
• ls ~
Lists what is in the directory directly above the current directory
Lists what is in the home directory
Compiled By : Dr. Manamohan Prusty
Unix/Linux – More commands
• more location/filename display the contents of a file one page at a time on the
screen: pressing spacebar goes to the next page and b back a page
• cat location/filename
• head location/filename
• wc location/filename
• tail location/filename
• file location/filename
• vi location/filename
• emacs location/filename
scroll the whole file to the screen
displays the first 10 lines of a file
word count : displays the number of words, lines and
characters in a file
displays the last 10 lines of a file
displays the type of file if determinable
edit the file with vi (VIsual editor)
open the file for editing in emacs editor.
Compiled By : Dr. Manamohan Prusty
Unix/Linux – More commands
• mkdir dirname
• pwd
• cp loc1/file1 loc2/file2
• mv loc1/file1 loc2/file2
• rm location/filename
• rmdir dname
• rm –i filename
make a directory with name dirname
displays the present working directory
copies the file1 from loc1 directory to loc2 directory and
stores it with a new file name file2
moves the file1 from loc1 directory to loc2 directory and
stores it with a new file name file2
removes the file named filename from location directory
removes the directory names dname
removes the file named filename interactively
Compiled By : Dr. Manamohan Prusty
Unix/Linux – More commands
• df
• du –ks ~username
finds out how much space is on mounted disks
finds out how much space (in KB) is used by the user
usename
list previous commands
execute the previous command
execute command 3
• history
• !!
• !3
• chmod <options permissions> filename Changes the permission of filename (which
can be a file or directory as per given <options> [u=user, g=group, o=other, a=all].
Permissions can be read(r), write(w), execute(x) with a + sign for addition and a –
sign forremoval)
• Caution/Warning -
Example : chmod go-r myprog.f chmod u+xmyprog.f
Never give everyone write permissions
Compiled By : Dr. Manamohan Prusty
Unix/Linux – Piping and redirection commands
• Piping is used to send the output of a command to another command
• ls –l | more
• ls –l | lp
It pipes the output of ls –l command to the more command
It sends the results of ls –l to the printer
• Redirection (<,>,>>) deals with input and output from files
• mail username@mainaddress < filename It takes the file filename and make
it the input to the mail command
• ls –l > filename It does the long listing (ls –l) and writes the output to filename
• ls –l >> filename It appends the output of ls –l command to end of the file filename
• a.out < infile > outfile a.out gets the input from infile and sends the output to outfile
Compiled By : Dr. Manamohan Prusty
Unix/Linux – Killing a process
• If a program is running in the foreground type Ctrl-c (hold the control keyand
press c) to kill the foreground program
• If the process is running in the background then open a shell/terminal and type
ps –elf It returns a list of processes you are running.The first column inthis
list is the Process ID (PID) number.Then use kill 1234 to kill the
process having PID number 1234
ps –elf | grep username Returns the processes run by user username
Compiled By : Dr. Manamohan Prusty
PART II : FORTRAN - Basic Overview
• History and development of FORTRAN
• Basic elements of FORTRAN
• Layout of FORTRAN program and programexecution
• Operators
• Expressions
• Input/Output
• Keywords
• Statements
Compiled By : Dr. Manamohan Prusty
FORTRAN : John Backus (1924-2007) and IBM 704
Compiled By : Dr. Manamohan Prusty
FORTRAN : History
• John Backus (3rd Dec. 1924 – 17th Mar. 2007) a chemistry major in University
ofVirginia (1943), flunked out after second semester, enrolled intoarmy
• Began medical training at Haverford college - ended in nine months
• Moved to NewYork city and trained as a radiotechnician
• Graduated from ColumbiaUniversity with a bachelor's degree in 1949 anda
master's degree in 1950 – both in mathematics
• Joined IBM in 1950 and worked on the project SSEC (Selective Sequence
ElectronicCalculator)
• In 1953, he developed the language speedcoding – the first high level
software developed for IBM 701 computer
• In 1954, Backus assembled a team to develop FORTRAN 0(for IBM 704
computer – the first high level programming language for broad use.
Compiled By : Dr. Manamohan Prusty
FORTRAN : History
• Stands for `IBM Mathematical FORmulaTRANslation System’ – abbreviated to “FORmula
TRANslation” - designed for use in scientific and engineering applications as a friendly
alternative to AssemblyLanguages
• FORTRAN I Compiler (1957) was the first optimizing compiler – cut development time from
2 weeks to 2 hours
• By 1958 over 50% of softwares was inFORTRAN
• FORTRAN II – Independent compilation with bugfixes
• FORTRAN III –Was developed but never widelydistributed
• FORTRAN IV – ANSI standard 1966 with explicit type declarations, logical (IF)statements
• FORTRAN77 – became new standard with character string handling, Logical Loop
statements and IF with ELSE (optional)statements
• Originally written as FORTRAN - all capitals upto FOTRAN77, later modified to title capital
for Fortran 90 onwards
Compiled By : Dr. Manamohan Prusty
FORTRAN : History
• Fortran 90 (1991) – FORTRAN77 was revised and modernized to continue
its long history as a scientific and engineering programming language,
included modules, structures etc
• Fortran 95 – minor tweaks to Fortran90
• Fortran 2003 – More improvements and was implemented by compiler
companies. Includes object oriented support and interoperability with C
programming language
• Fortran 2008 (2010) – Includes much more advanced features such as
submodules, coarrays, complex arguments to trigonometric function etc.
Compiled By : Dr. Manamohan Prusty
FORTRAN I – some statements
• IF <expression> n1, n2, n3
• DO n1 variable = m1, m2, m3
n1CONTINUE
• READ n1, List
• WRITE TAPE i, List
• FORMAT(specification)
• REWIND
Compiled By : Dr. Manamohan Prusty
IBM 704 Fortran
manual, 1956
Compiled By : Dr. Manamohan Prusty
FORTRAN77Syntax
• First six columns must be spaces, unless it is a comment
• Comments starts with a ! orC
• Program starts with PROGRAM <name> and stops with END PROGRAM
• Lines can only be seventy-two characters long
• No semi-colons after each line
• A newline is a statement terminator
• Always put IMPLICIT NONE right after the PROGRAM line – It prevents
implicit variable declaration (all constants, variables and arrays starting with
the letters I, J, K, L, M and N are automatically taken to be INTEGER type)
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A Typical ProgramLayout
c234567
PROGRAM MYPROGRAM
STOP
END
Program Options
Declaration of Variables
MAIN CODE
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A Typical ProgramLayout
c234567
PROGRAM MYPROGRAM
STOP
END
Program Options
Declaration of Variables
MAIN CODE
The first seven columns
of the program code are
reserved for special
functions – most lines
of code begin on the
seventh column
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A Typical ProgramLayout
c234567
PROGRAM MYPROGRAM
STOP
END
Program Options
Declaration of Variables
MAIN CODE
This line identifies the
code as a program
(instead of, say, a
subroutine) and gives it
the name
MYPROGRAM.
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A Typical ProgramLayout
c234567
PROGRAM MYPROGRAM
STOP
END
Program Options
Declaration of Variables
MAIN CODE
All the variables used
in the code have to be
declared at the top,
before any main code
could be executed
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A Typical ProgramLayout
c234567
PROGRAM MYPROGRAM
STOP
END
Program Options
Declaration of Variables
MAIN CODE
Here is where all the
magic (read, write,
calculations etc) of
your program happens
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A Typical ProgramLayout
c234567
PROGRAM MYPROGRAM
STOP
END
Program Options
Declaration of Variables
MAIN CODE
This identifies the end of
the program.
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A More complicated programLayout
PROGRAM MYPROGRAM
Options
Declaration of Variables
MAIN CODE
CALL MYSUBROUTINE
MAIN CODE
STOP
END PROGRAM
SUBROUTINE MYSUBROUTINE
Options
Declaration of Variables
MAIN CODE
RETURN
END SUBROUTINE
Compiled By : Dr. Manamohan Prusty
FORTRAN77 – A More complicated program Layout
PROGRAM MYPROGRAM
Options
Declaration of Variables
MAIN CODE
CALL MYSUBROUTINE
MAIN CODE
STOP
END PROGRAM
SUBROUTINE MYSUBROUTINE
Options
Declaration of Variables
MAIN CODE
RETURN
END SUBROUTINE
Being able to trace the flow of
information is by far the most
important thing to learn
about programming, in
Fortran or in any other
language.
You will eventually have to
write codes that is not only
error free but also should be
able to perform complicated
functions and is readable to
someone else who wishes
to use it.
Compiled By : Dr. Manamohan Prusty
Example : A
Demo Program
to calculate the
sum of few
numbers and
their average
The numbers are input from the keyboard.
PROGRAM average
IMPLICIT none
! Type variables.
REAL :: indata, sum, avg
INTEGER n, i
! Prompt for the number of numbers to be averaged.
PRINT *,"Enter the number of numbers to be averaged."
READ *,n
sum = 0.0
DO i = 1, n !Loop goes over the number of data
! Prompt for and enter a number.
PRINT *,"Enter a value for the number"
READ *,indata
sum = sum + indata ! Add number to total.
END DO
avg = sum/real(n) ! Calculates the average.
PRINT*,“Sum =”,sum,“Average = ",avg !Prints the results.
STOP
END PROGRAM
Compiled By : Dr. Manamohan Prusty
! program that sums and averages a series of numbers.
!
Compiling a FORTRAN Program
• First edit the program using your favorite editor.
(Note – while editing the program, all program codes must start from 7th
column except the comments)
• Save the program with a filename file.f
(Note - the extension of the filename is .f)
• Enter the command f77 –o file.exe file.f or g77 –o file.exe file.f
• Then execute the command ./file.exe on the command prompt
Compiled By : Dr. Manamohan Prusty
Character sets
• Character sets : Upper and lower case letters (A - Z and a -z),
Numerals (0 - 9)
• Special characters : . Decimal point, () Parenthesis, = Equal, + Plus, - Minus,
*Asterisk, / Slash, , Comma, ‘’Apostrophe, ! Exclamation
• Symbolic names : - can be any number of characters long (consisting of
letters, digits, the dollar $ and the underscore _ sign), generally starts with a
letter (never with numerals, the dollar sign or the underscore sign)
• For any single program – different entities such as Entry points, Functions,
Main program, Subroutines, Common blocks, Subprograms cannot havesame
symbolic names
• Cannot change the value of parameters within functions
Compiled By : Dr. Manamohan Prusty
Constants and their types
• Constants are data whose values do not change during the program unit
• Three general type of constants : Arithmetic, Logical andCharacter
• Arithmetic constants : Complex, Real, Integer, Binary,Octal, Hexadecimal etc (can
be signed or unsigned)
• Examples : Integer constants - +199, -2147483648, 0
• Real constants - +32.0, -12.34, 1.6E-9,7D3,
• Other constants - DATAn1 /B ‘10110101’/, n2 /O ‘37’/, n3 /X ‘1f’/
• Logical constants : .TRUE. and .FALSE. (only two types)
• PARAMETER (T=.TRUE.,F=.FALSE.)
• Character Constants : a string of characters enclosed within apostrophes or quotes
• Examples : ‘abc’, “can’t”, ‘’ (Null character)
• character*1 x / ‘a’/, y / ‘’/,z / ‘ b’/
Compiled By : Dr. Manamohan Prusty
Constants and their types (more examples)
• CHARACTER :: ‘FILENAME’
• INTEGER :: 3, -9999, 1e10
• Must be in the range (-2147483648, 2147483647).
• REAL:: 3.3, -9999., 1.5e8, 1e-3
• Must be in the range (1.175494E-38, 3.402823E+38)
• REAL*8 :: 6D2, -25.3D-7
• Must be in the range (2.225074D-308, 1.797693D+308)
• COMPLEX:: (1,-2) or (1.3,0.4)
• LOGICAL:: .TRUE. and .FALSE.
Compiled By : Dr. Manamohan Prusty
Variables and their types
• A symbolic name paired with a storage location. It can have a value.
• Mainly of four types - real, integer, character, logical
• Examples - REAL :: x, y, z=1.414
INTEGER :: a, b=1, c
CHARACTER :: name *20, college_name=“Govt (Auto)College”
LOGICAL :: logical1=.TRUE., logical2=.FALSE.,T,F
• Upper case and lower case are not significant as the compiler converts them
all to lower case during compilation.Thus shx = 5 and SHX=5 areequivalent
• Standard FORTRAN Joke, “GOD is REAL unless declared INTEGER”.
Compiled By : Dr. Manamohan Prusty
Operators : Arithmetic and Logical
• Arithmetic operators : ** Exponentiation, * Multiplication, / Division, +
Addition or Unary plus, - Subtraction or Unaryminus
• Among the above the precedence of operations is from left to right except
when parentheses are involved.
• Calculations are carried out from right to left except in case of parenthesis
where calculations are carried out from inside out
• Examples :: 2+3, x**2, x*y, -z, 29.5/8, x**3+5*(x*y+y*z+z*z)+x/y-z+0.2
• Logical operators : Conjunction operator -X .AND.Y (BothX andY are true)
Disjunction operator –X .OR.Y (EitherX orY or both are true)
Compiled By : Dr. Manamohan Prusty
Operators : Type conversion and Mixed modeArithmetic
Expression type Output type
INTEGER / INTEGER INTEGER
INTEGER * REAL REAL
INTEGER / REAL REAL
INTEGER + or – REAL REAL
REAL or INTEGER * DOUBLE DOUBLE PRECISION
Compiled By : Dr. Manamohan Prusty
Operators : Relational , Character andAssignment
• Relational operators : .LT.Less than (<), .GT.Greater than (>), .LE. Less than
or equal (<=), .GE.Greater than or equal (>=), .EQ. Equal (==), .NE. Not equal
(/=)
• Character operator : Concatenation operator - //
Examples - a//b (a, b are characters), ‘file’// ‘name’
• Assignment operator : the equal sign (=) is the assignment operator. Comes in
the form variable = expression
Examples – DISC = B**2-4*A*C
x1 = (-B +SQRT(DISC))/(2*A)
x2 = (-B -SQRT(DISC))/(2*A)
Compiled By : Dr. Manamohan Prusty
Expressions
• An expression consists of constants, variables, operators, parentheses, function
references and specific rules for computing a value
• Expressions can be arithmetic, logical, character or assignment
• A constant expression consists of explicit constants and parameters and the
FORTRAN operators
• Examples :
• PARAMETER (L=29), (B=15),(P=3.14159), (C='along the ')
• PARAMETER (PR=(L+B)*2,V=4.0*P/3.0,S=C//'riverrun')
• LOGICALT,F
• K = 66 * 80 ;VOLUME =V*10**3
• DO i = 1, 20*3
• T = .TRUE.; F=T .AND. 3 .LT.5/2
Compiled By : Dr. Manamohan Prusty
Expressions
• Examples of few arithmetic and logical expressions
• x, 3.0, x+3.0, (2**2)**3 = 2**6
• x = 1.0 + 3 * (7/4) – 4* (7.0/3.0)
• 2**(2**3)
• p = w/x/y/z
• q =w*x/y*z
• x==y
=2**8
= w/(x*y*z)
= w*(x/y)*z
= .TRUE. or .FALSE.
Compiled By : Dr. Manamohan Prusty
Predefined Functions – Data TypeConversion
Function Description
INT(x) Convert to INTEGER
NINT(x) Convert to nearest integer
REAL(a) Convert to REAL
DBLE(x) Convert to DOUBLE PRECISSION
CMPLX(x,y) Convert to COMPLEX
DCMPLX(x,y) Convert to DOUBLECOMPLEX
CHAR(x) Convert to CHARACTER
Compiled By : Dr. Manamohan Prusty
Predefined Functions - CHARACTER andCOMPLEX
Function Description
LEN(char) Length of character entry (char)
INDEX(string, substring) Index of substring within a string i.e., position of first
occurrence of substring as a substring in string
ICHAR(A) ASCII value of a single byte character argument
Function description
IMAG(z) Imaginary part of complex number z
REAL(z) Real part of complex number z
CONJG(z) Complex Conjugate of complex number z
CHARACTER Functions
Complex Functions
Compiled By : Dr. Manamohan Prusty
Predefined Functions - Mathematical andTrigonometric
Function Description
MAX(x,y) Maximum value
MIN(x,y) Minimum value
ABS(x) Absolute value
DIM(x,y) Positive difference
MOD(x,y) Modulus or remaindering
SIGN(x,y) Transfer of sign
DPROD(x,y) Double precision product of reals
SQRT(x) Square root
EXP(x) Exponential
LOG(x) Natural logarithm (base e)
LOG10(x) Common logarithm (base 10)
Function description
SIN(x) / SIND(x) Sine (x) / Sine (degrees)
COS(x) / COSD(x) Cosine (x) / Cosine(degrees)
TAN(x) /TAND(x) Tangent (x) / Tangent(degrees)
ASIN(x) / ASIND(x) Arcsine (x) / Arcsine(degrees)
ACOS(x) / ACOSD(x) Arccosine (x) / Arccosine(degrees)
ATAN(x) / ATAND(x) Arctangent (x) / Arctangent(degrees)
ATAN2(x,y) Arctangent result between [–π : π]
SINH(x) Hyperbolic sine (x)
COSH(x) Hyperbolic cosine (x)
TANH(x) Hyperbolic tangent (x)
Mathematical Functions Trigonometric Functions
Compiled By : Dr. Manamohan Prusty
Input andOutput
• Twokinds of I/O – Formatted, Unformatted
• Format specifiers for Formatted I/O
• A - text string
• D - double precision numbers, exponent notation
• E - real numbers, exponent notation
• F - real numbers, fixed point format
• I - integer
• L – Logical value (T or F)
• X - horizontal skip (space)
• / - vertical skip to newline
• T –Tabspace to certaincolumn
• D, E and F have the general syntax Dw.d , Ew.d , Fw.d (w denotes the field width and d denotes
the number of significant digits)
• A, I andT have the general syntax Aw, Iw andTw(w denotes the fieldwidth)
Compiled By : Dr. Manamohan Prusty
Input and Output – Formatted - examples
• General syntax – READ(unit,format) list
WRITE(unit,format) list
• Example : REAL *, X/1.23D0/, Y/43.D0/
INTEGER *, J=16
WRITE(6,203) J, X, Y
203 FORMAT(2x, I3/’X=‘,T7,F5.2/D8.2)
• If the field is narrow then the FORTRAN library prints only asterisks
• Output on screen
16
X= 1.23
0.43D+02
Compiled By : Dr. Manamohan Prusty
Input and Output - File operations
OPEN(unit=n, FILE=‘filename’,FORM=‘formatted’,ACCESS=‘DIRECT)
•Modes of FileAccess : Sequential (default) and Direct
•Types of Files : External file – resides on a physical
peripheral device such as disk, usb drive etc
Internal file – It is a location in main
memory, is of character type. It is either a variable, a
substring, array, array element, a field of structured
record.
Compiled By : Dr. Manamohan Prusty
Keywords within the statements
• In FORTRAN most statements begin with a keyword; the exceptions are the
statement function and assignment statements
• Keywords of FORTRAN77 are ASSIGN, BACKSPACE, BLOCK DATA,CALL,
OPEN, CLOSE, INQUIRE,COMMON, DATA, DIMENSION, DO, ENDDO,
CONTINUE, IF,THEN, ELSE, ELSEIF, ENDIF, ENDFILE, ENTRY,
EQUIVALENCE, EXTERNAL, FORMAT, FUNCTION, SUBROUTINE,
PROGRAM, GOTO, IMPLICIT, INTRINSIC, PARAMETER, PAUSE, PRINT,
READ,WRITE, SAVE, REWRITE, REWIND, STOP,END, FILE etc
Compiled By : Dr. Manamohan Prusty
Executable statements
• Executable Statements : It specifies actions and form an execution sequence
in a program.The following are executablestatements
• Arithmetic, logical and assignment statements
• UnconditionalGOTO, assigned GOTO and computedGOTOstatements
• Arithmetic and Logical IF statements
• BLOCK IF,ELSEIF, ELSE and ENDIF statements
• CONTINUE, PAUSE and STOP statements
• DO, ENDDO and END statements
• READ,WRITE and PRINTstatements
• CALL and RETURN statements
• REWIND, BACKSPACE, ENDFILE,OPEN,CLOSE and INQUIREstatements
Compiled By : Dr. Manamohan Prusty
Non-executable statements
• Non-executableStatements :These are not part of the executionsequence.
They specify characteristics or attributes such as type and size,
arrangements or order, editing instructions, entry points within
subprograms, statement functions, program units etc.The following are
non-executable statements
• PROGRAM, FUNCTION, SUBROUTINE, ENTRY and Block DATAstatements
• DIMENSION,COMMON, EQUIVALENCE, IMPLICIT, PARAMETER, EXTERNAL, INTRINSIC
and SAVEstatements
• INTEGER, REAL, DOUBLE PRECISION,COMPLEX, LOGICAL and CHARACTER type
statements
• DATAand FORMAT statements
Compiled By : Dr. Manamohan Prusty
PART III : Control Statements and Programming
• Logical expressions and type of logic
• BranchingStatements
• JumpingStatements
• LoopingStatements
• Subscripted variables
• Functions andSubroutines
• Disk I/OStatements
• File operations
Compiled By : Dr. Manamohan Prusty
Logical operators
• Logical expression - sequence of one/more logical operands and/or operators
• Two logical operators cannot appear twice unless the second is .NOT. operator
Operator Standard Name Precedence
.NOT. Logical Negation Highest
.AND. LogicalConjunction
.OR. Logical Disjunction (InclusiveOR)
.NEQV. Logical Nonequivalence Lowest
.XOR. Logical ExclusiveOR Lowest
.EQV. Logical Equivalence Lowest
Operator Precedence
Arithmetic Highest
Character
Relational
Logical Lowest
Compiled By : Dr. Manamohan Prusty
Logical variable and expressions
Syntax : Variable =Expression
Expression Meaning
X .AND.Y Both X and Y aretrue
X .OR.Y Either X orY or both are true
X .NEQV.Y X and Y are not both true and not bothfalse
X .XOR.Y Either X orY is true, but not both
X .EQV.Y X and Y are both true or bothfalse
.NOT.X Logical negation
Compiled By : Dr. Manamohan Prusty
Types of Logic
• Sequential Logic – Sequential logic is a type of logic whose output depends
not only on the present value of its input but also on the sequence of past
inputs, the input history.
• Selection Logic - In a selection logic, a question is asked, and depending on
the answer, the program takes one of two courses of action, after which the
program moves on to the next event.
• Repetition Logic - Repetition Logic repeats a sequence of test steps a number
of times while or until a user-defined condition is true.The condition used in
repetition logic compares two values and returns a value based on the
comparison.
Compiled By : Dr. Manamohan Prusty
Branching Statements (IF)
• Logical IF
• Arithmetic IF
• Block IF
• ELSEIF
• Nested BlockIF
• SELECTCASE
Compiled By : Dr. Manamohan Prusty
Logical IF
• The Logical IF is a single line statement only
• Syntax : IF (logical expression) executable statement
• If the logical expression is true then execute the executable statement
• Example : !Program for checking if a given number is odd
• PROGRAM odd
INTEGER x, y,rem
PRINT*, “Enter the value of number”
READ (5,*) x
y=x/2; rem = x – 2*y
IF (rem .EQ. 1)WRITE (6,*) x, “is odd”
END PROGRAM
Compiled By : Dr. Manamohan Prusty
Arithmetic IF
• The Arithmetic IF is a three way arithmetic conditional statement
• Syntax : IF (arithmetic expression) negative, zero, positive
• If the arithmetic expression is negative then execute the negative label statement, if
it is zero then execute the zero label statement and if it is positive then execute the
positive label statement
• It was declared obsolescent (no longer being used even though it can work) in
Fortran 90
• Example : DISC = B*B - 4*A*C
IF (DISC) m1, m2, m3
m1 negative condition statement
m2 zero condition statement
m3 positive condition statement
Compiled By : Dr. Manamohan Prusty
• The Block IF statement is a more general version of simple Logical IF statement and
can take several forms depending on the complexity of the decisions. If output
depends on several conditions repeatedly then ELSEIF statement is used.
• Syntax : Simplest Form - IF (logical expression)THEN
executable statement
ENDIF
Form 2 : IF (logical expression) THEN
executable statement1
ELSE
executable statement2
ENDIF
Block IF, ELSEIF and Ladder statements
General Form : IF (logical expression1) THEN
executable statement1
ELSEIF (logical expression2) THEN
executable statement2
ELSEIF (logical expression3) THEN
executable statement3
…
ELSE
executable statement
ENDIF
Compiled By : Dr. Manamohan Prusty
• Nesting refers to the inclusion of one control within another control. Thus one can create
one Block IF construct within another Block IF. In this case both the IF statements will not
overlap, rather one IF statement will contain the other IF construct.
• Example : A 𝑥2 + B 𝑥 + C = 0, solution 𝑥 = − 𝐵 ± 𝐵2 − 4 𝐴 𝐶
2 𝐴
IF (A .NE. 0.0) THEN
DISC = B**2 – 4*A*C
IF (DISC .GT. 0.0) THEN
!Level1 IF statement
!Calculates the Discriminant
!Level2 IF statement inside the level1 IF statement
WRITE(*,*) “Roots are real and distinct”
ELSEIF (DISC .LT. 0.0) THEN
WRITE(*,*) “Roots are complex conjugate”
ELSE
WRITE(*,*) “Solutions are real andidentical”
ENDIF
ELSE
WRITE(*,*) “The equation is a linear equation and not a quadraticone”
ENDIF
Nested Block IF
Compiled By : Dr. Manamohan Prusty
Arithmetic IF vs Block IF - Equivalence
• DISC = B*B-4*A*C
IF (DISC) m1, m2, m3
m1 negative condition statement
m2 zero condition statement
m3 positive condition statement
• DISC = B**2-4*A*C
IF (DISC .LT. 0) THEN
GOTO m1
ELSEIF (DISC .EQ. 0) THEN
GOTO m2
ELSE
GOTO m3
ENDIF
m1 negative condition statement
m2 zero condition statement
m3 positive condition statement
Block IFConstructArithmetic IFConstruct
Compiled By : Dr. Manamohan Prusty
SELECT CASE
• SELECT CASE is used to execute a set of multi-alternative selection criterions.
• Syntax : SELECT CASE (selector)
•
•
•
•
•
•
•
•
CASE (list_1)
statement1
CASE (list_2)
statement2
…
CASE DEFAULT
default statement
ENDSELECT
Note - Here selector can be an
integer, character or logical
expression.The list_i is a list of
one or more possible values of
the selector index.The DEFAULT
option in a CASE constructor
can be omitted.
Compiled By : Dr. Manamohan Prusty
SELECT CASE - Example
• SELECTCASE(points)
CASE (:50)
WRITE(*,*) “You need to practice more”
CASE (50:80)
WRITE(*,*) “You have tried well but not enough”
CASE (80:90)
WRITE(*,*) “You just missed the top list”
CASE DEFAULT
WRITE(*,*) “Congratulations :You made to the toplist”
ENDSELECT
Compiled By : Dr. Manamohan Prusty
Looping : DO – CONTINUEstatements
• Loop allows that a block of statements be executed repeatedly
without actually writing them down numerous times.
• Syntax : DO label variable = initial, final, step-size
statement1
statement2
……
label CONTINUE
• Note – 1.The loop variable can be a variable of typeREAL,
INTEGER or DOUBLE PRECISSION but not an array element
2. If the step size is unity (one), then it can be omitted as
part of the DO statement
Compiled By : Dr. Manamohan Prusty
DO – WHILELoop
DOWHILE (logical expression)
statement1
statement2
……
ENDDO
• The DO –WHILE Loop allows a block of statements beexecuted
repeatedly until the specifiedWHILE condition istrue.
• Syntax :WHILE (logical expression)DO
statement1
statement2
……
ENDDO
• Note – DO –WHILE Loop is not part ofANSI FORTRAN77.So the
correct way is to use IF and GOTOstatements
Compiled By : Dr. Manamohan Prusty
• WHILE (logical expression) DO
statement1
statement2
……
ENDDO
DO –WHILE vs IF – GOTOstatements
• label IF (logical expression)THEN
statement1
statement2
……
GOTO label
ENDIF
Example : i = 0
100 IF (x .GE. 0D0) THEN
x = x - SQRT(x)
i = i + 1
GOTO 100
ENDIF
Compiled By : Dr. Manamohan Prusty
DO-UNTIL Loop
label CONTINUE
statement1
statement2
……
IF (logical expression) GOTO label
• The DO – UNTIL Loop keeps the termination criterion at the end
instead of at the beginning.
• Syntax : DO
statement1
statement2
……
UNTIL (logical expression)
• Note – UNTIL Loop is also not part ofANSI FORTRAN77. Sothe
correct way is to use IF and GOTOstatements
Compiled By : Dr. Manamohan Prusty
DO-ENDDO Loop
• The DO – ENDDO Loop replaces the DO - CONTINUEloop.
DO label variable = initial, final, step-size
statement1
statement2
……
label CONTINUE
DO variable = initial, final, step-size
statement1
statement2
……
ENDDO
loop1: DO
statements
……
ENDDO
loop1
Uncountable DO-ENDDO statement. It continues indefinitely
until an exit path is found. Normally the exit route is created
using the EXIT or GOTO commands. Here loop1: corresponds
to the DO-ENDDO construct name which can be optional.
Compiled By : Dr. Manamohan Prusty
• When a CYCLE statement is encountered inside a DO loop, then one
single DO loop is prematurely terminated and execution continues with
the next loop.
• Syntax :
DO i = 1, 100
statement1
IF (expression)THEN
! Skip the statement2 block when expression is trueCYCLE
ENDIF
statement2
ENDDO
CYCLE Statement
Compiled By : Dr. Manamohan Prusty
• An implied DO loop provides a fast way of listing many items.These items,
depending on the place where an implied DO is used, can be variables, expressions
or even implied DO loops (nested implied do loops).
• Syntax : (o-1, o-2, …, o-n, var = initial, final, step)
• It means for each value of the do variable var, all objects (o-1, o-2, …,o-n) are
listed once. Note that the adjacent objects are separated by commas.
• Example : (i*a(i), b(i+1), i=1,3) a(1), b(2), 2a(2), b(3), 3a(3), b(4)
• (i, (b(j), j=1,3),i=4,6) 4, b(1), b(2), b(3), 5, b(1), b(2), b(3), 6, b(1), b(2), b(3)
• ((a(i)*b(j), j=1,2), i=1,3) a(1)b(1),a(1)b(2),a(2)b(1),a(2)b(2),a(3)b(1),a(3)b(2)
• Note –The inner and outer loops are not interchangeable
• -These implied DO lists can also appear within the variable lists on I/O
statements such as PRINT, READ andWRITE.
Implied DO Loop
Compiled By : Dr. Manamohan Prusty
• READ(*,*) (x(i), i=1,5)
• WRITE(*, 50) ((Matrix(i,j),i=1,5),j=1,5)
• 50 FORMAT(‘ ‘, 5F10.4, /)
• WRITE(*, 80) (i, X(i),Y(i),i=1,101,5)
80 FORMAT(1X, I3,2x,2F10.6)
• WRITE(*,150) (i, i=1,5),((j,x(j,k), k=1,5), j=1,100)
150 FORMAT(1X, ‘Line’, 5I10, 100(/,2x,I5, F10.4))
Implied DO Loop – More examples
Compiled By : Dr. Manamohan Prusty
• It is possible to keep one DO loop within another DO loop to create a
nested DO loop
• Examples : DO i = 1,5
DO j = i, 12
DO k = 7, 2,-1
statements
ENDDO
ENDDO
ENDDO
Caution –Youcan exit from inside the IF-ENDIF and DO-ENDDOblocks.
However entering from outside is prohibited into them.
Loop inside Loop - Nested DO Loop
DO 20 i=1,6
DO 20 j=1,12
WRITE(6,*) a(i), b(j)
20CONTINUE
Compiled By : Dr. Manamohan Prusty
• A GOTO statement is used to transfer the control from one place to
another
• Mainly three types : UnconditionalGOTO
ComputedGOTO
AssignedGOTO
Caution – A GOTO statement can be used to transfer controlfrom
IF-ENDIF and DO-ENDDO blocks but not into them.
Jumping Statements -GOTO
Compiled By : Dr. Manamohan Prusty
• Syntax - GOTOlabel
…..
label executable statement
• When an unconditional GOTO statement is encountered, control
immediately jumps to the executable statement labelled with label
• Example - 10 CONTINUE
WRITE(*,*) “Enter a positive value”
READ(*,*) x
IF ( x .LE. 0.0) GOTO 10
UnconditionalGOTO
Compiled By : Dr. Manamohan Prusty
• The Computed GOTO statement selects one statement label from a list, depending on the computed
value (integer) of a mathematical expression.
• Syntax - GOTO (label1, label2, …), expression
label1 executable statement1 label2
executable statement2
…
• Example - GOTO (10, 20, 30,40), N
• 10WRITE(*,*) “Your choice is 1”
• 20 WRITE(*,*) “Your choice is2”
• 30 WRITE(*,*) “Your choice is 3”
• 40 WRITE(*,*) “Your choice is 4”
• Here if N=1 then the control moves to 10, for N=2, it jumps to 20 and so on. However if N is less then
1 or greater than 4, then no GOTO statement is executed and the control just continues as it is.
• Note – It’s use is strongly discouraged. Instead the block IF ladder statement has to be used.
ComputedGOTO
Compiled By : Dr. Manamohan Prusty
• GOTO (label1, label2, …), expression
label1 executable statement1 label2
executable statement2
…
Computed GOTO vs Block IF Ladder statements
• IF (expression .EQ. 1) THEN
GOTO label1
ELSEIF (expression .EQ. 2) THEN
GOTO label2
…
ENDIF
label1 executable statement1
label2 executable statement2
…
ComputedGOTOStatement Block IFStatement
Compiled By : Dr. Manamohan Prusty
• The ASSIGN statement is the only way to assign a statement label value to an INTEGER variable.
• Syntax - ASSIGN label TO integer-variable
• When an integer-variable is assigned a label statement, it may not be referenced as a number as
it has no numerical value
• Syntax ofAssigned GOTO - GOTO integer-variable, (label1,label2,…)
• Here the integer-variable must be assigned a statement label in an earlier ASSIGN statement.
The integer-variable must match one of the labels in the list
• Note –This form ofGOTO statement is obscure and it’s use is stronglydiscouraged.
ASSIGN and AssignedGOTO
Compiled By : Dr. Manamohan Prusty
• ASSIGN 40 TON
…
GOTO N, (10, 20,30,40)
10 PAUSE “Press enter to continue”
20 WRITE(*,*) “Your choice is2”
30 WRITE(*,*) “Your choice is 3”
40 STOP ‘Emergency Stop’
• PAUSE Syntax - PAUSE ‘string’ – A PAUSE statement prints out the string and waits for
the user response to continue
• STOP Syntax - STOP ‘string’ – A STOP statement displays the string and stops the
execution of the program before returning the control to the operating system
Assigned GOTO, PAUSE and STOP statement
Compiled By : Dr. Manamohan Prusty
• A constant or a variable – a particular memory location for a particular type of
data
• AnArray is a symbolic name referring to a group of memory locations,all
holding the same type of data
• One-DimensionalArray - In order to represent an one-dimensional array two
pieces of information is required – 1. data type and 2. number of elements in the
array
• SYNTAX : Data type, DIMENSION array-name(array_length)
Data type, DIMENSION array-name(lower_bound:upper-bound)
• Note –The upper_bound must be greater than the lower_bound.The
array_length, lower_bound:upper-bound must be integer constants.
Subscripted Variables -Arrays
Compiled By : Dr. Manamohan Prusty
!200 element double precission array• DOUBLE PRECISSION xarray(-99:100)
• INTEGER year, monno, dayno
PARAMETER (year=2018, monno=12, dayno=30)
CHARACTER*3 month(monno)
LOGICAL day(dayno)
• REAL, DIMENSION xyval(-100:10)
! 12 element 3 characterarray
! 30 element logical array
! 111 element real array
1D Arrays -Examples
Compiled By : Dr. Manamohan Prusty
• FORTRAN 77 has arrays up to seven dimensions.The elements ineach
dimension are of the same type.
• Examples : INTEGER i, j, ncol,nrow
PARAMETER (ncol=7, nrow=12)
REAL matrix(ncol,nrow),sum=0.0
DO i = 1, ncol
DO j = 1, nrow
READ(*,*) matrix(i,j)
sum = sum + matrix(i, j)
ENDDO
ENDDO
Multidimensional arrays
Compiled By : Dr. Manamohan Prusty
• 1D array :A(1),A(2),A(3),A(8),…..
• Higher Dimensional Array : stored in COLUMN major form. Example for -B(m,n)
B(3,1) … B(m,1)
B(3,2) … B(m,2)
B(2,3) … B(m,3)
B(1,1)
B(1,2)
B(1,3)
…
B(1,n)
B(2,1)
B(2,2)
B(2,3)
…
B(2,n)
… … …
B(3,n) … B(m,n)
• Note - the order in which array stores the data and accesses it makes compiler
run faster and efficient codes. ‘out of order’ code slows down the program and
thus is less efficient. C++ stores array as a ROW major.
Arrays - storage
Compiled By : Dr. Manamohan Prusty
• The number of subscripts in any array reference must match the array declaration.
• The subscript must always remain within the bounds declared.
• The subscript must be an INTEGER expression
• An array element is undefined until it has a value assigned to it in some manner
• An array may be accessed by its name only (without subscripts) in a few limited
circumstances:
• In a type declaration if a DIMENSION statement is used to set the array bounds
• In a DATA statement which initializes the entire array
• In a READ orWRITE statement which reads in or writes out the entirearray
• as an argument in an external function reference or subroutine cell
• as a dummy argument in an external function or subroutine
Arrays – Points to be noted
Compiled By : Dr. Manamohan Prusty
• REALA(5)
INTEGER, DIMENSION(3,0:3) B
DATAA /1.0, 1.414, 1.732, 2.0,2.236/
DATAB /1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144/
• INTEGER i, j
REAL, DIMENSION(3, 4)C
DO j=1, 4
DO i=1,3
C(i,j) =SQRT(i*j)
ENDDO
ENDDO
WRITE(*, 100) ((C(i, j), j = 1, 4), i=1, 3)
100 FORMAT (4(F10.6, 2x) /)
Arrays – Read andWrite
Compiled By : Dr. Manamohan Prusty
• A statement function is a user defined function which is defined and used in a
program unit. It appears after the type declaration and before the executable
statements.
• Syntax : function_name(dvar1, dvar2, dvar4, …,dvarn) = expression
• Note – function_name is a symbolic name and must be unique within the program
expression may contain constants, variables and array elements or
other functions defined earlier
It may return any of the six (integer, real, double precision, complex,
logical, character) data types
• It is invoked by its name and argument list
Statement Function
Compiled By : Dr. Manamohan Prusty
• REAL Celsius, Fahrenheit, temp
Celsius(Fahrenheit) = 5.0 * (Fahrenheint-32.0)/9.0
WRITE(*,*) ‘Enter the value of temperature in Fahrenheit ?’
READ(*,*) temp
WRITE(*,*) ‘The equivalentCelsius of ‘, temp ,’ Fahrenheit is =‘,Celsius(temp)
Statement Function
Compiled By : Dr. Manamohan Prusty
• Function subprogram (external function) and Subroutine are external
subprograms which may only contain two statements RETURN and SAVE
• Both must end with the END statement
• The external function returns one value while the subroutine may return zero or
more values via an argument list.
• Program units are independent i.e., they contain their own symbolic names and
labels.
• They may call each other but cannot call themselves, either directly or indirectly.
• Information is passed via argument lists or through COMMON Blocks or by using
external files.
Subprogram – Function and Subroutine
Compiled By : Dr. Manamohan Prusty
• Syntax : type FUNCTION f_name(dvar1, dvar2,dvar3,…,dvarn)
• The type designates the data type of the value returned by the external function.
• If the function returns a CHARACTER value then, the length must be specified or
given asCHARACTER*(*).
• The name f_name may be used within the external function as a variable but it
must be assigned a value before the end of subprogram unit
• The function is invoked by using it’s name f_name followed by the arguments
• There can be zero or more arguments of any type, however, the parentheses
must be present even if there are no arguments
Subprogram Function
Compiled By : Dr. Manamohan Prusty
PROGRAM Main
IMPLICIT NONE
INTEGER i, n, nmax
PARAMETER (nmax=10)
REAL a(0:nmax), poly, x
10 CONTINUE
WRITE(*,*) “Enter the value of n”
READ(*,*) n
IF (n .GT. nmax) THEN
WRITE(*,*)”Choose smaller value n<=”,nmax
GOTO 10
ENDIF
WRITE(*,*)”Enter the value of coefficients”
DO i=0,n
WRITE(*,*)”Enter the value of a(“,i,”)”
READ(*,*) a(i)
ENDDO
Subprogram Function - example
WRITE(*,*)”Enter the value of x”
READ(*,*) x
WRITE(*,*),”The value of polynomial at”,x,”=“,poly(a,n,x)
STOP “Program ends here”
END PROGRAM
!Function subprogram for calculation
! poly = a(0) + a(1) x + a(2) x**2 +
of the polynomial
…… + a(n) x**n
REAL FUNCTION poly(a,n,x)
IMPLICIT NONE
INTEGER i, n
REAL a(0:n), x
Poly=a(n)
DO i=n-1,0,-1
poly= a(i) + poly * x
ENDDO
END FUNCTION
Compiled By : Dr. Manamohan Prusty
• Syntax : SUBROUTINE sub_name(dvar1, dvar2,dvar3,…,dvarn)
• The name sub_name is global in nature. So, it may not be used as a variable inside
the subroutine
• The SUBROUTINE is invoked with a CALL statement in the main programunit
CALL sub_name(var1, var2,var3,…,varn)
where var1, var2,var3,…,varn are the actual arguments rather than the dummy
variables above.
• There can be zero or more arguments of any data type which are declared in the
body of the subroutine, however, the parentheses may be omitted if there are no
arguments
Subprogram - Subroutines
Compiled By : Dr. Manamohan Prusty
Subprogram Subroutine - Examples
PROGRAM Main
IMPLICIT
NONE
REAL time, s
INTEGER h, m
10 CONTINUE
WRITE(*,*) “Enter the time in decimal hours”
READ(*,*,END=88) time
IF (time .LT. 0.0) GOTO 88
CALL CONVERT(time, h, m,
s) WRITE(*,20) time, h, m,
s
20 FORMAT(F10.4,’ hrs = ‘,I6,’ h ‘,I2,’ m ‘,F5.2,’ s’)
GOTO 10
88 STOP ‘End of Program’
END PROGRAM
!Subroutine for converting the decimal time to
!Individual hours, minutes and seconds
mins, secs)SUBROUTINE CONVERT(dtime, hrs,
IMPLICIT NONE
INTEGER hrs, mins
REAL dtime, secs
secs = dtime * 3600.0
hrs = INT(dtime)
secs = secs – 3600.0 * hrs
mins = INT(secs/60.0)
secs = secs – 60.0 * mins
END SUBROUTINE
Compiled By : Dr. Manamohan Prusty
• The RETURN statement immediately transfers execution back to the calling
program. It’s Syntax : RETURN without any arguments
• Note – The END statement has the same effect. So, it is unnecessary to include it.
However if you want to put more than one exit point in a subprogram/subroutine
then it becomes necessary
• The SAVE statement is used to preserve the values of local variables. It’s Syntax :
SAVE item1, item2, …, itemn.The items can be variables, array_names or
COMMON blocks but not the dummy arguments or blankCOMMONblocks.
• Without the arguments it saves the values of all allowable items in the procedure.
RETURN and SAVEStatements
Compiled By : Dr. Manamohan Prusty
• The BlankCOMMON block is setup withthe
statement : COMMON variable-list
• and the named COMMON block is declared
by : COMMON /name/variable-list
• Every SUBROUTINE, FUNCTION that uses
the data stored in the COMMON block
must have a similar statement to those
above
• Without the arguments it saves the values
of all allowable items in the procedure.
COMMON Statement
PROGRAM main
INTEGER i
REAL w, x, y,
z COMMON x, y,
i
x = 3.141592; y=1.414;
i=46 CALL SUB(w,x)
…
END
SUBROUTINE SUB(a,
b) INTEGER j
REAL A, B, C,
D COMMON A, B,
j
…
END
Compiled By : Dr. Manamohan Prusty
• It is not necessary to declare named COMMON blocks in the main program
unless they are used there.These namedCOMMON blocks must be exactlythe
same length wherever they appears
• BlankCOMMON blocks must be declared in the main program.These
COMMON blocks need not be the same length in different program units
• Variables in COMMON blocks may be initialized with READ or assignment
statements but not with a DATA statement
COMMON Statement
Compiled By : Dr. Manamohan Prusty
• The EQUIVALENCE statement causes two or more statement items (arrays or
variables) to occupy the same memory space.
• The general form of the statement is
EQUIVALENCE var_list1, var_list2, var_list3, ..., var_listn
• In the above syntax var_listi contains two or more variables or arrays or
mixture of the two.
• It occurs near the beginning of the program unit where type declaration and
other specification statements are present.
EQUIVALENCE Statement
Compiled By : Dr. Manamohan Prusty
• The EXTERNAL statement is used to include the modules containing a
procedure which is omitted.
• Without this the linker will return an error during compilation if the Block data
program is missing as part of the main program.
• The general form of the statement is
EXTERNAL ename1, ename2, ename3, ..., enamen
• In the above syntax enamei is the name of an external function, subprogramor
dummy procedure in an argumentlist
EXTERNAL Statement
Compiled By : Dr. Manamohan Prusty
Fortran Continuation of lines
• Some times if a statement is too long to fit in a single line and it needs to be
continued then it needs the use of + or 1 (any character can be used) as part of the
sixth place. Good practice is to use the plus sign or digits or & .The default maximum
of continuation lines is 99.
• Or you can extent the source line length to 132 characters from the default of up to
72. This is done by using the –e option during compilation whose syntax is
f77 –e file.f
• Example :
WRITE(*,*) "The solutions are x1= ", re , "+ i" , im ,
1
+
" and x2= " , re , "- i" , im ,” and theyare
imaginary complex conjugates"
Compiled By : Dr. Manamohan Prusty
Disk I/O - File OPEN -specifiers
SPECIFIER VALUE OFVARIABLE DATATYPEOFVARIABLE
ACCESS ‘APPEND’,’DIRECT’,’SEQUENTIAL’ CHARACTER
ACTION ‘READ’,’WRITE’,’READWRITE’ CHARACTER
BLANK ‘NULL’,’ZERO’ CHARACTER
ERR Statement Number INTEGER
FORM ‘FORMATTED’,’UNFPRMATTED’,’PRINT’ CHARACTER
FILE * <Filename> or * CHARACTER
FILEOPT ‘NOPAT’, ‘BUFFER=n’,’EOF’ CHARACTER
IOSTAT Error Number INTEGER
READONLY - -
RECL Record Length for DIRECTACCESS INTEGER
STATUS ‘OLD’, ‘NEW’,’UNKNOWN’,’SCRATCH’ CHARACTER
OPEN(<UNIT=>u,SPECIFIER)
Compiled By : Dr. Manamohan Prusty
Disk I/O - File OPENexamples
• 100WRITE(*,* ) ‘Enter the input file name’
READ(*,’(A)’,END=999) FNAME
OPEN(20,FILE=FNAME,STATUS=UNKNOWN,BLANK=‘ZERO’,ERR=100)
• OPEN(8,STATUS='SCRATCH') – It opens a temporary file to act as a scratch file
• Note that - it is forbidden to specify a filename for a scratch file.
Compiled By : Dr. Manamohan Prusty
Disk I/O - File CLOSE - specifiers
SPECIFIER VALUE OFVARIABLE DATATYPEOFVARIABLE
ACCESS ‘APPEND’,’DIRECT’,’SEQUENTIAL’ CHARACTER
ERR Statement Number INTEGER
IOSTAT Error Number INTEGER
STATUS ‘KEEP’, ‘DELETE’ CHARACTER
CLOSE(<UNIT=>u,SPECIFIER)
Examples - CLOSE(27,STATUS=‘DELETE’)
CLOSE (39)
Compiled By : Dr. Manamohan Prusty
Disk I/O - File INQUIRE statement
• INQUIRE statement is useful when you wish to know if a file exists or is already connected or not. It can be
carried out in two ways (i) By UNIT or (ii) By FILE
• Syntax – INQUIRE(UNIT=u or FILE=FILENAME (but not both), SPECIFIER)
SPECIFIER RETURNEDVALUE OFVARIABLE DATATYPE OFVARIABLE
EXIST/OPENED .TRUE. or . FALSE. LOGICAL
NAMED .TRUE. or . FALSE. LOGICAL
ERR Statement Number INTEGER
NAME Returns FILENAME CHARACTER
NUMBER Returns the UNITNUMBER INTEGER
ACCESS Returns SEQUENTIAL or DIRECT CHARACTER
IOSTAT Returns an Error Number INTEGER
FORM Returns FORMATTED/UNFORMATTED CHARACTER
NEXTREC Returns n+1 (n is the rec no. of last record) INTEGER
STATUS ‘OLD’, ‘NEW’,’UNKNOWN’,’SCRATCH’ CHARACTER
BLANK Returns ‘NULL’ or ‘ZERO’ CHARACTER
Compiled By : Dr. Manamohan Prusty
File INQUIRE statement (Example)
last)• INTEGER FUNCTION FREEUNIT(first,
IMPLICIT NONE
INTEGER iunit, first, last
LOGICAL isopen
DO iunit=first, last
INQUIRE(UNIT=inuit, OPENED=isopen)
IF (.NOT. isopen) THEN
freeunit = iunit
RETURN
ENDIF
ENDDO
freeunit = -1
END
• Demo subprogram
that returns the
smallest unit
number that is
currently not in use
Compiled By : Dr. Manamohan Prusty
REWIND and BACKSPACE statements
• REWIND(UNIT, ERR, IOSTAT) statement is used to re-read a sequential
input file from the first record
• BACKSPACE(UNIT, ERR, IOSTAT) statement is used to re-read the
most recently read record
Compiled By : Dr. Manamohan Prusty
FILE Operations - READING andWRITING
• READ/WRITE(UNIT=u, FMT=fmt, IOSTAT=ios, ERR=err, END=s)
• The UNIT=u is unit number that denotes the associated file.
• The FMT=fmt is either FORMATTED or UNFORMATTED.
• The IOSTAT=ios is the I/O status identifier. If successful it returns an
zero value otherwise a non zero value.
• The ERR=err is a label the program jumps to if there is an error.
• The END=s defines which statement label the program jumps to if it
reaches the end of file.
Compiled By : Dr. Manamohan Prusty
Example Program - 1
!Function subprogram for multiplication of matrix
!and a vector
SUBROUTINE mat_vec_mpy(Matrix, n, vecin, vecout)
IMPLICIT NONE
INTEGER n, i, j
REAL, DIMENSION Matrix(n, n), vecin(n), vecout(n)
DO i=1,n
vecout(i) = 0.0
DO j=1,n
vecout(i) = vecout(i) + Matrix(i,j) * vecin(j)
ENDDO
ENDDO
END SUBROUTINE
Compiled By : Dr. Manamohan Prusty
Example Program - 2
!Function subprogram for Fibonacci Series
SUBROUTINE Fib(F,n)
IMPLICIT NONE
INTEGER n, i
REAL F(0:n)
THEN
DO i=0,n
IF (i==0) THEN
F(i)=0
ELSEIF(i==1)
F(i)=1
ELSE
F(i)=F(i-1)+F(i-2)
ENDIF
ENDDO
END SUBROUTINE
Compiled By : Dr. Manamohan Prusty
Example Program - 3
!Function subprogram for Sorting in increasing order
SUBROUTINE sort(num,n)
IMPLICIT NONE
INTEGER n, i, j
REAL num(n), temp
DO i=1,n
DO j=i,n
IF (num(i) > num(j)) THEN
num(i)
= num(j)
= temp
temp =
num(i)
num(j)
ENDIF
ENDDO
ENDDO
END SUBROUTINE
Compiled By : Dr. Manamohan Prusty
AT THEEND
• Have the necessity to use FORTRAN.
• Have a book for quick reference.
• Make some time for practicing it.
• In case of doubts do not hesitate to ask for help.
• Last but not least
Thank you and GoodLuck!
Compiled By : Dr. Manamohan Prusty

Weitere ähnliche Inhalte

Was ist angesagt?

Elementary particles
Elementary particlesElementary particles
Elementary particlesSNS
 
lecture notes heat transfer.pdf
lecture notes heat transfer.pdflecture notes heat transfer.pdf
lecture notes heat transfer.pdfLaggo Anelka
 
Segmentation in Operating Systems.
Segmentation in Operating Systems.Segmentation in Operating Systems.
Segmentation in Operating Systems.Muhammad SiRaj Munir
 
The Message Passing Interface (MPI) in Layman's Terms
The Message Passing Interface (MPI) in Layman's TermsThe Message Passing Interface (MPI) in Layman's Terms
The Message Passing Interface (MPI) in Layman's TermsJeff Squyres
 
superconducting materials
superconducting materialssuperconducting materials
superconducting materials2461998
 
Nmap basics
Nmap basicsNmap basics
Nmap basicsitmind4u
 
Classical mechanics introduction
Classical mechanics   introductionClassical mechanics   introduction
Classical mechanics introductionAmeenSoomro1
 
Magnetostriction and application of ultrasonic waves
Magnetostriction and application of ultrasonic wavesMagnetostriction and application of ultrasonic waves
Magnetostriction and application of ultrasonic wavesPreethiSureshkumar1
 
Presentation for higgs boson
Presentation for higgs bosonPresentation for higgs boson
Presentation for higgs bosonAditi Podder
 
Magnetic materials
Magnetic materialsMagnetic materials
Magnetic materialsNilay Patel
 
Classification of magnetic
Classification of magneticClassification of magnetic
Classification of magneticDhrupal Patel
 
Particle physics - Standard Model
Particle physics - Standard ModelParticle physics - Standard Model
Particle physics - Standard ModelDavid Young
 
DENSITY OF ENERGY STATES
DENSITY OF ENERGY STATESDENSITY OF ENERGY STATES
DENSITY OF ENERGY STATESSathees Physics
 

Was ist angesagt? (20)

Elementary particles
Elementary particlesElementary particles
Elementary particles
 
lecture notes heat transfer.pdf
lecture notes heat transfer.pdflecture notes heat transfer.pdf
lecture notes heat transfer.pdf
 
Segmentation in Operating Systems.
Segmentation in Operating Systems.Segmentation in Operating Systems.
Segmentation in Operating Systems.
 
Shared memory
Shared memoryShared memory
Shared memory
 
Unit 1
Unit 1Unit 1
Unit 1
 
The Message Passing Interface (MPI) in Layman's Terms
The Message Passing Interface (MPI) in Layman's TermsThe Message Passing Interface (MPI) in Layman's Terms
The Message Passing Interface (MPI) in Layman's Terms
 
Free electron in_metal
Free electron in_metalFree electron in_metal
Free electron in_metal
 
superconducting materials
superconducting materialssuperconducting materials
superconducting materials
 
Nmap basics
Nmap basicsNmap basics
Nmap basics
 
Classical mechanics introduction
Classical mechanics   introductionClassical mechanics   introduction
Classical mechanics introduction
 
Advance Quantum Mechanics
Advance Quantum Mechanics Advance Quantum Mechanics
Advance Quantum Mechanics
 
Magnetostriction and application of ultrasonic waves
Magnetostriction and application of ultrasonic wavesMagnetostriction and application of ultrasonic waves
Magnetostriction and application of ultrasonic waves
 
Presentation for higgs boson
Presentation for higgs bosonPresentation for higgs boson
Presentation for higgs boson
 
Ferrites
Ferrites Ferrites
Ferrites
 
Magnetic materials
Magnetic materialsMagnetic materials
Magnetic materials
 
Statistical Mechanics B.Sc. Sem VI
Statistical Mechanics B.Sc. Sem VIStatistical Mechanics B.Sc. Sem VI
Statistical Mechanics B.Sc. Sem VI
 
Classification of magnetic
Classification of magneticClassification of magnetic
Classification of magnetic
 
Particle physics - Standard Model
Particle physics - Standard ModelParticle physics - Standard Model
Particle physics - Standard Model
 
Memory management
Memory managementMemory management
Memory management
 
DENSITY OF ENERGY STATES
DENSITY OF ENERGY STATESDENSITY OF ENERGY STATES
DENSITY OF ENERGY STATES
 

Ähnlich wie FORTRAN Theory and Basic LINUX Fundamentals

Ähnlich wie FORTRAN Theory and Basic LINUX Fundamentals (20)

Linux 4 you
Linux 4 youLinux 4 you
Linux 4 you
 
Distributed File System
Distributed File SystemDistributed File System
Distributed File System
 
UNIX.pptx
UNIX.pptxUNIX.pptx
UNIX.pptx
 
Linux Shell Basics
Linux Shell BasicsLinux Shell Basics
Linux Shell Basics
 
4. linux file systems
4. linux file systems4. linux file systems
4. linux file systems
 
Nguyễn Vũ Hưng: Basic Linux Power Tools
Nguyễn Vũ Hưng: Basic Linux Power Tools Nguyễn Vũ Hưng: Basic Linux Power Tools
Nguyễn Vũ Hưng: Basic Linux Power Tools
 
Linux Introduction (Commands)
Linux Introduction (Commands)Linux Introduction (Commands)
Linux Introduction (Commands)
 
Linux introduction-commands2338
Linux introduction-commands2338Linux introduction-commands2338
Linux introduction-commands2338
 
Linux introduction-commands2338
Linux introduction-commands2338Linux introduction-commands2338
Linux introduction-commands2338
 
intro unix/linux 11
intro unix/linux 11intro unix/linux 11
intro unix/linux 11
 
UNIX Operating System ppt
UNIX Operating System pptUNIX Operating System ppt
UNIX Operating System ppt
 
beginner.en.print
beginner.en.printbeginner.en.print
beginner.en.print
 
beginner.en.print
beginner.en.printbeginner.en.print
beginner.en.print
 
beginner.en.print
beginner.en.printbeginner.en.print
beginner.en.print
 
Introduction to UNIX
Introduction to UNIXIntroduction to UNIX
Introduction to UNIX
 
Linux introduction (eng)
Linux introduction (eng)Linux introduction (eng)
Linux introduction (eng)
 
Introduction to Unix
Introduction to UnixIntroduction to Unix
Introduction to Unix
 
Introduction to linux2
Introduction to linux2Introduction to linux2
Introduction to linux2
 
Programming Embedded linux
Programming Embedded linuxProgramming Embedded linux
Programming Embedded linux
 
Part 03 File System Implementation in Linux
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
 

Mehr von Jyotismat Raul

Presence of Pesticides in Fruits and vegetables
Presence of Pesticides in Fruits and vegetables Presence of Pesticides in Fruits and vegetables
Presence of Pesticides in Fruits and vegetables Jyotismat Raul
 
Project on Carnot Engine
Project on Carnot EngineProject on Carnot Engine
Project on Carnot EngineJyotismat Raul
 
Treatment of Phenolic water using adsorption
Treatment of Phenolic water using adsorptionTreatment of Phenolic water using adsorption
Treatment of Phenolic water using adsorptionJyotismat Raul
 
Project Report on "Fabrication & Characterization of ZnO thin film based on P...
Project Report on "Fabrication & Characterization of ZnO thin film based on P...Project Report on "Fabrication & Characterization of ZnO thin film based on P...
Project Report on "Fabrication & Characterization of ZnO thin film based on P...Jyotismat Raul
 
Project report on LHC " Large Hadron Collider " Machine
Project report on LHC  " Large Hadron Collider " MachineProject report on LHC  " Large Hadron Collider " Machine
Project report on LHC " Large Hadron Collider " MachineJyotismat Raul
 
Project report on Growth of ZnO Nanowire and It's applications as Photodetector
Project report on Growth of ZnO Nanowire and It's applications as PhotodetectorProject report on Growth of ZnO Nanowire and It's applications as Photodetector
Project report on Growth of ZnO Nanowire and It's applications as PhotodetectorJyotismat Raul
 
Project on GPS (Global Positioning System)
Project on GPS (Global Positioning System)Project on GPS (Global Positioning System)
Project on GPS (Global Positioning System)Jyotismat Raul
 

Mehr von Jyotismat Raul (7)

Presence of Pesticides in Fruits and vegetables
Presence of Pesticides in Fruits and vegetables Presence of Pesticides in Fruits and vegetables
Presence of Pesticides in Fruits and vegetables
 
Project on Carnot Engine
Project on Carnot EngineProject on Carnot Engine
Project on Carnot Engine
 
Treatment of Phenolic water using adsorption
Treatment of Phenolic water using adsorptionTreatment of Phenolic water using adsorption
Treatment of Phenolic water using adsorption
 
Project Report on "Fabrication & Characterization of ZnO thin film based on P...
Project Report on "Fabrication & Characterization of ZnO thin film based on P...Project Report on "Fabrication & Characterization of ZnO thin film based on P...
Project Report on "Fabrication & Characterization of ZnO thin film based on P...
 
Project report on LHC " Large Hadron Collider " Machine
Project report on LHC  " Large Hadron Collider " MachineProject report on LHC  " Large Hadron Collider " Machine
Project report on LHC " Large Hadron Collider " Machine
 
Project report on Growth of ZnO Nanowire and It's applications as Photodetector
Project report on Growth of ZnO Nanowire and It's applications as PhotodetectorProject report on Growth of ZnO Nanowire and It's applications as Photodetector
Project report on Growth of ZnO Nanowire and It's applications as Photodetector
 
Project on GPS (Global Positioning System)
Project on GPS (Global Positioning System)Project on GPS (Global Positioning System)
Project on GPS (Global Positioning System)
 

Kürzlich hochgeladen

Pests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdfPests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
Pests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdfPests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdfPirithiRaju
 
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPirithiRaju
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
Bioteknologi kelas 10 kumer smapsa .pptx
Bioteknologi kelas 10 kumer smapsa .pptxBioteknologi kelas 10 kumer smapsa .pptx
Bioteknologi kelas 10 kumer smapsa .pptx023NiWayanAnggiSriWa
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxpriyankatabhane
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxpriyankatabhane
 
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxRESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxFarihaAbdulRasheed
 
User Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationUser Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationColumbia Weather Systems
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingNetHelix
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPirithiRaju
 
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In DubaiDubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubaikojalkojal131
 
Environmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial BiosensorEnvironmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial Biosensorsonawaneprad
 
Call Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 Genuine
Call Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 GenuineCall Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 Genuine
Call Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 Genuinethapagita
 
Davis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technologyDavis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technologycaarthichand2003
 
Good agricultural practices 3rd year bpharm. herbal drug technology .pptx
Good agricultural practices 3rd year bpharm. herbal drug technology .pptxGood agricultural practices 3rd year bpharm. herbal drug technology .pptx
Good agricultural practices 3rd year bpharm. herbal drug technology .pptxSimeonChristian
 

Kürzlich hochgeladen (20)

Volatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -IVolatile Oils Pharmacognosy And Phytochemistry -I
Volatile Oils Pharmacognosy And Phytochemistry -I
 
Pests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdfPests of safflower_Binomics_Identification_Dr.UPR.pdf
Pests of safflower_Binomics_Identification_Dr.UPR.pdf
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
Pests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdfPests of Bengal gram_Identification_Dr.UPR.pdf
Pests of Bengal gram_Identification_Dr.UPR.pdf
 
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)
 
Bioteknologi kelas 10 kumer smapsa .pptx
Bioteknologi kelas 10 kumer smapsa .pptxBioteknologi kelas 10 kumer smapsa .pptx
Bioteknologi kelas 10 kumer smapsa .pptx
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptx
 
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptxRESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
RESPIRATORY ADAPTATIONS TO HYPOXIA IN HUMNAS.pptx
 
User Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationUser Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather Station
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
 
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In DubaiDubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
Dubai Calls Girl Lisa O525547819 Lexi Call Girls In Dubai
 
Environmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial BiosensorEnvironmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial Biosensor
 
Call Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 Genuine
Call Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 GenuineCall Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 Genuine
Call Girls in Majnu Ka Tilla Delhi 🔝9711014705🔝 Genuine
 
Davis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technologyDavis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technology
 
Good agricultural practices 3rd year bpharm. herbal drug technology .pptx
Good agricultural practices 3rd year bpharm. herbal drug technology .pptxGood agricultural practices 3rd year bpharm. herbal drug technology .pptx
Good agricultural practices 3rd year bpharm. herbal drug technology .pptx
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 

FORTRAN Theory and Basic LINUX Fundamentals

  • 1. Skill Enhancement Course Computational Physics : FORTRAN Dr. Manamohan Prusty (Asst. Prof. in Physics) P.G. Dept. of Physics, Government (Autonomous)College, Angul
  • 2. PLAN •PART I – Computers and Linux •PART II – FORTRAN History and structure •PART III – Control statements and Programming Compiled By : Dr. Manamohan Prusty
  • 3. PART I : COMPUTER and LINUX COMMANDS • Computer Hardware • Components • Motherboard • CPU • RAM • Hard disk and Giant MagnetoResistance • UNIX/LINUX File System • Shells and UNIX/LINUX commands • Shell Utilities and text editor Compiled By : Dr. Manamohan Prusty
  • 4. Computer Hardware - Components Source : wikipedia Compiled By : Dr. Manamohan Prusty
  • 5. Motherboard Source : wikipedia Compiled By : Dr. Manamohan Prusty
  • 6. Central Processing Unit (CPU) Source : www.intel.com Compiled By : Dr. Manamohan Prusty
  • 7. Central Processing Unit CPU Components 1) Core 2) Branch predictor 3) Floating Point Unit 4) Level 1 Cache 5) Bus Interface Compiled By : Dr. Manamohan Prusty
  • 8. RANDOM ACCESS MEMORY Random access memory (RAM) is a form of computer data storage that stored data and machine code currently being used. It allows data items to be read and written in almost the same amount of time irrespective of the physical location of data inside the memory. In today’s technology it takes the form of ICs. It is normally associated with volatile type of memory, where the stored information is lost if power is removed. Source : wikipedia Compiled By : Dr. Manamohan Prusty
  • 9. HARD DISK A hard disk is a data storage device that uses magnetic storage to store and retrieve digital information using one or more rapidly rotating disks coated with magnetic material. In hard disks data is accesses in a random-access manner, meaning that individual blocks of data can be stored or retrieved in any order. Hard disks are type of non-volatile storage, retaining stored data even when powered off. Physics Nobel Prize 2007 – Jointly awarded to Albert Fert andPeter Grünberg “for discovery of GiantMagnetoresistance”. Source : wikipedia Compiled By : Dr. Manamohan Prusty
  • 10. Physics Nobel Prize – 2007 (GMR) AlbertFert PeterGrünberg Nanotechnology gives sensitive read-out heads for compact harddisks This year's physics prize is awarded for the technology that is used to read data on hard disks. It is thanks to this technology that it has been possible to miniaturize hard disks so radically in recent years. Sensitive read-out heads are needed to be able to read data from the compact hard disks used in laptops and some music players, for instance. In 1988 the Frenchman Albert Fert and the German PeterGrünberg each independently discovered a totally new physical effect – Giant Magnetoresistance or GMR.Very weak magnetic changes give rise to major differences in electrical resistance in a GMR system.A system of this kind is the perfect tool for reading data from hard disks when information registered magnetically has to be converted to electric current. Soon researchers and engineers began work to enable use of the effect in read-out heads. In 1997 the first read-out head based on the GMR effect was launched and this soon became the standard technology. Even the most recent read-out techniques of today are further developments ofGMR. A hard disk stores information, such as music, in the form of microscopically small areas magnetized in different directions.The information is retrieved by a read-out head that scans the disk and registers the magnetic changes. The smaller and more compact the hard disk, the smaller and weaker the individual magnetic areas. More sensitive read-out heads are therefore required if information has to be packed more densely on a hard disk. A read-out head based on theGMR effect can convert very small magnetic changes into differences in electrical resistance and there- fore into changes in the current emitted by the read-out head.The current is the signal from the read-out head and its different strengths represent ones and zeros. TheGMR effect was discovered thanks to new techniques developed during the 1970s to produce very thin layers of different materials. If GMR is to work, structures consisting of layers that are only a few atoms thick have to be produced. For this reasonGMR can also be considered one of the first real applications of the promising field of nanotechnology. Source :: www.nobelprize.org Compiled By : Dr. Manamohan Prusty
  • 11. Operating Systems • It is a system software that • Manages computer hardware and softwareresources • Acts as a resource manager for various components • Acts as an intermediary between hardware functions such as various I/O devices, memory allocations and the computer programs • Provides common services for computer programs • Various type of operating systems are • Microsoft windows by Microsoft corp. • MacOS by AppleInc. • Varieties of Linux (these are dominant in the server and supercomputing sectors) Source :wikipedia Compiled By : Dr. Manamohan Prusty
  • 12. Unix/Linux OS – DevelopmentHistory Source : wikipedia Compiled By : Dr. Manamohan Prusty
  • 13. Unix/Linux OS -History Source : wikipedia Compiled By : Dr. Manamohan Prusty
  • 14. Unix/Linux OS – Filesystem Source : wikipedia /home (saved personal files) /proc (virtual file system providing process and kernel information) /bin (Essential command libraries – ls, cp, …) /root (home for root user) /boot (Boot loader files - kernel, initrd etc) /run (info on running system) /dev (Essential device files) /sbin (Essential system binaries) /etc (system-wide configuration files) /srv (site specific data forservers) /sys (contains info on devices, drivers etc) /lib (files essential for /bin and /sbin) /tmp (temporary files) /media (mount points for removable media) /usr (user utilities and applications) /mnt (Temporary mounted file system) /var (variable files which change frequently) /opt (Optional application packages) Primary root Compiled By : Dr. Manamohan Prusty
  • 15. Unix/Linux Commands - Specialcharacters • . present working directory • .. directory above the present directory • / divider between directories • * a wild card that matches any sequence of characters • ? a wild card that matches any single character • ; separates Linux commands on a single line • ! related to history (past typed) commands • ~ location of main home directory • & causes a command to run in background • | routes the output from a command to the next command • > routes the output from a command to create a new specified file • >! same as above but if file already exists then replaces the file • >> routes the output from a command to append to a specified file • < routes a specified file to be input to a command • SPACE acts as field separators Compiled By : Dr. Manamohan Prusty
  • 16. Unix/Linux Commands - Moving around (cd) • cd • cd ~ • cd ../ • cd ~/dir • cd ../../ • cd ../dir change directory to home directory same as above change directory one level up change to directory dir below your home directory change directory two level up go up one directory and then down into directory dir Compiled By : Dr. Manamohan Prusty
  • 17. Unix/Linux Command – Exploring around (ls - list) • ls • ls -a • ls -l • ls -s • ls –la list - location and/of filename info list all entries including normally hidden files (that starts with a .) list in long format (it include time of last modification, size, group, owner etc) give size in blocks it combines the above flags –l and –a (In fact you can combine as many flags as possible) Compiled By : Dr. Manamohan Prusty
  • 18. Unix/Linux Command – ls –l and ls examples • ls –l type : d (directory) - (0rdinary) l (link) permissions : r (read) w (write) x (execute) size in byte and name is the name of the file • ls .. • ls ~ Lists what is in the directory directly above the current directory Lists what is in the home directory Compiled By : Dr. Manamohan Prusty
  • 19. Unix/Linux – More commands • more location/filename display the contents of a file one page at a time on the screen: pressing spacebar goes to the next page and b back a page • cat location/filename • head location/filename • wc location/filename • tail location/filename • file location/filename • vi location/filename • emacs location/filename scroll the whole file to the screen displays the first 10 lines of a file word count : displays the number of words, lines and characters in a file displays the last 10 lines of a file displays the type of file if determinable edit the file with vi (VIsual editor) open the file for editing in emacs editor. Compiled By : Dr. Manamohan Prusty
  • 20. Unix/Linux – More commands • mkdir dirname • pwd • cp loc1/file1 loc2/file2 • mv loc1/file1 loc2/file2 • rm location/filename • rmdir dname • rm –i filename make a directory with name dirname displays the present working directory copies the file1 from loc1 directory to loc2 directory and stores it with a new file name file2 moves the file1 from loc1 directory to loc2 directory and stores it with a new file name file2 removes the file named filename from location directory removes the directory names dname removes the file named filename interactively Compiled By : Dr. Manamohan Prusty
  • 21. Unix/Linux – More commands • df • du –ks ~username finds out how much space is on mounted disks finds out how much space (in KB) is used by the user usename list previous commands execute the previous command execute command 3 • history • !! • !3 • chmod <options permissions> filename Changes the permission of filename (which can be a file or directory as per given <options> [u=user, g=group, o=other, a=all]. Permissions can be read(r), write(w), execute(x) with a + sign for addition and a – sign forremoval) • Caution/Warning - Example : chmod go-r myprog.f chmod u+xmyprog.f Never give everyone write permissions Compiled By : Dr. Manamohan Prusty
  • 22. Unix/Linux – Piping and redirection commands • Piping is used to send the output of a command to another command • ls –l | more • ls –l | lp It pipes the output of ls –l command to the more command It sends the results of ls –l to the printer • Redirection (<,>,>>) deals with input and output from files • mail username@mainaddress < filename It takes the file filename and make it the input to the mail command • ls –l > filename It does the long listing (ls –l) and writes the output to filename • ls –l >> filename It appends the output of ls –l command to end of the file filename • a.out < infile > outfile a.out gets the input from infile and sends the output to outfile Compiled By : Dr. Manamohan Prusty
  • 23. Unix/Linux – Killing a process • If a program is running in the foreground type Ctrl-c (hold the control keyand press c) to kill the foreground program • If the process is running in the background then open a shell/terminal and type ps –elf It returns a list of processes you are running.The first column inthis list is the Process ID (PID) number.Then use kill 1234 to kill the process having PID number 1234 ps –elf | grep username Returns the processes run by user username Compiled By : Dr. Manamohan Prusty
  • 24. PART II : FORTRAN - Basic Overview • History and development of FORTRAN • Basic elements of FORTRAN • Layout of FORTRAN program and programexecution • Operators • Expressions • Input/Output • Keywords • Statements Compiled By : Dr. Manamohan Prusty
  • 25. FORTRAN : John Backus (1924-2007) and IBM 704 Compiled By : Dr. Manamohan Prusty
  • 26. FORTRAN : History • John Backus (3rd Dec. 1924 – 17th Mar. 2007) a chemistry major in University ofVirginia (1943), flunked out after second semester, enrolled intoarmy • Began medical training at Haverford college - ended in nine months • Moved to NewYork city and trained as a radiotechnician • Graduated from ColumbiaUniversity with a bachelor's degree in 1949 anda master's degree in 1950 – both in mathematics • Joined IBM in 1950 and worked on the project SSEC (Selective Sequence ElectronicCalculator) • In 1953, he developed the language speedcoding – the first high level software developed for IBM 701 computer • In 1954, Backus assembled a team to develop FORTRAN 0(for IBM 704 computer – the first high level programming language for broad use. Compiled By : Dr. Manamohan Prusty
  • 27. FORTRAN : History • Stands for `IBM Mathematical FORmulaTRANslation System’ – abbreviated to “FORmula TRANslation” - designed for use in scientific and engineering applications as a friendly alternative to AssemblyLanguages • FORTRAN I Compiler (1957) was the first optimizing compiler – cut development time from 2 weeks to 2 hours • By 1958 over 50% of softwares was inFORTRAN • FORTRAN II – Independent compilation with bugfixes • FORTRAN III –Was developed but never widelydistributed • FORTRAN IV – ANSI standard 1966 with explicit type declarations, logical (IF)statements • FORTRAN77 – became new standard with character string handling, Logical Loop statements and IF with ELSE (optional)statements • Originally written as FORTRAN - all capitals upto FOTRAN77, later modified to title capital for Fortran 90 onwards Compiled By : Dr. Manamohan Prusty
  • 28. FORTRAN : History • Fortran 90 (1991) – FORTRAN77 was revised and modernized to continue its long history as a scientific and engineering programming language, included modules, structures etc • Fortran 95 – minor tweaks to Fortran90 • Fortran 2003 – More improvements and was implemented by compiler companies. Includes object oriented support and interoperability with C programming language • Fortran 2008 (2010) – Includes much more advanced features such as submodules, coarrays, complex arguments to trigonometric function etc. Compiled By : Dr. Manamohan Prusty
  • 29. FORTRAN I – some statements • IF <expression> n1, n2, n3 • DO n1 variable = m1, m2, m3 n1CONTINUE • READ n1, List • WRITE TAPE i, List • FORMAT(specification) • REWIND Compiled By : Dr. Manamohan Prusty
  • 30. IBM 704 Fortran manual, 1956 Compiled By : Dr. Manamohan Prusty
  • 31. FORTRAN77Syntax • First six columns must be spaces, unless it is a comment • Comments starts with a ! orC • Program starts with PROGRAM <name> and stops with END PROGRAM • Lines can only be seventy-two characters long • No semi-colons after each line • A newline is a statement terminator • Always put IMPLICIT NONE right after the PROGRAM line – It prevents implicit variable declaration (all constants, variables and arrays starting with the letters I, J, K, L, M and N are automatically taken to be INTEGER type) Compiled By : Dr. Manamohan Prusty
  • 32. FORTRAN77 – A Typical ProgramLayout c234567 PROGRAM MYPROGRAM STOP END Program Options Declaration of Variables MAIN CODE Compiled By : Dr. Manamohan Prusty
  • 33. FORTRAN77 – A Typical ProgramLayout c234567 PROGRAM MYPROGRAM STOP END Program Options Declaration of Variables MAIN CODE The first seven columns of the program code are reserved for special functions – most lines of code begin on the seventh column Compiled By : Dr. Manamohan Prusty
  • 34. FORTRAN77 – A Typical ProgramLayout c234567 PROGRAM MYPROGRAM STOP END Program Options Declaration of Variables MAIN CODE This line identifies the code as a program (instead of, say, a subroutine) and gives it the name MYPROGRAM. Compiled By : Dr. Manamohan Prusty
  • 35. FORTRAN77 – A Typical ProgramLayout c234567 PROGRAM MYPROGRAM STOP END Program Options Declaration of Variables MAIN CODE All the variables used in the code have to be declared at the top, before any main code could be executed Compiled By : Dr. Manamohan Prusty
  • 36. FORTRAN77 – A Typical ProgramLayout c234567 PROGRAM MYPROGRAM STOP END Program Options Declaration of Variables MAIN CODE Here is where all the magic (read, write, calculations etc) of your program happens Compiled By : Dr. Manamohan Prusty
  • 37. FORTRAN77 – A Typical ProgramLayout c234567 PROGRAM MYPROGRAM STOP END Program Options Declaration of Variables MAIN CODE This identifies the end of the program. Compiled By : Dr. Manamohan Prusty
  • 38. FORTRAN77 – A More complicated programLayout PROGRAM MYPROGRAM Options Declaration of Variables MAIN CODE CALL MYSUBROUTINE MAIN CODE STOP END PROGRAM SUBROUTINE MYSUBROUTINE Options Declaration of Variables MAIN CODE RETURN END SUBROUTINE Compiled By : Dr. Manamohan Prusty
  • 39. FORTRAN77 – A More complicated program Layout PROGRAM MYPROGRAM Options Declaration of Variables MAIN CODE CALL MYSUBROUTINE MAIN CODE STOP END PROGRAM SUBROUTINE MYSUBROUTINE Options Declaration of Variables MAIN CODE RETURN END SUBROUTINE Being able to trace the flow of information is by far the most important thing to learn about programming, in Fortran or in any other language. You will eventually have to write codes that is not only error free but also should be able to perform complicated functions and is readable to someone else who wishes to use it. Compiled By : Dr. Manamohan Prusty
  • 40. Example : A Demo Program to calculate the sum of few numbers and their average The numbers are input from the keyboard. PROGRAM average IMPLICIT none ! Type variables. REAL :: indata, sum, avg INTEGER n, i ! Prompt for the number of numbers to be averaged. PRINT *,"Enter the number of numbers to be averaged." READ *,n sum = 0.0 DO i = 1, n !Loop goes over the number of data ! Prompt for and enter a number. PRINT *,"Enter a value for the number" READ *,indata sum = sum + indata ! Add number to total. END DO avg = sum/real(n) ! Calculates the average. PRINT*,“Sum =”,sum,“Average = ",avg !Prints the results. STOP END PROGRAM Compiled By : Dr. Manamohan Prusty ! program that sums and averages a series of numbers. !
  • 41. Compiling a FORTRAN Program • First edit the program using your favorite editor. (Note – while editing the program, all program codes must start from 7th column except the comments) • Save the program with a filename file.f (Note - the extension of the filename is .f) • Enter the command f77 –o file.exe file.f or g77 –o file.exe file.f • Then execute the command ./file.exe on the command prompt Compiled By : Dr. Manamohan Prusty
  • 42. Character sets • Character sets : Upper and lower case letters (A - Z and a -z), Numerals (0 - 9) • Special characters : . Decimal point, () Parenthesis, = Equal, + Plus, - Minus, *Asterisk, / Slash, , Comma, ‘’Apostrophe, ! Exclamation • Symbolic names : - can be any number of characters long (consisting of letters, digits, the dollar $ and the underscore _ sign), generally starts with a letter (never with numerals, the dollar sign or the underscore sign) • For any single program – different entities such as Entry points, Functions, Main program, Subroutines, Common blocks, Subprograms cannot havesame symbolic names • Cannot change the value of parameters within functions Compiled By : Dr. Manamohan Prusty
  • 43. Constants and their types • Constants are data whose values do not change during the program unit • Three general type of constants : Arithmetic, Logical andCharacter • Arithmetic constants : Complex, Real, Integer, Binary,Octal, Hexadecimal etc (can be signed or unsigned) • Examples : Integer constants - +199, -2147483648, 0 • Real constants - +32.0, -12.34, 1.6E-9,7D3, • Other constants - DATAn1 /B ‘10110101’/, n2 /O ‘37’/, n3 /X ‘1f’/ • Logical constants : .TRUE. and .FALSE. (only two types) • PARAMETER (T=.TRUE.,F=.FALSE.) • Character Constants : a string of characters enclosed within apostrophes or quotes • Examples : ‘abc’, “can’t”, ‘’ (Null character) • character*1 x / ‘a’/, y / ‘’/,z / ‘ b’/ Compiled By : Dr. Manamohan Prusty
  • 44. Constants and their types (more examples) • CHARACTER :: ‘FILENAME’ • INTEGER :: 3, -9999, 1e10 • Must be in the range (-2147483648, 2147483647). • REAL:: 3.3, -9999., 1.5e8, 1e-3 • Must be in the range (1.175494E-38, 3.402823E+38) • REAL*8 :: 6D2, -25.3D-7 • Must be in the range (2.225074D-308, 1.797693D+308) • COMPLEX:: (1,-2) or (1.3,0.4) • LOGICAL:: .TRUE. and .FALSE. Compiled By : Dr. Manamohan Prusty
  • 45. Variables and their types • A symbolic name paired with a storage location. It can have a value. • Mainly of four types - real, integer, character, logical • Examples - REAL :: x, y, z=1.414 INTEGER :: a, b=1, c CHARACTER :: name *20, college_name=“Govt (Auto)College” LOGICAL :: logical1=.TRUE., logical2=.FALSE.,T,F • Upper case and lower case are not significant as the compiler converts them all to lower case during compilation.Thus shx = 5 and SHX=5 areequivalent • Standard FORTRAN Joke, “GOD is REAL unless declared INTEGER”. Compiled By : Dr. Manamohan Prusty
  • 46. Operators : Arithmetic and Logical • Arithmetic operators : ** Exponentiation, * Multiplication, / Division, + Addition or Unary plus, - Subtraction or Unaryminus • Among the above the precedence of operations is from left to right except when parentheses are involved. • Calculations are carried out from right to left except in case of parenthesis where calculations are carried out from inside out • Examples :: 2+3, x**2, x*y, -z, 29.5/8, x**3+5*(x*y+y*z+z*z)+x/y-z+0.2 • Logical operators : Conjunction operator -X .AND.Y (BothX andY are true) Disjunction operator –X .OR.Y (EitherX orY or both are true) Compiled By : Dr. Manamohan Prusty
  • 47. Operators : Type conversion and Mixed modeArithmetic Expression type Output type INTEGER / INTEGER INTEGER INTEGER * REAL REAL INTEGER / REAL REAL INTEGER + or – REAL REAL REAL or INTEGER * DOUBLE DOUBLE PRECISION Compiled By : Dr. Manamohan Prusty
  • 48. Operators : Relational , Character andAssignment • Relational operators : .LT.Less than (<), .GT.Greater than (>), .LE. Less than or equal (<=), .GE.Greater than or equal (>=), .EQ. Equal (==), .NE. Not equal (/=) • Character operator : Concatenation operator - // Examples - a//b (a, b are characters), ‘file’// ‘name’ • Assignment operator : the equal sign (=) is the assignment operator. Comes in the form variable = expression Examples – DISC = B**2-4*A*C x1 = (-B +SQRT(DISC))/(2*A) x2 = (-B -SQRT(DISC))/(2*A) Compiled By : Dr. Manamohan Prusty
  • 49. Expressions • An expression consists of constants, variables, operators, parentheses, function references and specific rules for computing a value • Expressions can be arithmetic, logical, character or assignment • A constant expression consists of explicit constants and parameters and the FORTRAN operators • Examples : • PARAMETER (L=29), (B=15),(P=3.14159), (C='along the ') • PARAMETER (PR=(L+B)*2,V=4.0*P/3.0,S=C//'riverrun') • LOGICALT,F • K = 66 * 80 ;VOLUME =V*10**3 • DO i = 1, 20*3 • T = .TRUE.; F=T .AND. 3 .LT.5/2 Compiled By : Dr. Manamohan Prusty
  • 50. Expressions • Examples of few arithmetic and logical expressions • x, 3.0, x+3.0, (2**2)**3 = 2**6 • x = 1.0 + 3 * (7/4) – 4* (7.0/3.0) • 2**(2**3) • p = w/x/y/z • q =w*x/y*z • x==y =2**8 = w/(x*y*z) = w*(x/y)*z = .TRUE. or .FALSE. Compiled By : Dr. Manamohan Prusty
  • 51. Predefined Functions – Data TypeConversion Function Description INT(x) Convert to INTEGER NINT(x) Convert to nearest integer REAL(a) Convert to REAL DBLE(x) Convert to DOUBLE PRECISSION CMPLX(x,y) Convert to COMPLEX DCMPLX(x,y) Convert to DOUBLECOMPLEX CHAR(x) Convert to CHARACTER Compiled By : Dr. Manamohan Prusty
  • 52. Predefined Functions - CHARACTER andCOMPLEX Function Description LEN(char) Length of character entry (char) INDEX(string, substring) Index of substring within a string i.e., position of first occurrence of substring as a substring in string ICHAR(A) ASCII value of a single byte character argument Function description IMAG(z) Imaginary part of complex number z REAL(z) Real part of complex number z CONJG(z) Complex Conjugate of complex number z CHARACTER Functions Complex Functions Compiled By : Dr. Manamohan Prusty
  • 53. Predefined Functions - Mathematical andTrigonometric Function Description MAX(x,y) Maximum value MIN(x,y) Minimum value ABS(x) Absolute value DIM(x,y) Positive difference MOD(x,y) Modulus or remaindering SIGN(x,y) Transfer of sign DPROD(x,y) Double precision product of reals SQRT(x) Square root EXP(x) Exponential LOG(x) Natural logarithm (base e) LOG10(x) Common logarithm (base 10) Function description SIN(x) / SIND(x) Sine (x) / Sine (degrees) COS(x) / COSD(x) Cosine (x) / Cosine(degrees) TAN(x) /TAND(x) Tangent (x) / Tangent(degrees) ASIN(x) / ASIND(x) Arcsine (x) / Arcsine(degrees) ACOS(x) / ACOSD(x) Arccosine (x) / Arccosine(degrees) ATAN(x) / ATAND(x) Arctangent (x) / Arctangent(degrees) ATAN2(x,y) Arctangent result between [–π : π] SINH(x) Hyperbolic sine (x) COSH(x) Hyperbolic cosine (x) TANH(x) Hyperbolic tangent (x) Mathematical Functions Trigonometric Functions Compiled By : Dr. Manamohan Prusty
  • 54. Input andOutput • Twokinds of I/O – Formatted, Unformatted • Format specifiers for Formatted I/O • A - text string • D - double precision numbers, exponent notation • E - real numbers, exponent notation • F - real numbers, fixed point format • I - integer • L – Logical value (T or F) • X - horizontal skip (space) • / - vertical skip to newline • T –Tabspace to certaincolumn • D, E and F have the general syntax Dw.d , Ew.d , Fw.d (w denotes the field width and d denotes the number of significant digits) • A, I andT have the general syntax Aw, Iw andTw(w denotes the fieldwidth) Compiled By : Dr. Manamohan Prusty
  • 55. Input and Output – Formatted - examples • General syntax – READ(unit,format) list WRITE(unit,format) list • Example : REAL *, X/1.23D0/, Y/43.D0/ INTEGER *, J=16 WRITE(6,203) J, X, Y 203 FORMAT(2x, I3/’X=‘,T7,F5.2/D8.2) • If the field is narrow then the FORTRAN library prints only asterisks • Output on screen 16 X= 1.23 0.43D+02 Compiled By : Dr. Manamohan Prusty
  • 56. Input and Output - File operations OPEN(unit=n, FILE=‘filename’,FORM=‘formatted’,ACCESS=‘DIRECT) •Modes of FileAccess : Sequential (default) and Direct •Types of Files : External file – resides on a physical peripheral device such as disk, usb drive etc Internal file – It is a location in main memory, is of character type. It is either a variable, a substring, array, array element, a field of structured record. Compiled By : Dr. Manamohan Prusty
  • 57. Keywords within the statements • In FORTRAN most statements begin with a keyword; the exceptions are the statement function and assignment statements • Keywords of FORTRAN77 are ASSIGN, BACKSPACE, BLOCK DATA,CALL, OPEN, CLOSE, INQUIRE,COMMON, DATA, DIMENSION, DO, ENDDO, CONTINUE, IF,THEN, ELSE, ELSEIF, ENDIF, ENDFILE, ENTRY, EQUIVALENCE, EXTERNAL, FORMAT, FUNCTION, SUBROUTINE, PROGRAM, GOTO, IMPLICIT, INTRINSIC, PARAMETER, PAUSE, PRINT, READ,WRITE, SAVE, REWRITE, REWIND, STOP,END, FILE etc Compiled By : Dr. Manamohan Prusty
  • 58. Executable statements • Executable Statements : It specifies actions and form an execution sequence in a program.The following are executablestatements • Arithmetic, logical and assignment statements • UnconditionalGOTO, assigned GOTO and computedGOTOstatements • Arithmetic and Logical IF statements • BLOCK IF,ELSEIF, ELSE and ENDIF statements • CONTINUE, PAUSE and STOP statements • DO, ENDDO and END statements • READ,WRITE and PRINTstatements • CALL and RETURN statements • REWIND, BACKSPACE, ENDFILE,OPEN,CLOSE and INQUIREstatements Compiled By : Dr. Manamohan Prusty
  • 59. Non-executable statements • Non-executableStatements :These are not part of the executionsequence. They specify characteristics or attributes such as type and size, arrangements or order, editing instructions, entry points within subprograms, statement functions, program units etc.The following are non-executable statements • PROGRAM, FUNCTION, SUBROUTINE, ENTRY and Block DATAstatements • DIMENSION,COMMON, EQUIVALENCE, IMPLICIT, PARAMETER, EXTERNAL, INTRINSIC and SAVEstatements • INTEGER, REAL, DOUBLE PRECISION,COMPLEX, LOGICAL and CHARACTER type statements • DATAand FORMAT statements Compiled By : Dr. Manamohan Prusty
  • 60. PART III : Control Statements and Programming • Logical expressions and type of logic • BranchingStatements • JumpingStatements • LoopingStatements • Subscripted variables • Functions andSubroutines • Disk I/OStatements • File operations Compiled By : Dr. Manamohan Prusty
  • 61. Logical operators • Logical expression - sequence of one/more logical operands and/or operators • Two logical operators cannot appear twice unless the second is .NOT. operator Operator Standard Name Precedence .NOT. Logical Negation Highest .AND. LogicalConjunction .OR. Logical Disjunction (InclusiveOR) .NEQV. Logical Nonequivalence Lowest .XOR. Logical ExclusiveOR Lowest .EQV. Logical Equivalence Lowest Operator Precedence Arithmetic Highest Character Relational Logical Lowest Compiled By : Dr. Manamohan Prusty
  • 62. Logical variable and expressions Syntax : Variable =Expression Expression Meaning X .AND.Y Both X and Y aretrue X .OR.Y Either X orY or both are true X .NEQV.Y X and Y are not both true and not bothfalse X .XOR.Y Either X orY is true, but not both X .EQV.Y X and Y are both true or bothfalse .NOT.X Logical negation Compiled By : Dr. Manamohan Prusty
  • 63. Types of Logic • Sequential Logic – Sequential logic is a type of logic whose output depends not only on the present value of its input but also on the sequence of past inputs, the input history. • Selection Logic - In a selection logic, a question is asked, and depending on the answer, the program takes one of two courses of action, after which the program moves on to the next event. • Repetition Logic - Repetition Logic repeats a sequence of test steps a number of times while or until a user-defined condition is true.The condition used in repetition logic compares two values and returns a value based on the comparison. Compiled By : Dr. Manamohan Prusty
  • 64. Branching Statements (IF) • Logical IF • Arithmetic IF • Block IF • ELSEIF • Nested BlockIF • SELECTCASE Compiled By : Dr. Manamohan Prusty
  • 65. Logical IF • The Logical IF is a single line statement only • Syntax : IF (logical expression) executable statement • If the logical expression is true then execute the executable statement • Example : !Program for checking if a given number is odd • PROGRAM odd INTEGER x, y,rem PRINT*, “Enter the value of number” READ (5,*) x y=x/2; rem = x – 2*y IF (rem .EQ. 1)WRITE (6,*) x, “is odd” END PROGRAM Compiled By : Dr. Manamohan Prusty
  • 66. Arithmetic IF • The Arithmetic IF is a three way arithmetic conditional statement • Syntax : IF (arithmetic expression) negative, zero, positive • If the arithmetic expression is negative then execute the negative label statement, if it is zero then execute the zero label statement and if it is positive then execute the positive label statement • It was declared obsolescent (no longer being used even though it can work) in Fortran 90 • Example : DISC = B*B - 4*A*C IF (DISC) m1, m2, m3 m1 negative condition statement m2 zero condition statement m3 positive condition statement Compiled By : Dr. Manamohan Prusty
  • 67. • The Block IF statement is a more general version of simple Logical IF statement and can take several forms depending on the complexity of the decisions. If output depends on several conditions repeatedly then ELSEIF statement is used. • Syntax : Simplest Form - IF (logical expression)THEN executable statement ENDIF Form 2 : IF (logical expression) THEN executable statement1 ELSE executable statement2 ENDIF Block IF, ELSEIF and Ladder statements General Form : IF (logical expression1) THEN executable statement1 ELSEIF (logical expression2) THEN executable statement2 ELSEIF (logical expression3) THEN executable statement3 … ELSE executable statement ENDIF Compiled By : Dr. Manamohan Prusty
  • 68. • Nesting refers to the inclusion of one control within another control. Thus one can create one Block IF construct within another Block IF. In this case both the IF statements will not overlap, rather one IF statement will contain the other IF construct. • Example : A 𝑥2 + B 𝑥 + C = 0, solution 𝑥 = − 𝐵 ± 𝐵2 − 4 𝐴 𝐶 2 𝐴 IF (A .NE. 0.0) THEN DISC = B**2 – 4*A*C IF (DISC .GT. 0.0) THEN !Level1 IF statement !Calculates the Discriminant !Level2 IF statement inside the level1 IF statement WRITE(*,*) “Roots are real and distinct” ELSEIF (DISC .LT. 0.0) THEN WRITE(*,*) “Roots are complex conjugate” ELSE WRITE(*,*) “Solutions are real andidentical” ENDIF ELSE WRITE(*,*) “The equation is a linear equation and not a quadraticone” ENDIF Nested Block IF Compiled By : Dr. Manamohan Prusty
  • 69. Arithmetic IF vs Block IF - Equivalence • DISC = B*B-4*A*C IF (DISC) m1, m2, m3 m1 negative condition statement m2 zero condition statement m3 positive condition statement • DISC = B**2-4*A*C IF (DISC .LT. 0) THEN GOTO m1 ELSEIF (DISC .EQ. 0) THEN GOTO m2 ELSE GOTO m3 ENDIF m1 negative condition statement m2 zero condition statement m3 positive condition statement Block IFConstructArithmetic IFConstruct Compiled By : Dr. Manamohan Prusty
  • 70. SELECT CASE • SELECT CASE is used to execute a set of multi-alternative selection criterions. • Syntax : SELECT CASE (selector) • • • • • • • • CASE (list_1) statement1 CASE (list_2) statement2 … CASE DEFAULT default statement ENDSELECT Note - Here selector can be an integer, character or logical expression.The list_i is a list of one or more possible values of the selector index.The DEFAULT option in a CASE constructor can be omitted. Compiled By : Dr. Manamohan Prusty
  • 71. SELECT CASE - Example • SELECTCASE(points) CASE (:50) WRITE(*,*) “You need to practice more” CASE (50:80) WRITE(*,*) “You have tried well but not enough” CASE (80:90) WRITE(*,*) “You just missed the top list” CASE DEFAULT WRITE(*,*) “Congratulations :You made to the toplist” ENDSELECT Compiled By : Dr. Manamohan Prusty
  • 72. Looping : DO – CONTINUEstatements • Loop allows that a block of statements be executed repeatedly without actually writing them down numerous times. • Syntax : DO label variable = initial, final, step-size statement1 statement2 …… label CONTINUE • Note – 1.The loop variable can be a variable of typeREAL, INTEGER or DOUBLE PRECISSION but not an array element 2. If the step size is unity (one), then it can be omitted as part of the DO statement Compiled By : Dr. Manamohan Prusty
  • 73. DO – WHILELoop DOWHILE (logical expression) statement1 statement2 …… ENDDO • The DO –WHILE Loop allows a block of statements beexecuted repeatedly until the specifiedWHILE condition istrue. • Syntax :WHILE (logical expression)DO statement1 statement2 …… ENDDO • Note – DO –WHILE Loop is not part ofANSI FORTRAN77.So the correct way is to use IF and GOTOstatements Compiled By : Dr. Manamohan Prusty
  • 74. • WHILE (logical expression) DO statement1 statement2 …… ENDDO DO –WHILE vs IF – GOTOstatements • label IF (logical expression)THEN statement1 statement2 …… GOTO label ENDIF Example : i = 0 100 IF (x .GE. 0D0) THEN x = x - SQRT(x) i = i + 1 GOTO 100 ENDIF Compiled By : Dr. Manamohan Prusty
  • 75. DO-UNTIL Loop label CONTINUE statement1 statement2 …… IF (logical expression) GOTO label • The DO – UNTIL Loop keeps the termination criterion at the end instead of at the beginning. • Syntax : DO statement1 statement2 …… UNTIL (logical expression) • Note – UNTIL Loop is also not part ofANSI FORTRAN77. Sothe correct way is to use IF and GOTOstatements Compiled By : Dr. Manamohan Prusty
  • 76. DO-ENDDO Loop • The DO – ENDDO Loop replaces the DO - CONTINUEloop. DO label variable = initial, final, step-size statement1 statement2 …… label CONTINUE DO variable = initial, final, step-size statement1 statement2 …… ENDDO loop1: DO statements …… ENDDO loop1 Uncountable DO-ENDDO statement. It continues indefinitely until an exit path is found. Normally the exit route is created using the EXIT or GOTO commands. Here loop1: corresponds to the DO-ENDDO construct name which can be optional. Compiled By : Dr. Manamohan Prusty
  • 77. • When a CYCLE statement is encountered inside a DO loop, then one single DO loop is prematurely terminated and execution continues with the next loop. • Syntax : DO i = 1, 100 statement1 IF (expression)THEN ! Skip the statement2 block when expression is trueCYCLE ENDIF statement2 ENDDO CYCLE Statement Compiled By : Dr. Manamohan Prusty
  • 78. • An implied DO loop provides a fast way of listing many items.These items, depending on the place where an implied DO is used, can be variables, expressions or even implied DO loops (nested implied do loops). • Syntax : (o-1, o-2, …, o-n, var = initial, final, step) • It means for each value of the do variable var, all objects (o-1, o-2, …,o-n) are listed once. Note that the adjacent objects are separated by commas. • Example : (i*a(i), b(i+1), i=1,3) a(1), b(2), 2a(2), b(3), 3a(3), b(4) • (i, (b(j), j=1,3),i=4,6) 4, b(1), b(2), b(3), 5, b(1), b(2), b(3), 6, b(1), b(2), b(3) • ((a(i)*b(j), j=1,2), i=1,3) a(1)b(1),a(1)b(2),a(2)b(1),a(2)b(2),a(3)b(1),a(3)b(2) • Note –The inner and outer loops are not interchangeable • -These implied DO lists can also appear within the variable lists on I/O statements such as PRINT, READ andWRITE. Implied DO Loop Compiled By : Dr. Manamohan Prusty
  • 79. • READ(*,*) (x(i), i=1,5) • WRITE(*, 50) ((Matrix(i,j),i=1,5),j=1,5) • 50 FORMAT(‘ ‘, 5F10.4, /) • WRITE(*, 80) (i, X(i),Y(i),i=1,101,5) 80 FORMAT(1X, I3,2x,2F10.6) • WRITE(*,150) (i, i=1,5),((j,x(j,k), k=1,5), j=1,100) 150 FORMAT(1X, ‘Line’, 5I10, 100(/,2x,I5, F10.4)) Implied DO Loop – More examples Compiled By : Dr. Manamohan Prusty
  • 80. • It is possible to keep one DO loop within another DO loop to create a nested DO loop • Examples : DO i = 1,5 DO j = i, 12 DO k = 7, 2,-1 statements ENDDO ENDDO ENDDO Caution –Youcan exit from inside the IF-ENDIF and DO-ENDDOblocks. However entering from outside is prohibited into them. Loop inside Loop - Nested DO Loop DO 20 i=1,6 DO 20 j=1,12 WRITE(6,*) a(i), b(j) 20CONTINUE Compiled By : Dr. Manamohan Prusty
  • 81. • A GOTO statement is used to transfer the control from one place to another • Mainly three types : UnconditionalGOTO ComputedGOTO AssignedGOTO Caution – A GOTO statement can be used to transfer controlfrom IF-ENDIF and DO-ENDDO blocks but not into them. Jumping Statements -GOTO Compiled By : Dr. Manamohan Prusty
  • 82. • Syntax - GOTOlabel ….. label executable statement • When an unconditional GOTO statement is encountered, control immediately jumps to the executable statement labelled with label • Example - 10 CONTINUE WRITE(*,*) “Enter a positive value” READ(*,*) x IF ( x .LE. 0.0) GOTO 10 UnconditionalGOTO Compiled By : Dr. Manamohan Prusty
  • 83. • The Computed GOTO statement selects one statement label from a list, depending on the computed value (integer) of a mathematical expression. • Syntax - GOTO (label1, label2, …), expression label1 executable statement1 label2 executable statement2 … • Example - GOTO (10, 20, 30,40), N • 10WRITE(*,*) “Your choice is 1” • 20 WRITE(*,*) “Your choice is2” • 30 WRITE(*,*) “Your choice is 3” • 40 WRITE(*,*) “Your choice is 4” • Here if N=1 then the control moves to 10, for N=2, it jumps to 20 and so on. However if N is less then 1 or greater than 4, then no GOTO statement is executed and the control just continues as it is. • Note – It’s use is strongly discouraged. Instead the block IF ladder statement has to be used. ComputedGOTO Compiled By : Dr. Manamohan Prusty
  • 84. • GOTO (label1, label2, …), expression label1 executable statement1 label2 executable statement2 … Computed GOTO vs Block IF Ladder statements • IF (expression .EQ. 1) THEN GOTO label1 ELSEIF (expression .EQ. 2) THEN GOTO label2 … ENDIF label1 executable statement1 label2 executable statement2 … ComputedGOTOStatement Block IFStatement Compiled By : Dr. Manamohan Prusty
  • 85. • The ASSIGN statement is the only way to assign a statement label value to an INTEGER variable. • Syntax - ASSIGN label TO integer-variable • When an integer-variable is assigned a label statement, it may not be referenced as a number as it has no numerical value • Syntax ofAssigned GOTO - GOTO integer-variable, (label1,label2,…) • Here the integer-variable must be assigned a statement label in an earlier ASSIGN statement. The integer-variable must match one of the labels in the list • Note –This form ofGOTO statement is obscure and it’s use is stronglydiscouraged. ASSIGN and AssignedGOTO Compiled By : Dr. Manamohan Prusty
  • 86. • ASSIGN 40 TON … GOTO N, (10, 20,30,40) 10 PAUSE “Press enter to continue” 20 WRITE(*,*) “Your choice is2” 30 WRITE(*,*) “Your choice is 3” 40 STOP ‘Emergency Stop’ • PAUSE Syntax - PAUSE ‘string’ – A PAUSE statement prints out the string and waits for the user response to continue • STOP Syntax - STOP ‘string’ – A STOP statement displays the string and stops the execution of the program before returning the control to the operating system Assigned GOTO, PAUSE and STOP statement Compiled By : Dr. Manamohan Prusty
  • 87. • A constant or a variable – a particular memory location for a particular type of data • AnArray is a symbolic name referring to a group of memory locations,all holding the same type of data • One-DimensionalArray - In order to represent an one-dimensional array two pieces of information is required – 1. data type and 2. number of elements in the array • SYNTAX : Data type, DIMENSION array-name(array_length) Data type, DIMENSION array-name(lower_bound:upper-bound) • Note –The upper_bound must be greater than the lower_bound.The array_length, lower_bound:upper-bound must be integer constants. Subscripted Variables -Arrays Compiled By : Dr. Manamohan Prusty
  • 88. !200 element double precission array• DOUBLE PRECISSION xarray(-99:100) • INTEGER year, monno, dayno PARAMETER (year=2018, monno=12, dayno=30) CHARACTER*3 month(monno) LOGICAL day(dayno) • REAL, DIMENSION xyval(-100:10) ! 12 element 3 characterarray ! 30 element logical array ! 111 element real array 1D Arrays -Examples Compiled By : Dr. Manamohan Prusty
  • 89. • FORTRAN 77 has arrays up to seven dimensions.The elements ineach dimension are of the same type. • Examples : INTEGER i, j, ncol,nrow PARAMETER (ncol=7, nrow=12) REAL matrix(ncol,nrow),sum=0.0 DO i = 1, ncol DO j = 1, nrow READ(*,*) matrix(i,j) sum = sum + matrix(i, j) ENDDO ENDDO Multidimensional arrays Compiled By : Dr. Manamohan Prusty
  • 90. • 1D array :A(1),A(2),A(3),A(8),….. • Higher Dimensional Array : stored in COLUMN major form. Example for -B(m,n) B(3,1) … B(m,1) B(3,2) … B(m,2) B(2,3) … B(m,3) B(1,1) B(1,2) B(1,3) … B(1,n) B(2,1) B(2,2) B(2,3) … B(2,n) … … … B(3,n) … B(m,n) • Note - the order in which array stores the data and accesses it makes compiler run faster and efficient codes. ‘out of order’ code slows down the program and thus is less efficient. C++ stores array as a ROW major. Arrays - storage Compiled By : Dr. Manamohan Prusty
  • 91. • The number of subscripts in any array reference must match the array declaration. • The subscript must always remain within the bounds declared. • The subscript must be an INTEGER expression • An array element is undefined until it has a value assigned to it in some manner • An array may be accessed by its name only (without subscripts) in a few limited circumstances: • In a type declaration if a DIMENSION statement is used to set the array bounds • In a DATA statement which initializes the entire array • In a READ orWRITE statement which reads in or writes out the entirearray • as an argument in an external function reference or subroutine cell • as a dummy argument in an external function or subroutine Arrays – Points to be noted Compiled By : Dr. Manamohan Prusty
  • 92. • REALA(5) INTEGER, DIMENSION(3,0:3) B DATAA /1.0, 1.414, 1.732, 2.0,2.236/ DATAB /1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144/ • INTEGER i, j REAL, DIMENSION(3, 4)C DO j=1, 4 DO i=1,3 C(i,j) =SQRT(i*j) ENDDO ENDDO WRITE(*, 100) ((C(i, j), j = 1, 4), i=1, 3) 100 FORMAT (4(F10.6, 2x) /) Arrays – Read andWrite Compiled By : Dr. Manamohan Prusty
  • 93. • A statement function is a user defined function which is defined and used in a program unit. It appears after the type declaration and before the executable statements. • Syntax : function_name(dvar1, dvar2, dvar4, …,dvarn) = expression • Note – function_name is a symbolic name and must be unique within the program expression may contain constants, variables and array elements or other functions defined earlier It may return any of the six (integer, real, double precision, complex, logical, character) data types • It is invoked by its name and argument list Statement Function Compiled By : Dr. Manamohan Prusty
  • 94. • REAL Celsius, Fahrenheit, temp Celsius(Fahrenheit) = 5.0 * (Fahrenheint-32.0)/9.0 WRITE(*,*) ‘Enter the value of temperature in Fahrenheit ?’ READ(*,*) temp WRITE(*,*) ‘The equivalentCelsius of ‘, temp ,’ Fahrenheit is =‘,Celsius(temp) Statement Function Compiled By : Dr. Manamohan Prusty
  • 95. • Function subprogram (external function) and Subroutine are external subprograms which may only contain two statements RETURN and SAVE • Both must end with the END statement • The external function returns one value while the subroutine may return zero or more values via an argument list. • Program units are independent i.e., they contain their own symbolic names and labels. • They may call each other but cannot call themselves, either directly or indirectly. • Information is passed via argument lists or through COMMON Blocks or by using external files. Subprogram – Function and Subroutine Compiled By : Dr. Manamohan Prusty
  • 96. • Syntax : type FUNCTION f_name(dvar1, dvar2,dvar3,…,dvarn) • The type designates the data type of the value returned by the external function. • If the function returns a CHARACTER value then, the length must be specified or given asCHARACTER*(*). • The name f_name may be used within the external function as a variable but it must be assigned a value before the end of subprogram unit • The function is invoked by using it’s name f_name followed by the arguments • There can be zero or more arguments of any type, however, the parentheses must be present even if there are no arguments Subprogram Function Compiled By : Dr. Manamohan Prusty
  • 97. PROGRAM Main IMPLICIT NONE INTEGER i, n, nmax PARAMETER (nmax=10) REAL a(0:nmax), poly, x 10 CONTINUE WRITE(*,*) “Enter the value of n” READ(*,*) n IF (n .GT. nmax) THEN WRITE(*,*)”Choose smaller value n<=”,nmax GOTO 10 ENDIF WRITE(*,*)”Enter the value of coefficients” DO i=0,n WRITE(*,*)”Enter the value of a(“,i,”)” READ(*,*) a(i) ENDDO Subprogram Function - example WRITE(*,*)”Enter the value of x” READ(*,*) x WRITE(*,*),”The value of polynomial at”,x,”=“,poly(a,n,x) STOP “Program ends here” END PROGRAM !Function subprogram for calculation ! poly = a(0) + a(1) x + a(2) x**2 + of the polynomial …… + a(n) x**n REAL FUNCTION poly(a,n,x) IMPLICIT NONE INTEGER i, n REAL a(0:n), x Poly=a(n) DO i=n-1,0,-1 poly= a(i) + poly * x ENDDO END FUNCTION Compiled By : Dr. Manamohan Prusty
  • 98. • Syntax : SUBROUTINE sub_name(dvar1, dvar2,dvar3,…,dvarn) • The name sub_name is global in nature. So, it may not be used as a variable inside the subroutine • The SUBROUTINE is invoked with a CALL statement in the main programunit CALL sub_name(var1, var2,var3,…,varn) where var1, var2,var3,…,varn are the actual arguments rather than the dummy variables above. • There can be zero or more arguments of any data type which are declared in the body of the subroutine, however, the parentheses may be omitted if there are no arguments Subprogram - Subroutines Compiled By : Dr. Manamohan Prusty
  • 99. Subprogram Subroutine - Examples PROGRAM Main IMPLICIT NONE REAL time, s INTEGER h, m 10 CONTINUE WRITE(*,*) “Enter the time in decimal hours” READ(*,*,END=88) time IF (time .LT. 0.0) GOTO 88 CALL CONVERT(time, h, m, s) WRITE(*,20) time, h, m, s 20 FORMAT(F10.4,’ hrs = ‘,I6,’ h ‘,I2,’ m ‘,F5.2,’ s’) GOTO 10 88 STOP ‘End of Program’ END PROGRAM !Subroutine for converting the decimal time to !Individual hours, minutes and seconds mins, secs)SUBROUTINE CONVERT(dtime, hrs, IMPLICIT NONE INTEGER hrs, mins REAL dtime, secs secs = dtime * 3600.0 hrs = INT(dtime) secs = secs – 3600.0 * hrs mins = INT(secs/60.0) secs = secs – 60.0 * mins END SUBROUTINE Compiled By : Dr. Manamohan Prusty
  • 100. • The RETURN statement immediately transfers execution back to the calling program. It’s Syntax : RETURN without any arguments • Note – The END statement has the same effect. So, it is unnecessary to include it. However if you want to put more than one exit point in a subprogram/subroutine then it becomes necessary • The SAVE statement is used to preserve the values of local variables. It’s Syntax : SAVE item1, item2, …, itemn.The items can be variables, array_names or COMMON blocks but not the dummy arguments or blankCOMMONblocks. • Without the arguments it saves the values of all allowable items in the procedure. RETURN and SAVEStatements Compiled By : Dr. Manamohan Prusty
  • 101. • The BlankCOMMON block is setup withthe statement : COMMON variable-list • and the named COMMON block is declared by : COMMON /name/variable-list • Every SUBROUTINE, FUNCTION that uses the data stored in the COMMON block must have a similar statement to those above • Without the arguments it saves the values of all allowable items in the procedure. COMMON Statement PROGRAM main INTEGER i REAL w, x, y, z COMMON x, y, i x = 3.141592; y=1.414; i=46 CALL SUB(w,x) … END SUBROUTINE SUB(a, b) INTEGER j REAL A, B, C, D COMMON A, B, j … END Compiled By : Dr. Manamohan Prusty
  • 102. • It is not necessary to declare named COMMON blocks in the main program unless they are used there.These namedCOMMON blocks must be exactlythe same length wherever they appears • BlankCOMMON blocks must be declared in the main program.These COMMON blocks need not be the same length in different program units • Variables in COMMON blocks may be initialized with READ or assignment statements but not with a DATA statement COMMON Statement Compiled By : Dr. Manamohan Prusty
  • 103. • The EQUIVALENCE statement causes two or more statement items (arrays or variables) to occupy the same memory space. • The general form of the statement is EQUIVALENCE var_list1, var_list2, var_list3, ..., var_listn • In the above syntax var_listi contains two or more variables or arrays or mixture of the two. • It occurs near the beginning of the program unit where type declaration and other specification statements are present. EQUIVALENCE Statement Compiled By : Dr. Manamohan Prusty
  • 104. • The EXTERNAL statement is used to include the modules containing a procedure which is omitted. • Without this the linker will return an error during compilation if the Block data program is missing as part of the main program. • The general form of the statement is EXTERNAL ename1, ename2, ename3, ..., enamen • In the above syntax enamei is the name of an external function, subprogramor dummy procedure in an argumentlist EXTERNAL Statement Compiled By : Dr. Manamohan Prusty
  • 105. Fortran Continuation of lines • Some times if a statement is too long to fit in a single line and it needs to be continued then it needs the use of + or 1 (any character can be used) as part of the sixth place. Good practice is to use the plus sign or digits or & .The default maximum of continuation lines is 99. • Or you can extent the source line length to 132 characters from the default of up to 72. This is done by using the –e option during compilation whose syntax is f77 –e file.f • Example : WRITE(*,*) "The solutions are x1= ", re , "+ i" , im , 1 + " and x2= " , re , "- i" , im ,” and theyare imaginary complex conjugates" Compiled By : Dr. Manamohan Prusty
  • 106. Disk I/O - File OPEN -specifiers SPECIFIER VALUE OFVARIABLE DATATYPEOFVARIABLE ACCESS ‘APPEND’,’DIRECT’,’SEQUENTIAL’ CHARACTER ACTION ‘READ’,’WRITE’,’READWRITE’ CHARACTER BLANK ‘NULL’,’ZERO’ CHARACTER ERR Statement Number INTEGER FORM ‘FORMATTED’,’UNFPRMATTED’,’PRINT’ CHARACTER FILE * <Filename> or * CHARACTER FILEOPT ‘NOPAT’, ‘BUFFER=n’,’EOF’ CHARACTER IOSTAT Error Number INTEGER READONLY - - RECL Record Length for DIRECTACCESS INTEGER STATUS ‘OLD’, ‘NEW’,’UNKNOWN’,’SCRATCH’ CHARACTER OPEN(<UNIT=>u,SPECIFIER) Compiled By : Dr. Manamohan Prusty
  • 107. Disk I/O - File OPENexamples • 100WRITE(*,* ) ‘Enter the input file name’ READ(*,’(A)’,END=999) FNAME OPEN(20,FILE=FNAME,STATUS=UNKNOWN,BLANK=‘ZERO’,ERR=100) • OPEN(8,STATUS='SCRATCH') – It opens a temporary file to act as a scratch file • Note that - it is forbidden to specify a filename for a scratch file. Compiled By : Dr. Manamohan Prusty
  • 108. Disk I/O - File CLOSE - specifiers SPECIFIER VALUE OFVARIABLE DATATYPEOFVARIABLE ACCESS ‘APPEND’,’DIRECT’,’SEQUENTIAL’ CHARACTER ERR Statement Number INTEGER IOSTAT Error Number INTEGER STATUS ‘KEEP’, ‘DELETE’ CHARACTER CLOSE(<UNIT=>u,SPECIFIER) Examples - CLOSE(27,STATUS=‘DELETE’) CLOSE (39) Compiled By : Dr. Manamohan Prusty
  • 109. Disk I/O - File INQUIRE statement • INQUIRE statement is useful when you wish to know if a file exists or is already connected or not. It can be carried out in two ways (i) By UNIT or (ii) By FILE • Syntax – INQUIRE(UNIT=u or FILE=FILENAME (but not both), SPECIFIER) SPECIFIER RETURNEDVALUE OFVARIABLE DATATYPE OFVARIABLE EXIST/OPENED .TRUE. or . FALSE. LOGICAL NAMED .TRUE. or . FALSE. LOGICAL ERR Statement Number INTEGER NAME Returns FILENAME CHARACTER NUMBER Returns the UNITNUMBER INTEGER ACCESS Returns SEQUENTIAL or DIRECT CHARACTER IOSTAT Returns an Error Number INTEGER FORM Returns FORMATTED/UNFORMATTED CHARACTER NEXTREC Returns n+1 (n is the rec no. of last record) INTEGER STATUS ‘OLD’, ‘NEW’,’UNKNOWN’,’SCRATCH’ CHARACTER BLANK Returns ‘NULL’ or ‘ZERO’ CHARACTER Compiled By : Dr. Manamohan Prusty
  • 110. File INQUIRE statement (Example) last)• INTEGER FUNCTION FREEUNIT(first, IMPLICIT NONE INTEGER iunit, first, last LOGICAL isopen DO iunit=first, last INQUIRE(UNIT=inuit, OPENED=isopen) IF (.NOT. isopen) THEN freeunit = iunit RETURN ENDIF ENDDO freeunit = -1 END • Demo subprogram that returns the smallest unit number that is currently not in use Compiled By : Dr. Manamohan Prusty
  • 111. REWIND and BACKSPACE statements • REWIND(UNIT, ERR, IOSTAT) statement is used to re-read a sequential input file from the first record • BACKSPACE(UNIT, ERR, IOSTAT) statement is used to re-read the most recently read record Compiled By : Dr. Manamohan Prusty
  • 112. FILE Operations - READING andWRITING • READ/WRITE(UNIT=u, FMT=fmt, IOSTAT=ios, ERR=err, END=s) • The UNIT=u is unit number that denotes the associated file. • The FMT=fmt is either FORMATTED or UNFORMATTED. • The IOSTAT=ios is the I/O status identifier. If successful it returns an zero value otherwise a non zero value. • The ERR=err is a label the program jumps to if there is an error. • The END=s defines which statement label the program jumps to if it reaches the end of file. Compiled By : Dr. Manamohan Prusty
  • 113. Example Program - 1 !Function subprogram for multiplication of matrix !and a vector SUBROUTINE mat_vec_mpy(Matrix, n, vecin, vecout) IMPLICIT NONE INTEGER n, i, j REAL, DIMENSION Matrix(n, n), vecin(n), vecout(n) DO i=1,n vecout(i) = 0.0 DO j=1,n vecout(i) = vecout(i) + Matrix(i,j) * vecin(j) ENDDO ENDDO END SUBROUTINE Compiled By : Dr. Manamohan Prusty
  • 114. Example Program - 2 !Function subprogram for Fibonacci Series SUBROUTINE Fib(F,n) IMPLICIT NONE INTEGER n, i REAL F(0:n) THEN DO i=0,n IF (i==0) THEN F(i)=0 ELSEIF(i==1) F(i)=1 ELSE F(i)=F(i-1)+F(i-2) ENDIF ENDDO END SUBROUTINE Compiled By : Dr. Manamohan Prusty
  • 115. Example Program - 3 !Function subprogram for Sorting in increasing order SUBROUTINE sort(num,n) IMPLICIT NONE INTEGER n, i, j REAL num(n), temp DO i=1,n DO j=i,n IF (num(i) > num(j)) THEN num(i) = num(j) = temp temp = num(i) num(j) ENDIF ENDDO ENDDO END SUBROUTINE Compiled By : Dr. Manamohan Prusty
  • 116. AT THEEND • Have the necessity to use FORTRAN. • Have a book for quick reference. • Make some time for practicing it. • In case of doubts do not hesitate to ask for help. • Last but not least Thank you and GoodLuck! Compiled By : Dr. Manamohan Prusty