Vous êtes sur la page 1sur 75

KNTU University Bakhtiari

1386
Fortran Course: Session 1

Computer Language:
The term computer language includes a wide variety of languages used to communicate with computers.

1- A programming language is an artificial language that can be used to control the behavior of a
machine, particularly a computer. Programming languages, like human languages, are defined
through the use of syntactic and semantic rules, to determine structure and meaning respectively.
2- Scripting Language
3- A specification language is a formal language used in computer science. Unlike most
programming languages, which are directly executable formal languages used to implement a
system, specification languages are used during system analysis, requirements analysis and design.
4- Etc

Programming language elements:
1- Syntax: The syntax of a language describes the possible combinations of symbols that form a
syntactically correct program. The meaning given to a combination of symbols is handled by
semantics. Since most languages are textual, this article discusses textual syntax.
2- Type system: defines: how a programming language classifies values and expressions into types,
how it can manipulate those types and how they interact. This generally includes a description of
the data structures that can be constructed in the language.
3- Execution semantics: Once data has been specified, the machine must be instructed to perform
operations on the data. The execution semantics of a language defines how and when the various
constructs of a language should produce a program behavior.
4- Core library: Most programming languages have an associated core library (sometimes known as
the 'Standard library', especially if it is included as part of the published language standard), which
is conventionally made available by all implementations of the language. Core libraries typically
include definitions for commonly used algorithms, data structures, and mechanisms for input and
output.
Algorithm:
In mathematics, computing, linguistics, and related disciplines, an algorithm is a finite list of well-defined
instructions for accomplishing some task that, given an initial state, will proceed through a well-defined
series of successive states, possibly eventually terminating in an end-state. ( example factorial)

Expressing algorithms:
1- Natural language
2- Pseudocode
3- Flowcharts
4- Programming language

Pseudocode
(derived from pseudo and code) is a compact and informal high-level description of a computer
programming algorithm that uses the structural conventions of programming languages, but omits detailed
subroutines, variable declarations or language-specific syntax. The programming language is augmented
with natural language descriptions of the details, where convenient:
KNTU University Bakhtiari
1386
Example:
A) Pseudocode:
if credit card number is valid
execute transaction based on number and order
else
show a generic failure message
end if
B) Same algorithm with PHP:

<?php
if (is_valid($cc_number)) {
execute_transaction($cc_number, $order);
} else {
show_failure();
}
?>

Flowchart
A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm or a
process.
A flowchart is described as "cross-functional" when the page is divided into different "lanes" describing the
control of different organizational units. A symbol appearing in a particular "lane" is within the control of
that organizational unit. This technique allows the analyst to locate the responsibility for performing an
action or making a decision correctly, allowing the relationship between different organizational units with
responsibility over a single process.
Algorithm Classification by implementation:
1- Recursion or iteration: A recursive algorithm is one that invokes (makes reference to) itself
repeatedly until a certain condition matches, which is a method common to functional
programming. Iterative algorithms use repetitive constructs like loops and sometimes additional
data structures like stacks to solve the given problems.
2- Logical: An algorithm may be viewed as controlled logical deduction. This notion may be
expressed as:

Algorithm = logic + control
The logic component expresses the axioms that may be used in the computation and the control
component determines the way in which deduction is applied to the axioms.

3- Serial, parallel, or distributed: Algorithms are usually discussed with the assumption that
computers execute one instruction of an algorithm at a time. Those computers are sometimes
called serial computers. An algorithm designed for such an environment is called a serial
algorithm, as opposed to parallel algorithms or distributed algorithms.

Loops:

A loop is a sequence of statements which is specified once but which may be carried out several times
in succession. The code "inside" the loop is obeyed a specified number of times, or once for each of a
collection of items, or until some condition is met.

Conditional:
In computer science, conditional statements, conditional expressions, and conditional constructs are
features of a programming language, which perform different computations, or actions depending on
whether a programmer-specified condition evaluates to true or false (see Boolean datatype). Apart
KNTU University Bakhtiari
1386
from the case of branch predication, this is always achieved by selectively altering the control flow
based on some condition.
1- if then else
If (condition 1) Then
(statements 1)
Else if (condition 2)
(statements 2)
.
.
.
Else
(statements n)
End If
2- Case and switch statements
case someChar of
'a': actionOnA;
'x': actionOnX;
'y','z':actionOnYandZ;
end;





EXAMPLE (Pseudocode) :
Output: Please enter your choice
Output: 1- Run Method A
Output: 2- Run Method B
Output: 3- Quit
Input: choise Integer choice
Select Case choice
Case 1
Run A
Case 2
Run B
Case 3
END
End select
3- Pattern Matching
4- Branch predication
if condition
do this
else
do that
branch if condition to label 1
do that
branch to label 2
label 1:
do this
label 2: ...
KNTU University Bakhtiari
1386

APPENDIX 1: Flowchart basic shapes
Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows
show the sequence of the steps, and the relationships among them.


Start/End
The terminator symbol marks the starting or ending point of the system. It usually contains the word "Start" or "End."

Action or Process
A box can represent a single step ("add two cups of flour"), or and entire sub-process ("make bread") within a larger
process.

Document
A printed document or report.

Decision
A decision or branching point. Lines representing different decisions emerge from different points of the diamond.

Input/Output
Represents material or information entering or leaving the system, such as customer order (input) or a product (output).

Connector
Indicates that the flow continues where a matching symbol (containing the same letter) has been placed.

Flow Line
Lines indicate the sequence of steps and the direction of flow.

Delay
Indicates a delay in the process.
KNTU University Bakhtiari
1386

Merge
Indicates a step where two or more sub-lists or sub-processes become one.

Collate
Indicates a step that orders information into a standard format.

Sort
Indicates a step that organizes a list of items into a sequence or sets based on some pre-determined criteria.

Subroutine
Indicates a sequence of actions that perform a specific task embedded within a larger process. This sequence of actions
could be described in more detail on a separate flowchart.

Manual Loop
Indicates a sequence of commands that will continue to repeat until stopped manually.

Loop Limit
Indicates the point at which a loop should stop.

Data storage
Indicates a step where data gets stored.

Database
Indicates a list of information with a standard structure that allows for searching and sorting.

Display
Indicates a step that displays information.

Off Page
Indicates that the process continues off page.
KNTU University Bakhtiari
1386
Fortran Course: Session 2

Fortran history:
Fortran (previously FORTRAN) is a general-purpose, procedural, imperative programming language that is
especially suited to numeric computation and scientific computing. Originally developed by IBM in the
1950s for scientific and engineering applications, Fortran came to dominate this area of programming early
on and has been in continual use for over half a century in computationally intensive areas such as climate
modeling, computational fluid dynamics (CFD), computational physics, financial computing, and
computational chemistry.
Fortran (a portmanteau derived from The IBM Mathematical Formula Translating System) encompasses a
lineage of versions, each of which evolved to add extensions to the language while retaining compatibility
with previous versions. Successive versions have added support for processing of character-based data
(FORTRAN 77), array programming, module-based programming and object-based programming (Fortran
90 / 95), and object-oriented and generic programming (Fortran 2003).

The legacy of Fortran
Since Fortran has been in use for nearly fifty years, there is a vast body of Fortran in daily use throughout
the scientific and engineering communities. It is the primary language for some of the most intensive
supercomputing tasks, such as weather and climate modeling, computational fluid dynamics, computational
chemistry, quantum chromodynamics, simulations of long-term solar system dynamics, high-fidelity
evolution artificial satellite orbits, and simulation of automobile crash dynamics. Indeed, one finds that
even today, half a century later, floating-point benchmarks to gauge the performance of new computer
processors are still written in Fortran (e.g., CFP2000, the floating-point component of the SPEC CPU2000
benchmarks).

Advantages of using Fortran:
- Simplicity to achieve high performance and easy to learn in comparison with C++ and C.
- Huge collection of sample code available for different scientific purposes.
- Powerful memory handling (Variable-dimension array arguments in subroutines).
- Powerful built in array operations.
- Pass all variables by reference ( fastest method).
- In comparison with C++ on Massively Parallel Processors (MPPs), Fortran 90( and above)
compilers may be more highly optimized.

Disadvantages:
- It is not object oriented.
- Not a full-feathered language to achieve complete control over hardware.
- On Symmetric Multi-Processors (SMPs), C++ is likely to be further advanced.
- Free software and libraries useful for physics modeling as well as other problem domains will be
more rapidly developed in the C++ community.
KNTU University Bakhtiari
1386
Example Reference Table about CPU Benchmark
CFP2000:
Benchmark Language Category
168.wupwise Fortran 77 Physics / Quantum Chromodynamics
171.swim Fortran 77 Shallow Water Modeling
172.mgrid Fortran 77 Multi-grid Solver: 3D Potential Field
173.applu Fortran 77 Parabolic / Elliptic Partial Differential Equations
177.mesa C 3-D Graphics Library
178.galgel Fortran 90 Computational Fluid Dynamics
179.art C Image Recognition / Neural Networks
183.equake C Seismic Wave Propagation Simulation
187.facerec Fortran 90 Image Processing: Face Recognition
188.ammp C Computational Chemistry
189.lucas Fortran 90 Number Theory / Primality Testing
191.fma3d Fortran 90 Finite-element Crash Simulation
200.sixtrack Fortran 77 High Energy Nuclear Physics Accelerator Design
301.apsi Fortran 77 Meteorology: Pollutant Distribution



Common Fortran compilers (For windows) :
1- Compaq Visual Fortran
2- F95 PowerStation
3- Intel Fortran ( need .Net developer)
4- Lahey Fortran
KNTU University Bakhtiari
1386
1) Language Elements

The basic components of the Fortran language are its character set.
The members are:
the letters A ... Z and a ... z (which are equivalent outside a character context);
_ the numerals 0 ... 9;
_ the underscore _ and the special characters
= : + blank - * / ( ) , . $ ' (old)
! " % & ; < > ? (new)

From these components, we build the tokens that have a syntactic meaning to the compiler. There are six
classes of token:
Label: 123
Constant: 123.456789_long
Keyword: ALLOCATABLE
Operator: .add.
Name: solve_equation (can have up to 31 characters, including a _).
Separator: / ( ) (/ /) , = => : :: ; %

Note the trailing comments and the trailing continuation mark. There may be 39 continuation lines, and 132
characters per line.
Blanks are significant. Where a token or character constant is split across two lines:
... start_of&
&_name
2- Intrinsic data types:

Fortran has 5 intrinsic Data Types.
A) INTEGER
B) REAL
C) COMPLEX
D) CHARACTER
E) LOGICAL
NOTE: All variables must be declared in the beginning of routines!
NOTE: Always use IMPLICIT NONE to avoid errors on typing!
NOTE: Dont be lazy, it costs more time to recover your code: Always use meaningful names for
your variables!
NOTE: Do not hesitate to leave comments for yourself!

2-1) Integer

There are 3 integer data types for desktop computers:
1- INTEGER*1 : -127 up to +127
2- INTEGER*2 : -32768 up to 32767
3- INTEGER*4: -2147483648 up to 2147483647
Note: Fortran 90 doesnt have unsigned integer!
Note: Fortran does not make an error on overflow!
KNTU University Bakhtiari
1386

2-2) Real

There are 2 real data types for desktop computers:
1- REAL*4 : 3.4028235E+38
2- REAL*8: 1.797693134862316E+308
REAL data types must be assigned these ways:

REAL*4 a
REAL*8: b

Incorrect assignment: a=2
Correct assignment : a=2.0


Incorrect assignment: b=2 or b=2.0
Correct assignment : b=2.0D0

2-3) Complex

There are 2 complex data types for desktop computers:
1- COMPLEX*8 : made from two REAL*4
2- COMPLEX*16: made from two REAL*8
Complex variables should be assigned this way:
COMPLEX*16 C1 C1 should be equal to 5.2+ 12.3 i
C1=CMPLX(5.2D0,12.3D0)
Note: All basic math operations can be used within complex variables!
COMPLEX*8 C1,C2,C3C1=CMPLX(1.0,2.0)
C2=CMPLX(2.2,5.1)
C3=C1+C2
C3=C1-C2
C3=C1*C2
C3=C1/C2


These functions are important for writing portable numerical software:

DIGITS(X) Number of significant digits
EPSILON(X) Almost negligible compared to one (real)
HUGE(X) Largest number
MAXEXPONENT(X) Maximum model exponent (real)
MINEXPONENT(X) Minimum model exponent (real)
PRECISION(X) Decimal precision (real, complex)
RADIX(X) Base of the model
RANGE(X) Decimal exponent range
TINY(X) Smallest positive number (real)
2-4) Characters
CHARACTER(LEN=18) CH1
CH1=Fortran Character
2-5) Logical
Here, there may also be different kinds (to allow for packing into bits):
Example:
LOGICAL*1 Cond1
Cond1=.false.
Cond1=.true.

KNTU University Bakhtiari
1386
3) Simple input and output statements
You can use these simple statements for input and output at these stages:
3-1) For input data from screen
REAL*4 R1,R2
READ(*,*) R1,R2
3-2) For output data to screen
WRITE(*,*) R1,R2

4) Simple Program structure:
PROGRAM P1
IMPLICIT NONE
Declare your variables here

Place your statements here


END PROGRAM P1

5) Exercises:
5-1) Write a program which has 6 variables of 3 different integer kinds(a pair from each
kind), and then use HUGE function to find the maximum values of each kind and place
them in the first set of variables and show the results . Then try to add the value equal to
1 to the first set and place the result in the second set and show the results.

5-2) Write a program which has 3 REAL*4 Variables. Then use HUGE function to place
huge value of REAL*4 kind in the first and second variables. Then multiply the first and
second variable and place the result in the third variable and show the result.

5-3) Write a program which has 3 REAL*8 Variable. Assign the Value 1.0 to first variable
and value 0.0 to second variable. Divide the first variable to second and place the result in
the third variable and show that.
5-4) Try to get a complex variable from user and show that!


KNTU University Bakhtiari
1386
Fortran Course: Session 3

Conditional Statements:
In computer science, conditional statements, conditional expressions, and conditional constructs are
features of a programming language, which perform different computations, or actions depending on
whether a programmer-specified condition evaluates to true or false (see Boolean datatype). Apart
from the case of branch predication, this is always achieved by selectively altering the control flow
based on some condition.
Fortran Conditional Statements:
A) SELECT CASE
B) IF



A Brief review on Fortran Operators:

Programming languages generally have a set of operators that are similar to operators in
mathematics: they are somehow special functions. In addition to arithmetic operations, they often
perform Boolean operations on truth values and string operations on strings of text. Relational
operators are used to test two values, such as equality if one value is greater than another. Unlike
functions, operators often provide the primitive operations of the language, their name consists of
punctuation rather than alphanumeric characters, and they have special infix syntax and irregular
parameter passing conventions. The exact terminology, however, varies from language to
language.

We can study operators in two categories:
A) Numerical Operators
B) Relational Operators
C) Logical Operators
Below is a set of common numerical operators:

**
Power
/
Division
*
Multiply
+
Sum
-
Subtract




KNTU University Bakhtiari
1386
Below is a set of common relational operators:

Sign In print Meaning Used to:
== .EQ. = equal to Test the equivalence of two values.
/= .NE. not equal to Test the negated equivalence of two values.
> .GT. > greater than Test if the value of the left value is greater than that of the right.
< .LT. < less than Test if the value of the left expression is less than that of the right.
>= .GE.
greater than or
equal to
Test if the value of the left expression is greater than or equal to that of the right.
<= .LE.
less than or
equal to
Test if the value of the left expression is less than or equal to that of the right.

Below is a set of common logical operators:

Operator Example Meaning
.AND. A .AND. B Logical conjunction: the expression is true if both A and B are true.
.OR. A .OR. B Logical disjunction (inclusive OR): the expression is true if either A,
B, or both, are true.
.NEQV. A .NEQV. B Logical inequivalence (exclusive OR): the expression is true if either
A or B is true, but false if both are true.
.XOR. A .XOR. B Same as .NEQV.
.EQV. A .EQV. B Logical equivalence: the expression is true if both A and B are true, or
both are false.
.NOT. .NOT. A Logical negation: the expression is true if A is false and false if A is
true.


A) Select Case:
KNTU University Bakhtiari
1386
Statement: Marks the beginning of a CASE construct. A CASE construct conditionally executes
one block of constructs or statements depending on the value of a scalar expression in a SELECT
CASE statement.

Syntax

[name:] SELECT CASE (expr)
[CASE (case-value [, case-value] ...) [name]

block] ...
[CASE DEFAULT [name]
block]
END SELECT [name]
name
Is the name of the CASE construct.

expr
Is a scalar expression of type integer, logical, or character (enclosed in parentheses). Evaluation of
this expression results in a value called the case index.

case-value
Is one or more scalar integer, logical, or character initialization expressions enclosed in
parentheses. Each case-value must be of the same type and kind parameter as expr. If the type is
character, case-value and expr can be of different lengths, but their kind parameter must be the
same.

Integer and character expressions can be expressed as a range of case values, taking one of the
following forms:


low:high
low:
:high

Case values must not overlap.

block
Is a sequence of zero or more statements or constructs.

CASE (1, 4, 7, 11:14, 22) ! Individual values as specified:
! 1, 4, 7, 11, 12, 13, 14, 22
CASE (:-1) ! All values less than zero
CASE (0) ! Only zero
CASE (1:) ! All values above zero
KNTU University Bakhtiari
1386

Examples:
A)
INTEGER FUNCTION STATUS_CODE (I)
INTEGER I
CHECK_STATUS: SELECT CASE (I)
CASE (:-1)
STATUS_CODE = -1
CASE (0)
STATUS_CODE = 0
CASE (1:)
STATUS_CODE = 1
END SELECT CHECK_STATUS
END FUNCTION STATUS_CODE

B)
SELECT CASE (J)
CASE (1, 3:7, 9) ! Values: 1, 3, 4, 5, 6, 7, 9
CALL SUB_A
CASE DEFAULT
CALL SUB_B
END SELECT

C)
SELECT CASE (ITEST .EQ. 1)
CASE (.TRUE.)
CALL SUB1 ()
CASE (.FALSE.)
CALL SUB2 ()
END SELECT
KNTU University Bakhtiari
1386
IF
Statement: Conditionally executes one block of constructs or statements depending on the
evaluation of a logical expression.

Syntax

[name:] IF (expr) THEN

block
[ELSE IF (expr) THEN [name]
block] ...
[ELSE [name]
block]
END IF [name]

name
(Optional) Is the name of the IF construct.

expr
Is a scalar logical expression enclosed in parentheses.

block
Is a sequence of zero or more statements or constructs.

Rules and Behavior

If a construct name is specified at the beginning of an IF THEN statement, the same name
must appear in the corresponding END IF statement. The same construct name must not
be used for different named constructs in the same scoping unit.

Depending on the evaluation of the logical expression, one block or no block is executed.
The logical expressions are evaluated in the order in which they appear, until a true value
is found or an ELSE or END IF statement is encountered.

Once a true value is found or an ELSE statement is encountered, the block immediately
following it is executed and the construct execution terminates.

If none of the logical expressions evaluate to true and no ELSE statement appears in the
construct, no block in the construct is executed and the construct execution terminates.
KNTU University Bakhtiari
1386
Example A:
BLOCK_A: IF (D > 0.0) THEN ! Initial statement for named
construct

RADIANS = ACOS(D) ! These two statements
DEGREES = ACOSD(D) ! form a block

END IF BLOCK_A ! Terminal statement for named
construct

Example B:

Block IF with ELSE IF statements:

IF (j .GT. 1000) THEN
! Statements here are executed only if J > 1000
ELSE IF (j .GT. 100) THEN
! Statements here are executed only if J > 100 and j <= 1000
ELSE IF (j .GT. 10) THEN
! Statements here are executed only if J > 10 and j <= 100
ELSE
! Statements here are executed only if j <= 10
END IF
KNTU University Bakhtiari
1386
IF -- Logical
Statement: Conditionally executes one statement based on the value of a logical
expression.
Syntax


IF (expr) stmt

expr
Is a scalar logical expression enclosed in parentheses.

stmt
Is any complete, unlabeled, executable Fortran statement, except for the following:

A CASE, DO, or IF construct
Another IF statement
The END statement for a program, function, or subroutine

When an IF statement is executed, the logical expression is evaluated first. If the value is
true, the statement is executed. If the value is false, the statement is not executed and
control transfers to the next statement in the program.


Example

IF (REF(J,K) .NE. HOLD) REF(J,K) = REF(J,K) * (-1.5D0)
KNTU University Bakhtiari
1386
IF -- Arithmetic
Statement: Conditionally transfers control to one of three statements, based on the value
of an arithmetic expression. It is an obsolescent feature in Fortran 95 and Fortran 90.

Syntax

IF (expr) label1, label2, label3

expr
Is a scalar numeric expression of type integer or real (enclosed in parentheses).

label1, label2, label3
Are the labels of valid branch target statements that are in the same scoping unit as the
arithmetic IF statement.

Rules and Behavior

All three labels are required, but they do not need to refer to three different statements.
The same label can appear more than once in the same arithmetic IF statement.

During execution, the expression is evaluated first. Depending on the value of the
expression, control is then transferred as follows:

If the Value of expr is: Control Transfers To:
Less than 0 Statement label1
Equal to 0 Statement label2
Greater than 0 Statement label3

Example


IF (n-10) 10, 20, 30
KNTU University Bakhtiari
1386
Do

Statement: Marks the beginning of a DO construct. The DO construct controls the
repeated execution of a block of statements or constructs. (This repeated execution is
called a loop.)

A DO construct takes one of the following forms:

Syntax

Block Form

[ name:] DO [label[, ] ] [loop-control]

block
[label] term-stmt

Nonblock Form

DO label[,] [loop-control]

name
(Optional) Is the name of the DO construct.

label
(Optional) Is a statement label identifying the terminal statement.

loop-control
Is a DO iteration (see Iteration Loop Control) or a DO WHILE statement.

block
Is a sequence of zero or more statements or constructs.

term-stmt
Is the terminal statement for the construct.


Rules and Behavior

A block DO construct is terminated by an END DO or CONTINUE statement. If the
block DO statement contains a label, the terminal statement must be identified with the
same label. If no label appears, the terminal statement must be an END DO statement.

If a construct name is specified in a block DO statement, the same name must appear in
the terminal END DO statement. If no construct name is specified in the block DO
statement, no name can appear in the terminal END DO statement.










KNTU University Bakhtiari
1386
A nonblock DO construct is terminated by an executable statement (or construct) that is
identified by the label specified in the nonblock DO statement
The following cannot be terminal statements for nonblock DO constructs:

CONTINUE
CYCLE
END (for a program or subprogram)
EXIT
Arithmetic IF
RETURN
STOP

Examples:
The following example shows block DO construct:
DO j = 1, 10
WRITE (*,*) j
END DO

LOOP_1: DO I = 1, N
A(I) = C * B(I)
END DO LOOP_1


DO j = 2, 20, 2
array(j) = 12.0
END DO

KNTU University Bakhtiari
1386

CYCLE
Statement: Interrupts the current execution cycle of the innermost (or named) DO construct.
Syntax
CYCLE [ name ]
name
(Optional) Is the name of the DO construct.
Rules and Behavior
When a CYCLE statement is executed, the following occurs:
1. The current execution cycle of the named (or innermost) DO construct is terminated.
If a DO construct name is specified, the CYCLE statement must be within the range of that
construct.
2. The iteration count (if any) is decremented by 1.
3. The DO variable (if any) is incremented by the value of the increment parameter (if any).
4. A new iteration cycle of the DO construct begins.
Any executable statements following the CYCLE statement (including a labeled terminal statement) are
not executed.
Example:
sample_loop: do i = 1, 5
print *,i
if( i .gt. 3 ) cycle sample_loop
print *,i
end do sample_loop
print *,'done!'


!output:
! 1
! 1
! 2
! 2
! 3
! 3
! 4
! 5
! done!
KNTU University Bakhtiari
1386

EXIT
Statement: Terminates execution of a DO construct.
Syntax
EXIT [ name ]
name
(Optional) Is the name of the DO construct.
Rules and Behavior
The EXIT statement causes execution of the named (or innermost) DO construct to be terminated.
If a DO construct name is specified, the EXIT statement must be within the range of that construct.
Any DO variable present retains its last defined value.
An EXIT statement can be labeled, but it cannot be used to terminate a DO construct.
Example:

LOOP_A : DO I = 1, 15
N = N + 1
IF (N > I) EXIT LOOP_A
END DO LOOP_A
KNTU University Bakhtiari
1386
DO WHILE
Statement: Executes the range of a DO construct while a specified condition remains true.
Syntax
DO [label[, ] ] WHILE (expr)
label
(Optional) Is a label specifying an executable statement in the same program unit.
expr
Is a scalar logical (test) expression enclosed in parentheses.
Rules and Behavior
Before each execution of the DO range, the logical expression is evaluated. If it is true, the statements in
the body of the loop are executed. If it is false, the DO construct terminates and control transfers to the
statement following the loop.
If no label appears in a DO WHILE statement, the DO WHILE loop must be terminated with an END DO
statement.
You can transfer control out of a DO WHILE loop but not into a loop from elsewhere in the program.
Example:
A)
DO WHILE (I / = J)
READ(*,*) I,J
END DO




B)
PROGRAM MAIN
REAL*8 Number,Residual
INTEGER*2 Power

READ(*,*) Number
POWER=0
Residual=Number/2.0D0
DO WHILE (Residual>1.0D0)
Residual = Residual/2.0D0
POWER=POWER+1
END DO
WRITE(*,*) NEAREST BINARY BASE DIGITS:, POWER+1
END PROGRAM MAIN
KNTU University Bakhtiari
1386
Exercises:



1) Use arithmetic IFs and assignment statements to store +1 in S if X >
0, store -1 in S if X < 0, and store 0 in S if X = 0. Do the same with
logical IFs.


2) Write a program, which read an integer number from user and calculate
the factorial of the number and show the result.

Hint: Use Block form of Do statement.

3) Write a program, which continuously reads a given choice from user as
an Integer number. The program should conduct following operations based
on the user choice:
Choice=1
Read a temperature value from user in Kelvin, and transform it to
Fahrenheit, and show the result.
Choice=2
Read a temperature value from user in Fahrenheit, and transform it to
Kelvin, and show the result.
Choice=3
Quit the program.
The program must not stop until Number 3 entered as a choice. Moreover
the program must be smart enough so that NOT TO CONDUCT TRANSFORM FOR
THE VALUES LOWER THAN ABSOLOUTE ZERO and warn the user about that!
Hint 1: Use Select Case and DO WHILE Statements.
See what happens if a real number entered as a choice instead of integer
value.
Hint 2: Use divide and conquer technique! First, do some simple
operation and then step by step add the condition and requirements.


KNTU University Bakhtiari
1386
Fortran Course: Session 4

Files:
A computer file is a block of arbitrary information, or resource for storing information, which is available
to a computer program and is usually based on some kind of durable storage. A file is durable in the sense
that it remains available for programs to use after the current program has finished. Computer files can be
considered as the modern counterpart of paper documents, which traditionally were kept in offices' and
libraries' files, which are the source of the term.


File contents:

As far as the operating system is concerned, a file is just a sequence of binary digits. At a higher level,
where the content of the file is being considered, these binary digits may represent integer values or text
characters, or anything else. It is up to the program using the file to understand the meaning and internal
layout of information in the file and present it to a user as more meaningful information (like text, images,
sounds).
Information in a computer file can consist of smaller packets of information (often called records or lines)
that are individually different but share some trait in common. For example, a payroll file might contain
information concerning all the employees in a company and their payroll details; each record in the payroll
file concerns just one employee, and all the records have the common trait of being related to payrollthis
is very similar to placing all payroll information into a specific filing cabinet in an office that does not have
a computer. A text file may contain lines of text, corresponding to printed lines on a piece of paper.
Alternatively, a file may contain an arbitrary binary image (a BLOB) or it may contain an executable.


Semantics

Although the way programs manipulate files varies according to the operating system and file system
involved, the following operations are typical:

Creating a file with a given name
Setting attributes that control operations on the file
Opening a file to use its contents
Reading or updating the contents
Committing updated contents to durable storage
Closing the file, thereby losing access until it is opened again



Data File Types based on how to access:

In common, there are 3 conventional data file types:
1- Sequent ional
2- Random Access (Direct Access)
3- Binary

KNTU University Bakhtiari
1386
Records and Files
A record is a sequence of values or a sequence of characters. There are three kinds of Fortran records, as
follows:


1- Formatted :
A record containing formatted data that requires translation from internal to external form. Formatted
I/O statements have explicit format specifiers (which can specify list-directed formatting) or namelist
specifiers (for namelist formatting). Only formatted I/O statements can read formatted data.


2- Unformatted :
A record containing unformatted data that is not translated from internal form. An unformatted record
can also contain no data. The internal representation of unformatted data is processor- dependent. Only
unformatted I/O statements can read unformatted data.


3- Endfile :
The last record of a file. An endfile record can be explicitly written to a sequential file by an ENDFILE
statement.

Fortran File Types:
A file is a sequence of records. There are two types of Fortran files, as follows:


1- External
A file that exists in a medium (such as computer disks or terminals) external to the executable program.
Records in an external file must be either all formatted or all unformatted. There are three ways to access
records in external files: sequential, keyed access (VMS only), and direct access.
In sequential access, records are processed in the order in which they appear in the file. In direct access,
records are selected by record number, so they can be processed in any order. In keyed access, records are
processed by key-field value.


2- Internal
Memory (internal storage) that behaves like a file. This type of file provides a way to transfer and convert
data in memory from one format to another. The contents of these files are stored as scalar character
variables.
KNTU University Bakhtiari
1386
OPEN
Statement: Connects an external file to a unit, creates a new file and connects it to a unit, creates a
preconnected file, or changes certain properties of a connection.

Syntax

OPEN ([UNIT=]io-unit [, FILE=name] [, ERR=label] [, IOSTAT=i-var], slist)

io-unit
Is an external unit specifier.

name
Is a character or numeric expression specifying the name of the file to be connected. For more information,
see FILE Specifier and STATUS Specifier.

label
Is the label of the branch target statement that receives control if an error occurs.

i-var
Is a scalar integer variable that is defined as a positive integer (the number of the error message) if an error
occurs, a negative integer if an end-of-file record is encountered, and zero if no error occurs. For more
information, see I/O Status Specifier.

slist
Is one or more of the following OPEN specifiers in the form specifier = value or specifier (each specifier
can appear only once)

Examples:

A)
Open(UNIT=12,File=C:\FlowProperties.txt)

B)
program FILE

implicit none

! Variables

OPEN(UNIT=10,FILE="k:\fg.txt",Err=100)
WRITE(10,*) 3.14159265
CLOSE(10)
STOP
! Body of FILE
100 WRITE(*,*) "Error in opening the file"

end program FILE

KNTU University Bakhtiari
1386
CLOSE
Syntax
CLOSE ( [UNIT=]io-unit )
io-unit
(Input) an external unit specifier.
CLOSE(10)

READ
Sequential
Formatted
READ (eunit, format) [io-list]
Formatted: List-Directed
READ (eunit, * [, iostat] [, err] [, end]) [io-list]

Unformatted
READ (eunit [, iostat] [, err] [, end]) [io-list]
Eunit:Is an external unit specifier, optionally prefaced by UNIT=. UNIT= is required if eunit is not the first
specifier in the list.
format :Is a format specifier. It is optionally prefaced by FMT= if format is the second specifier in the list
and the first specifier indicates a logical or internal unit specifier without the optional keyword UNIT=.

iostat :Is the name of a variable to contain the completion status of the I/O operation. Optionally prefaced
by IOSTAT=.

err, end, eor :Are branch specifiers if an error (ERR=label), end-of-file (END=label), or end-of-record
(EOR=label) condition occurs. EOR can only be specified for nonadvancing READ statements.
io-list :Is an I/O list: the names of the variables, arrays, array elements, or character substrings from which
or to which data will be transferred. Optionally an implied-DO list.




Example:

KNTU University Bakhtiari
1386
PRGRAM Main
IMPLICIT NONE
REAL*4 TEMPERATURE(1:10), PRESSURE(1:10)
INTEGER*2 I

OPEN(UNIT=10,FILE="C:\ Properties.txt",Err=100)
DO I=1,10
READ(10,*) TEMPERATURE(I), PRESSURE(I)
END DO
CLOSE(10)



STOP
100 WRITE(*,*) Warning: Properties File not Found! Program Terminated!
END PROGRAM MAIN


WRITE
Statement: Transfers output data to external sequential, direct-access, or internal records.
Syntax
Sequential
Formatted
WRITE (eunit, format) [io-list]

Internal
WRITE (iunit, format [, iostat] [, err]) [io-list]

eunit :Is an external unit specifier, optionally prefaced by UNIT=. UNIT= is required if eunit is not the first
specifier in the list.
format :Is a format specifier. It is optionally prefaced by FMT= if format is the second specifier in the list
and the first specifier indicates a logical or internal unit specifier without the optional keyword UNIT=.
For internal io-list
Is an I/O list: the names of the variables, arrays, array elements, or character substrings from which or to
which data will be transferred. Optionally an implied-DO list.
KNTU University Bakhtiari
1386
EOF

Inquiry Intrinsic Function (Specific): Checks whether a file is at or beyond the end-of-file record. This is a
specific function that has no generic function associated with it. It must not be passed as an actual
argument.

Syntax

result = EOF (A)

A
(Input) Must be of type integer. It represents a unit specifier corresponding to an open file. It cannot be zero
unless you have reconnected unit zero to a unit other than the screen or keyboard.

Results:

The result type is logical. The value of the result is .TRUE. if the file connected to A is at or beyond the
end-of-file record; otherwise, .FALSE..



!Creates a file of random numbers, reads them back
REAL x, total
INTEGER count
OPEN (1, FILE = 'TEST.DAT')
DO I = 1, 20
CALL RANDOM_NUMBER(x)
WRITE (1, '(F6.3)') x * 100.0
END DO
CLOSE(1)
OPEN (1, FILE = 'TEST.DAT')
DO WHILE (.NOT. EOF(1))
count = count + 1
READ (1, *) value
total = total + value
END DO
100 IF ( count .GT. 0) THEN
WRITE (*,*) 'Average is: ', total / count
ELSE
WRITE (*,*) 'Input file is empty '
END IF
STOP
END
KNTU University Bakhtiari
1386
Summary of Generic Intrinsic Functions

Generic Function Value Returned
ABS (A) The absolute value of an argument
ACOS (X) The arc cosine (in radians) of the argument
AIMAG (Z) The imaginary part of a complex argument
ASIN (X) The arc sine (in radians) of the argument
ATAN (X) The arc tangent (in radians) of the argument

CMPLX (X [,Y]
[,KIND])
The corresponding complex value of the argument
CONJG (Z) The conjugate of a complex number
COS (X) The cosine (in radians) of the argument
COSH (X) The hyperbolic cosine of the argument
EOF (A) .TRUE. or .FALSE. depending on whether a file is beyond the end-of-file
record
EPSILON (X) The number that is almost negligible when compared to one
EXP (X) The exponential value for the argument
EXPONENT (X) The value of the exponent part of a real argument
FRACTION (X) The fractional part of a real argument
HUGE (X) The largest number in the model for the argument
IMAG (Z) See AIMAG








INT (A [,KIND]) The corresponding integer value (truncated) of the argument
ISNAN (X) Tests for Not-a-Number (NaN) values
LOG (X) The natural logarithm of the argument
KNTU University Bakhtiari
1386
LOG10 (X) The common logarithm (base 10) of the argument
MAX (A1, A2 [, A3,...]) The maximum value in the set of arguments
MAX1 (A1, A2 [, A3,...]) The maximum value in the set of real arguments (returned as an integer)
MIN (A1, A2 [, A3,...]) The minimum value in the set of arguments
MIN1 (A1, A2 [, A3,...]) The minimum value in the set of real arguments (returned as an integer)
MOD (A, P) The remainder of the arguments (has the sign of the first argument)

NEAREST (X, S) The nearest different machine-represent able number in a given
direction
NINT (A [,KIND]) A real value rounded to the nearest integer
REAL (A [,KIND]) The corresponding real value of the argument
SIGN (A, B) A value with the sign transferred from its second argument
SIN (X) The sine (in radians) of the argument
SIND (X) The sine (in degrees) of the argument
SINH (X) The hyperbolic sine of the argument
SQRT (X) The square root of the argument
SUM (ARRAY [,DIM]
[,MASK])
The sum of the elements of the argument array
TAN (X) The tangent (in radians) of the argument
TANH (X) The hyperbolic tangent of the argument

KNTU University Bakhtiari
1386
Fortran Course: Session 5

Arrays:
In computer science, an array is a data structure consisting of a group of elements that are accessed by
indexing. In most programming languages, each element has the same data type and the array occupies a
contiguous area of storage. Most programming languages have a built-in array data type.

Some programming languages support array programming (e.g., APL, newer versions of Fortran) which
generalizes operations and functions to work transparently over arrays as they do with scalars, instead of
requiring looping over array members.

Classification:


Arrays can be classified as fixed-sized arrays (sometimes known as static arrays) whose size cannot change
once their storage has been allocated, or dynamic arrays, which can be resized.
Multi-dimensional arrays are accessed using more than one index: one for each dimension.

Indexing
The valid index values of each dimension of an array are a bounded set of integers. Programming
environments that check indexes for validity are said to perform bounds checking.


Index of the first element
The index of the first element varies by language. There are three main implementations: zero-based, one-
based, and n-based arrays, for which the first element has an index of zero, one, or a programmer-specified
value. The zero-based array was made popular by the C programming language, in which the abstraction of
array is very weak, and an index n of an array is simply the address of the first element offset by n units.
One-based arrays are based on traditional mathematics notation. n-based is made available so the
programmer is free to choose the lower bound, which is best, suited for the problem at hand.

Supporters of zero-based indexing often incorrectly criticize one-based and n-based arrays for being slower.
However, a one-based or n-based array access can be optimized with common sub expression elimination
or with a well-defined dope vector.

The 0-based/1-based debate is not limited to just programming languages. For example, the ground-floor of
a building is elevator button "0" in France, but elevator button "1" in the USA.

Multi-dimensional arrays
Ordinary arrays are indexed by a single integer. Also useful, particularly in numerical and graphics
applications, is the concept of a multi-dimensional array, in which we index into the array using an ordered
list of integers, such as in a[3,1,5]. The number of integers in the list used to index into the multi-
dimensional array is always the same and is referred to as the array's dimensionality, and the bounds on
each of these are called the array's dimensions. An array with dimensionality k is often called k-
dimensional. One-dimensional arrays correspond to the simple arrays discussed thus far; two-dimensional
arrays are a particularly common representation for matrices. In practice, the dimensionality of an array
rarely exceeds three. Mapping a one-dimensional array into memory is obvious, since memory is logically
itself a (very large) one-dimensional array. When we reach higher-dimensional arrays, however, the
problem is no longer obvious.
KNTU University Bakhtiari
1386
Array in Fortran:

In Fortran we have two types of definition for Arrays:
- Assumed Shaped Arrays
- Allocatable Arrays

Assumed Shaped Arrays:

Assumed Shaped arrays are defined just for one time with fixed size, which can not be changed through the
program. There are several simple ways to define an assumed shaped array. Here you can find examples:

Note: The default lower bound for an array in Fortran is 1

REAL*8, DIMENSION(0:10,0:20) :: Nodes
REAL*8 Nodes(0:10,0:20)

INTEGER*2 Table1(10,10) ! Which is equal to below:
INTEGER*2, DIMENSION(1:10,1:10):: Table1

When you passed an array to a subroutine, the data will be passed not the bounds, which means that you
can use different bound in you subroutines:

REAL, DIMENSION(0:10, 0:20) :: a
:
CALL sub(a)

the corresponding dummy argument specification defines only the type and rank of the array, not its size.
This information has
to be made available by an explicit interface, often using an interface block (see part 4). Thus we write just

SUBROUTINE sub(da)
REAL, DIMENSION(:, :) :: da


and this is as if da were dimensioned (11,21). However, we can specify any lower bound and the array
maps accordingly. The shape, not bounds, is passed, where the default lower bound is 1 and the default
upper bound is the corresponding extent. Also the folowings are valid:

SUBROUTINE sub(da)
REAL, DIMENSION(-1:9,10 :30) :: da

SUBROUTINE sub(da)
REAL, DIMENSION (0:10, 0:20) :: da
KNTU University Bakhtiari
1386
ALLOCATABLE and ALLOCATE

Fortran provides dynamic allocation of storage; it relies on a heap storage mechanism (and replaces
another use of EQUIVALENCE).
An example, for establishing a work array for a whole program, is:

PROGRAM TEST1
IMPLICIT NONE
REAL*4,DIMENSION( : , :) , ALLOCATABLE:: TEMPERATURES
INTEGER*2 XnoNodes,YnoNodes
WRITE(*,*) PLEASE ENTER NUMBER OF NODES IN X DIRECTION
READ(*,*) XnoNodes
WRITE(*,*) PLEASE ENTER NUMBER OF NODES IN Y DIRECTION
READ(*,*) YnoNodes
ALLOCATE(TEMPERATURES(1:XnoNodes,1:YnoNodes))
.
.
.


DEALLOCATE STATEMENT
Every time you allocate an array , after you finished your job with the array deallocate the array to
free memory!
( Continued from above example)

.
.
.
DEALLOCATE(TEMPERATURES)
END PROGRAM TEST1

ALLOCATED LOGICAL STATEMENT:
If in some place in your program you do not know if the array is allocated or not, you can use the
following statement for check:

PROGRAM TEST2
IMPLICIT NONE
REAL*4, DIMENSION( : ),ALLOCATABLE:: Pressures
INTEGER*2 NodesNo
WRITE(*,*) PLEASE ENTER THE NUMBER OF NODES
READ(*,*) NodesNo
.
.
.

IF(ALLOCATED(Pressures)) THEN
DEALLOCATE(Pressures)
END IF
ALLOCATE(Pressure(0:NoNodes-1))
KNTU University Bakhtiari
1386
Elemental operations and assignments

We have whole array assignments and operations:
EXAMPLE:
REAL*4, DIMENSION(1: 10) :: a, b
a = 0.5 ! scalar broadcast; elemental assignment
b = sqrt(a) ! intrinsic function result as array object

Also we can use partial assignments:

program ARRAY

implicit none

! Variables
REAL*4:: HU(0:10,5:10)
REAL*4:: AU(10:20,10:15)
.
.
.

HU(2:7,3:4)=SQRT(AU(12:17,11:12))
.
.
.
WHERE STATEMENT:
You can use WHERE statement to avoid making loop around array bounds:
EXAMPLE:

WHERE (a /= 0.0) a = 1.0/a ! avoid division by 0
:
WHERE (a /= 0.0)
a = 1.0/a
b = a
END WHERE

WHERE (a /= 0.0)
a = 1.0/a
ELSEWHERE
a = HUGE(a)
END WHERE
Note: If you are using more than one array in the where statement, all arrays most have similar shape and
size.

Note: Avoid WHERE statement when the performance is important for you!
KNTU University Bakhtiari
1386

Array subobjects (sections)
The general form of subscript for an array section is
[lower] : [upper] [:stride ]

EXAMPLE:
REAL a(10, 10)
a(i, 1:n) ! part of one row
a(1:m, j) ! part of one column
a(i, : ) ! whole row
a(i, 1:n:3) ! every third element of row
a(i, 10:1:-1) ! row in reverse order
a( (/ 1, 7, 3, 2 /), 1) ! vector subscript
a(1, 2:11:2) ! 11 is legal as not referenced
a(:, 1:7) ! rank two section


Arrays intrinsic functions

Vector and matrix multiply

DOT_PRODUCT Dot product of 2 rank-one arrays
MATMUL Matrix multiplication
Array reduction
ALL True if all values are true
ANY True if any value is true. Example: IF (ANY( a > b)) THEN
COUNT Number of true elements in array
MAXVAL Maximum value in an array
MINVAL Minimum value in an array
SUM Sum of array elements
Array inquiry
ALLOCATED Array allocation status
LBOUND Lower dimension bounds of an array
SIZE Total number of elements in an array
UBOUND Upper dimension bounds of an array
Array manipulation
TRANSPOSE Transpose of an array of rank two
Array location
MAXLOC Location of first maximum value in an array
MINLOC Location of first minimum value in an array


KNTU University Bakhtiari
1386
Exercises:

5-1) Write a program which deifne a m x n array, calculate the Multiplication Table and place the result in
the array with corresponding to indexes. Then put the results in a file which has 3 columns, column one the
first index, column two the second index and column three the value. The values of n and m should be
given from user.

5-2) Add a section to above program for calculating the summation of the numbers in the table by using
loops and display the result.
5-3) Add another section to above program to calculate the summation of the number in the last columns
by using SUM statement and show the results.
5-4) Add another section, to count all values, which are greater than 50 by using COUNT statement.
KNTU University Bakhtiari
1386
Fortran Course: Session 6

Subprograms:
In computer science, a subprogram (function, method, procedure, or subroutine) is a portion of code within
a larger program, which performs a specific task and can be relatively independent of the remaining code.
The syntax of many programming languages includes support for creating self contained subprograms, and
for calling and returning from them.

There are many advantages to breaking a program up into subprogram, including:

reducing the duplication of code in a program (e.g., by replicating useful functionality, such as
mathematical functions),
enabling reuse of code across multiple programs,
decomposing complex problems into simpler pieces (this improves maintainability and ease of
extension),
improving readability of a program,
hiding or regulating part of the program

The components of a subroutine may include:
a body of code to be executed when the subroutine is called
parameters that are passed to the subroutine from the point where it is called
a value that is returned to the point where the call occurs

Many programming languages, such as Pascal , FORTRAN, Ada, distinguish between functions or function
subprograms, which return values (via a return statement), and subroutines or procedures, which do not.
Some languages, such as C and LISP, do not make this distinction, and treat those terms as synonymous.
The name method is commonly used in connection with object-oriented programming, specifically for
subroutines that are part of objects; it is also used in conjunction with type classes.
KNTU University Bakhtiari
1386
Fortran Program units and procedure:

In order to discuss this topic we need some definitions. In logical terms, an executable program consists of
one main program and zero or more subprograms (or procedures) - these do something. Subprograms are
either functions or subroutines, which are either external, internal or module subroutines. From an
organizational point of view, however, a complete program consists of program units. These are either main
programs, external subprograms or modules and can be separately compiled.



Subroutines ( Internal and external):

A subroutine is a procedure that may return or may not return value(s) despite the functions, which should
return value. An internal subprogram is one contained in another (at a maximum of one level of nesting).


SUBROUTINE outer
REAL*4 x, y
:
CONTAINS
SUBROUTINE inner
REAL*4 y
y = x + 1.
:
END SUBROUTINE inner ! SUBROUTINE mandatory
END SUBROUTINE outer

We say that outer is the host of inner, and that inner obtains access to entities in outer by host association
(e.g. to x), whereas y is a local variable to inner. The scope of a named entity is a scoping unit, here outer
less inner, and inner. The names of program units and external procedures are global, and the names of
implied-DO variables have a scope of the statement that contains them. Subroutines can be accessed by
using CALL statement.

CALL outer()


FUNCTIONS
A function subprogram is invoked in an expression and returns a single value (a function result) that is
used to evaluate the expression. Functions like math can be accessed by simply assigning their values. The
declaration of a function is done by using FUNCTION statement:

[prefix] FUNCTION name ([d-arg-list]) [RESULT (r-name)]

prefix
(Optional) Is one of the following:

type [keyword]
keyword [type]
type
Is a data type specifier.

keyword
Is one of the following:

Keyword Meaning
KNTU University Bakhtiari
1386
RECURSIVE Permits direct recursion to occur. If a function is directly recursive and array valued,
RESULT must also be specified.
PURE Asserts that the procedure has no side effects.
ELEMENTAL Restricted form of pure procedure that acts on one array element at a time.

name
Is the name of the function. If RESULT is specified, the function name must not appear in any specification
statement in the scoping unit of the function subprogram.

The function name can be followed by the length of the data type. The length is specified by an asterisk (*)
followed by any unsigned, nonzero integer that is a valid length for the function's type. For example, REAL
FUNCTION LGFUNC*8 (Y, Z) specifies the function result as REAL(8) (or REAL*8).

This optional length specification is not permitted if the length has already been specified following the
keyword CHARACTER.

d-arg-list
(Optional) Is a list of one or more dummy arguments.

Passing arguments to subroutines and functions:

We assumed that we have two kinds of arguments:
1- single value arguments.
2- Arrays
1)To pass single value arguments simply pass them as following example:

Subrouitne ADD1(A,B,C)
REAL*4 A,B,C
C=A+B
END SUBROUTINE ADD1

Same as:

FUNCTION ADD1(A,B)
REAL*4 ADD1,A,B
ADD1=A+B
END FUNCTION

Same as:
REAL*4 FUNCTION ADD1(A,B)
REAL*4 A,B
ADD1=A+B
END FUNCTION
KNTU University Bakhtiari
1386
2) To pass arrays to Subroutines and Functions, you can use several methods as can be seen in examples:

PROGRAM MAIN
REAL*4 :: A(1:20)
REAL*4 :B
INTEGER*2 n
.
.
.
CALL SUB1(A)
! ALTERNATIVE
n=20
CALL SUB2(A,n)
.
END PROGRAM MAIN

SUBROUTINE SUB1(A)
REAL*4,DIMENSION(:)::A
! REAL*4 ,DIMENSION(1:10)::A
!REAL*4 A(1:20)
END SUBROUTINE SUB1

Or:

SUBROUTINE SUB2(A,n)
INTEGER*2 n
REAL*4,DIMENSION(1:n)::A
END SUBROUTINE SUB2


Arguments intention and optional arguments:

We may specify the intent of dummy arguments:


SUBROUTINE shuffle (ncards, cards)
INTEGER, INTENT(IN) :: ncards ! input values
INTEGER, INTENT(OUT), DIMENSION(ncards) :: cards ! output values
Also, INOUT is possible: here the actual argument must be a variable (unlike the default case where it may
be a constant).


Arguments may be optional:
SUBROUTINE mincon(n, f, x, upper, lower, equalities, inequalities, convex, xstart)
REAL, OPTIONAL, DIMENSION :: upper, lower
.
.
allows us to call mincon by
CALL mincon (n, f, x, upper)
and in mincon we have something like:
IF (PRESENT(lower)) THEN ! test for presence of actual argument
KNTU University Bakhtiari
1386

MODULES:

Modules are used to package
global data
type definitions (themselves a scoping unit);
subprograms ;
interface blocks;
namelist groups.

EXAMPLE:


MODULE MATH
IMPLICIT NONE
REAL*4,PUBLIC :: Pi
PARAMETERS(Pi=3.14159265)
CONTAINS
REAL*4 FUNCTION CircleArea(Radious)
REAL*4 Radious
CircleArea=Pi*(Radious**2.0)
END FUNCTION
.
.
.

END MODULE MATH


PROGRAM MAIN
USE MATH
IMPLICIT NONE
REAL*4 Radious
WRITE(*,*) PLEASE ENTER THE RADIOUS
READ(*,*) Radious
WRITE(*,*) The circle are is:
WRITE(*,*) CircleArea(Radious)
WRITE(*,*) With PI number is equal to:
WRITE(*,*) Pi

END PROGRAM MAIN

KNTU University Bakhtiari
1386

Using Function as arguments:
We can use functions as arguments. This could improve programming with shortening the code required to
be written.

MODULE FUNCS
IMPLICIT NONE
CONTAINS
REAL*4 FUNCTION F(x)
REAL*4 x
F=x**2.0
END FUNCTION
REAL*4 FUNCTION G(x)
REAL*4 x
G=x**3.0
END FUNCTION
END MODULE FUNCS

MODULE INTEGRATION
USE FUNCS
IMPLICIT NONE
CONTAINS
REAL*4 FUNCTION INTEGRATE( lowerbound, upperbound , function)
REAL*4 lowerbound,upperbound
REAL*4,EXTERNAL :: function
REAL*4 time
time=(lowerbound+upperbound)/2.0
INTEGRATE= function (time)*(upperbound-lowerbound)
END FUNCTION
END MODULE INTEGRATION
PROGRAM MAIN
USE FUNCS
USE INTEGRATION
WRITE(*,*) INTEGRATE(1.0,2.0,F)
WRITE(*,*) INTEGRATE(1.0,2.0,G)
END PROGRAM MAIN

Recursion
Recursion in computer programming defines a function in terms of itself. One example application of
recursion is in recursive descent parsers for programming languages. The great advantage of recursion is
that an infinite set of possible sentences, designs, or other data can be defined, parsed, or produced by a
finite computer program. In FORTRAN we have two kind of recursion: direct and indirect.

Here you can find a example for direct recursive function. For indirect example and usage see page 11 on
Fortran 90 tutorial.

RECURSIVE FUNCTION factorial(n) RESULT(res)
INTEGER res, n
IF(n.EQ.1) THEN
res = 1
ELSE
res = n*factorial(n-1)
END IF
END FUNCTION
KNTU University Bakhtiari
1386
Specification Statements
This part completes what we have learned so far about specification statements.
Implicit typing
It is good practice to explicitly type all variables, and this can be forced by inserting the statement
IMPLICIT NONE
at the beginning of each program unit.

PARAMETER attribute

A named constant can be specified directly by adding the PARAMETER attribute and the constant values
to a type statement:

REAL, DIMENSION(3), PARAMETER :: field = (/ 0., 1., 2. /)
REAL*4, PARAMETER:: Pi=3.14159265

DATA statement
The DATA statement can be used also for arrays and variables of derived type. It is also the only way to
initialize just parts of
such objects, as well as to initialize to binary, octal or hexadecimal values:

DATA array(1:64) / 64*0/ ! only a section of array initialized
DATA i, j, k/ B'01010101', O'77', Z'ff'/

Characters
There are many variations on the way character arrays may be specified. Among the shortest and longest
are
CHARACTER name(4, 5)*20

RESHAPE and TRANSFER:

It is possible to specify details of variables using any non-constant, scalar, integer expression that may also
include inquiry function references:

SUBROUTINE s(b, m, c)
USE mod ! contains a
REAL, DIMENSION(:, :) :: b ! assumed-shape array
REAL, DIMENSION(UBOUND(b, 1) + 5) :: x ! automatic array
INTEGER m
CHARACTER(LEN=*) c ! assumed-length
CHARACTER(LEN= m + LEN(c)) cc ! automatic object
REAL (SELECTED_REAL_KIND(2*PRECISION(a))) z ! precision of z twice that of a


PUBLIC and PRIVATE

These attributes are used in specifications in modules to limit the scope of entities. The attribute form is
REAL, PUBLIC :: x, y, z ! default
INTEGER, PRIVATE :: u, v, w
and the statement form is
PUBLIC :: x, y, z
PRIVATE :: u, v, w
The statement form has to be used to limit access to operators, and can also be used to change the overall
default:
PRIVATE ! sets default for module
PUBLIC :: only_this
KNTU University Bakhtiari
1386
Fortran Course: Session 7

Data structure:
In computer science, a data structure is a way of storing data in a computer so that it can be used efficiently.
Often a carefully chosen data structure will allow the most efficient algorithm to be used. The choice of the
data structure often begins from the choice of an abstract data type. A well-designed data structure allows a
variety of critical operations to be performed, using as few resources, both execution time and memory
space, as possible. Data structures are implemented using the data types, references, and operations on them
provided by a programming language.

Different kinds of data structures are suited to different kinds of applications, and some are highly
specialized to certain tasks. For example, B-trees are particularly well-suited for implementation of
databases, while routing tables rely on networks of machines to function.

In the design of many types of programs, the choice of data structures is a primary design consideration, as
experience in building large systems has shown that the difficulty of implementation and the quality and
performance of the final result depends heavily on choosing the best data structure. After the data structures
are chosen, the algorithms to be used often become relatively obvious. Sometimes things work in the
opposite direction - data structures are chosen because certain key tasks have algorithms that work best
with particular data structures. In either case, the choice of appropriate data structures is crucial.


Abstract data type:
In computing, an abstract data type (ADT) is a specification of a set of data and the set of operations that
can be performed on the data. Such a data type is abstract in the sense that it is independent of various
concrete implementations. The definition can be mathematical, or it can be programmed as an interface. A
first class ADT supports the creation of multiple instances of the ADT, and the interface normally provides
a constructor, which returns an abstract handle to new data, and several operations, which are functions
accepting the abstract handle as an argument.

Example of ADT or derived types:
Point : X Y Z
Coordinate: latitude longitude altitude
Airflow: Temperature, Pressure, Mach number, Density &....

Implementation in FORTRAN:
In FORTRAN ADTs called derived types. Derived types could be constructed from five known intrinsic
DATA types, which mentioned below:
1- INTEGER
2- REAL
3- COMPLEX
4- LOGICAL
5- CHARACTER
For Example:
Each coordinate could be constructed from 3 REAL*4 variables which indicating to lat long alt
Each signal could be constructed from phase and domain as two REAL variables
Each student record could be constructed from 2 CHARACTER string for given and surname and
an integer number as student number
KNTU University Bakhtiari
1386

Advantage of using derived types:

We can mention several advantages for ADTs or derived types:
1- Efficient memory and storage usage
2- Improvement in readability
3- Improvement in reliability
4- Briefing arguments passing
5- Enhanced control over operations, functions, subroutines
6- Improvement in code exchange between programs and standard code development.


Derived Types Definition:

Fortran 90 (and above) allows compound entities or derived types to be defined. The definition could be
done by using TYPE statement.
MODULE DRVTYPES
IMPLICIT NONE
TYPE COORDS_3D
REAL*4 x
REAL*4 y
REAL*4 z
END TYPE COORDS_3D
END MODULE DRVTYPES

Derived types definitions should be placed in a MODULE.

Defining variables as derived type is easily could be done like example below:

PROGRAM MAIN
USE DRVTYPES
TYPE(COORDS_3D) :: point_1, point_2
.
.
.
END PROGRAM MAIN

Supertypes

Previously defined types can be used as components of other derived types,


TYPE SPHERE
TYPE (COORDS_3D) :: centre
REAL :: radius
END TYPE SPHERE
Objects of type SPHERE can be declared:


TYPE (SPHERE) :: bubble, ball





KNTU University Bakhtiari
1386
Derived Type Assignment

Values can be assigned to derived types in two ways:



1- Component by component;

2- as an object.
An individual component may be selected, using the % operator:


Point_1%x = 1.0
bubble%radius = 3.0
bubble%centre%x = 1.0
The whole object may be selected and assigned to using a constructor:

point_1 = COORDS_3D(1.,2.,3.)
bubble%centre = COORDS_3D(1.,2.,3.)
bubble = SPHERE(bubble%centre,10.)
bubble = SPHERE(COORDS_3D(1.,2.,3.),10.)
The derived type component of SPHERE must also be assigned to using a constructor.
Assignment between two objects of the same derived type is intrinsically defined,

ball = bubble

Arrays and Derived Types
It is possible to define derived type objects, which contain non-ALLOCATABLE arrays and arrays of
derived type objects.

Consider,

TYPE NODE ! refer to a structural node
TYPE(COORDS_3D) ::crd
REAL*4 ,DIMENSION(1:3,1:3) ::TENSOR ! refer to stress tensor
END TYPE NODE

And we can define followings:

TYPE(NODE):: BEAM_1(1:10)
TYPE(NODE),DIMENSION(:,:),ALLOCATABLE:: PLATE_1
.
.
.
ALLOCATE (PLATE_1(1 :XNo,1 :Yno))

We can refer to an element or subsection of the array component:

BEAM_1(5)
BEAM_1(5)%TENSOR(1,1)
BEAM_1(5)%TENSOR(1:3,1:2)
PLATE_1(2:7,1)%TENSOR(2,3)



KNTU University Bakhtiari
1386
but not a collection of elements or subsections of the array component:

BEAM_1(2:4)%TENSOR(1:2,2:3) ! COMPILR ERROR!!!
BEAM_1(:)%TENSOR(:,2) ! COMPILR ERROR!!!

Derived Type I/O
Derived type objects, which do not contain pointers (or private), components may be input or output using
`normal' methods:


PRINT*, bubble
is exactly equivalent to

PRINT*, bubble%centre%x, bubble%centre%y, bubble%centre%z, bubble%radius

Derived types are handled on a component by component basis.

Derived Types and Procedures
Derived types definitions should be packaged in a MODULE. And you can use them in procedures like
example below:


MODULE DRVTYPES
IMPLICIT NONE
TYPE COORDS_3D
REAL*4 x
REAL*4 y
REAL*4 z
END TYPE COORDS_3D
END MODULE DRVTYPES
MODULE FUNCS
! to make the type definitions visible, the module must be used:
USE DRVTYPES
IMPLICIT NONE
REAL*4 FUNCTION DISTANCE(p1,p2)
TYPE(COORD_3D)::p1,p2
DISTANCE=(p1%x-p2%x)**2.0+(p1%y-p2%y)**2.0+(p1%z-p2%z)**2.0
DISTANCE=SQRT(DISTANCE)
END FUNCTION
END MODULE FUNCS


PROGRAM MAIN
USE DRVTYPES
USE FUNCS
IMPLICIT NONE
TYPE(COORD_3D) :: centre, origin
REAL*4 length
.
.
.
Length=DISTANCE(origin,centre)
.
END PROGRAM MAIN
Type definitions can only become accessible by use association.
KNTU University Bakhtiari
1386
Derived Type Valued Functions

Functions can return results of an arbitrary defined type


FUNCTION midpoint(p1,p2)
USE DRVTYPES
TYPE (COORD_3D) :: midpoint
TYPE (COORD_3D), INTENT(IN) :: p1,p2
Midpoint%x=(p1%x+p2%x)/2.0
Midpoint%y=(p1%y+p2%y)/2.0
Midpoint%z=(p1%z+p2%z)/2.0
END FUNCTION

Recall that the definitions of DRVTYPES must be made available by use association.



KNTU University Bakhtiari
1386
Exercises:

Write a program, which has two derived, types named VECTOR and POINT and defined in a module
named DRVTYPES.
VECTOR indicates to mathematical vectors and POINT indicates to coordinate in Cartesian space.
The program should be able to conduct following operations on VECTOR and POINT data type in a
different module named FUNCS by multiple functions or subroutines:
1- generating vector form two given points.
2- Adding and subtracting two given vectors
3- Calculating dot product and cross product of two given vector ( The result should be a vector)
4- Calculating new coordinate of a point after transferred along a given vector ( The result should be
a point)
5- Calculating normal vector of a given vector (The result should be a vector)
6- Calculating length of a given vector
7- generating a vector form array of n given points in predetermined order

Hint: Use following declaration for you derived types

TYPE POINT
REAL*4 x
REAL*4 y
REAL*4 z
END TYPE
TYPE VECTOR
REAL*4 i
REAL*4 j
REAL*4 k
END TYPE


KNTU University Bakhtiari
1386
Fortran Course: Session 8

Pointers:
In computer science, a pointer is a programming language data type whose value refers directly to (or
points to) another value stored elsewhere in the computer memory using its address. Obtaining the value
to which a pointer refers is called dereferencing the pointer. A pointer is a simple implementation of the
general reference data type (although it is quite different from the facility referred to as a reference in C++).

Pointers are so commonly used as references that sometimes people use the word pointer to refer to
references in general; however, more properly it only applies to data structures whose interface explicitly
allows it to be manipulated as a memory address.

What is a pointer contains?
A pointer usually contains the address of target object in the memory (there is a little difference between
Fortran and other languages, which will be explained latter). A pointer does not have any value until it
referenced to an object. With help of following example (C++), you can find out what happens in a
pointer:

int a = 5;
int *money = NULL;

Variable Memory Address Contents
a 0x8130 0x00000005
money 0x8134 0x00000000

(The NULL pointer shown here is 0x00000000.) By assigning the address of "a" to "money":

money = &a;

yields the following memory values:

Variable Memory Address Contents
a 0x8130 0x00000005
money 0x8134 0x00008130
Then by dereferencing money by doing

*money = 8;

KNTU University Bakhtiari
1386
the computer will take the contents of money (which is 0x8130), go to that address, and assign 8 to that
location yielding the following memory.

Variable Memory Address Contents
a 0x8130 0x00000008
money 0x8134 0x00008130
Clearly, accessing a will yield the value of 8 because the previous instruction modified the contents of a by
way of the pointer money.

Fortran

Fortran-90 introduced a strongly typed pointer capability. Fortran pointers contain more than just a simple
memory address. They also encapsulate the lower and upper bounds of array dimensions, strides (for
example, to support arbitrary array sections), and other metadata. An association operator => is used to
associate a POINTER to a variable which has a TARGET attribute. The Fortran-90 ALLOCATE statement
may also be used to associate a pointer to a block of memory.

Basics

Pointers are variables with the POINTER attribute; they are not a distinct data type (and so no pointer
arithmetic is possible):
REAL, POINTER :: var

They are conceptually a descriptor listing the attributes of the objects (targets) that the pointer may point to,
and the address, if any, of a target. They have no associated storage until it is allocated or otherwise
associated (by pointer assignment, see below):

ALLOCATE (var)

in addition, they are dereferenced automatically, so no special symbol is required. In

var = var + 2.3

the value of the target of var is used and modified. Pointers cannot be transferred via I/Othe statement

WRITE *, var

writes the value of the target of var and not the pointer descriptor itself.
A pointer can point to other pointers, and hence to their targets, or to a static object that has the TARGET
attribute:

REAL, POINTER :: object
REAL, TARGET :: target_obj
var => object ! pointer assignment
var => target_obj


KNTU University Bakhtiari
1386
however, they are strongly typed:

INTEGER, POINTER :: int_var
var => int_var ! illegal - types must match and, similarly, for arrays the ranks as well as the type must
agree.

A pointer can be a component of a derived data type:

TYPE entry ! type for sparse matrix
REAL value
INTEGER index
END TYPE entry
and we can define the beginning of a linked chain of such entries:
TYPE(entry), POINTER :: chain

Association

A pointers association status is one of
undefined (initial state);
associated (after allocation or a pointer assignment);
disassociated:
DEALLOCATE (p, q) ! for returning storage
NULLIFY (p, q) ! for setting to 'null'

Some care has to be taken not to leave a pointer dangling by use of DEALLOCATE on its target without
NULLIFYing any other pointer referring to it.
The intrinsic function ASSOCIATED can test the association status of a defined pointer:

IF (ASSOCIATED(pointer)) THEN

or between a defined pointer and a defined target (which may, itself, be a pointer):

IF (ASSOCIATED(pointer, target)) THEN

KNTU University Bakhtiari
1386
Pointers in expressions and assignments

For intrinsic types, we can sweep pointers over different sets of target data using the same code without
any data movement.
Given the matrix manipulationy = B C z
, we can write the following code (although, in this case, the same result could be
achieved more simply by other means):

REAL, TARGET :: b(10,10), c(10,10), r(10), s(10, z(10)
REAL, POINTER :: a(:,:), x(:), y(:)
INTEGER mult
:
DO mult = 1, 2
IF (mult == 1) THEN
y => r ! no data movement
a => c
x => z
ELSE
y => s ! no data movement
a => b
x => r
END IF
y = MATMUL(a, x) ! common calculation
END DO

Pointer arguments

If an actual argument is a pointer then, if the dummy argument is also a pointer,
it must have same rank,
it receives its association status from the actual argument,
it returns its final association status to the actual argument (note: the target may be undefined!),
it may not have the INTENT attribute (it would be ambiguous),
it requires an interface block.
If the dummy argument is not a pointer, it becomes associated with the target of the actual argument:
REAL, POINTER :: a(:,:)
:
ALLOCATE (a(80, 80))
:
CALL sub(a)
:
SUBROUTINE sub(c)
REAL c(:, :)
KNTU University Bakhtiari
1386
Derived data types and Arrays of pointers

We can simply define arrays of pointers like intrinsic and derived data types:

program POINTERTEST
implicit none
INTEGER*2,DIMENSION(:),ALLOCATABLE,TARGET:: A
INTEGER*2,DIMENSION(:),POINTER:: B
ALLOCATE(A(1:10))
B=>A
end program POINTERTEST

Please note that POINTERS are intrinsically allocatable, so you can not use ALLOCATABLE attribute for
them:

INTEGER*2,DIMENSION(:),ALLOCATABLE,POINTER:: B !!!!COMPILE ERROR

You can use pointers in derived data types. See the following example:

TYPE row
REAL, POINTER :: r(:)
END TYPE
and then defining arrays of this data type:
TYPE(row) :: s(n), t(n)
where the storage for the rows can be allocated by, for instance,
DO i = 1, n
ALLOCATE (t(i)%r(1:i)) ! Allocate row i of length i
END DO
The array assignment
s = t
is then equivalent to the pointer assignments
s(i)%r => t(i)%r
for all components.
KNTU University Bakhtiari
1386
Example of using pointers:

Consider following problem. We have a thin triangular plate, which we want to estimate transient
temperature distribution over it by using triangular elements.
Suggested method says use vertexes temperatures of each element at time step n to update the temperature
of element center at time step n+1 (which will be considered as element temperature) and then it will be
used to update the temperatures at vortexes for time step n+1. Then iterate the method until desired time.
The problem is that: several vertexes are shared between different cells. So if we declared a derived type
CELL which consists of 3 vertexes and 1 center point, at any time step we have to find out neighbors cells
and the shared vertexes between current cell and those cells and then update those cells vertexes. This could
need extremely complicated algorithm. Hence, we need a method to share each given vertexes between
several cells, and that is where the POINTERS come in with great assistance. Consider following
algorithm:
We declare a derived type, which named POINT:
TYPE POINT
real*8 X
real*8 Y
INTEGER*4 No ! Vertex Number
REAL*8 Vn ! Properties at timestep n
REAL*8 VnP1 ! Properties at timestep n+1 (n PLus 1)
LOGICAL*1 B ! indicates that the node is internal or on the boundary
INTEGER*4 inc(0:6) ! indicates to cells which included this point
END TYPE POINT
KNTU University Bakhtiari
1386
And another derived type, which named CELL:
TYPE CELL
!INTEGER*4 CellNo
! Type 1 internal, type 2 boundary, type 3 sym internal, type 4 sym boundary
INTEGER*1 CellType
TYPE(POINT) ,POINTER::P1
TYPE(POINT) ,POINTER::P2
TYPE(POINT) ,POINTER::P3
TYPE(POINT) Pcn ! Element Center
REAL*8 d1
REAL*8 d2
REAL*8 d3
INTEGER*4 Nighbs(1:3)
LOGICAL*1 LR ! left or right
END TYPE
As can be seen derived type, CELL contains 3 instance of object POINT which are all pointers. So we can
share vertexes between several cells without wasting memory storage or complicating the algorithm. To do
so we define two allocatable arrays of above types:

TYPE(Cell), Dimension(:),ALLOCATABLE,Target::MeshedDomain
TYPE(POINT), Dimension(:),ALLOCATABLE,TARGET::Nodes

After allocating those arrays to desired size we can use following procedure:
1- first, we produce all vertexes in a left to right and bottom to top procedure as derived type POINT.
The results stored in the array named Nodes
2- Then using same procedure (left to right, bottom to top) to produce elements. At this step instead
of creating new instance of POINT object for each element's vertex, we just simply referencing the
vertexes to their values in Nodes array. By this method, cells can share vertexes without
complicating the algorithm or wasting memory.
Every time we change a value of Temperature at any given vertex, this value automatically will be
updated for all cells, which share this vertex. The efficiency and simplicity of this method is obvious.

KNTU University Bakhtiari
1386
Fortran Course: Session 9

Dynamic Link Libraries (DLLs):
Dynamic-link library (also written without the hyphen), or DLL, is Microsoft's implementation of the
shared library concept in the Microsoft Windows and OS/2 operating systems. These libraries usually have
the file extension DLL, OCX (for libraries containing ActiveX controls), or DRV (for legacy system
drivers).
The file formats for DLLs are the same as for Windows EXE files that is, Portable Executable (PE) for
32-bit Windows, and New Executable (NE) for 16-bit Windows. As with EXEs, DLLs can contain code,
data, and resources, in any combination.

Background:
The original purpose for DLLs was saving both disk space and memory required for applications by storing
it locally on the hard drive. In a conventional non-shared library, sections of code are simply added to the
calling program; if two programs use the same routine, the code has to be included in both. Instead, code
which multiple applications share can be separated into a DLL which only exists as a single, separate file,
loaded only once into memory during usage. Extensive use of DLLs allowed early versions of Windows to
work under tight memory conditions.

DLLs provide the standard benefits of shared libraries, such as modularity. Modularity allows changes to be
made to code and data in a single self-contained DLL shared by several applications without any change to
the applications themselves. This basic form of modularity allows for relatively compact patches and
service packs for large applications, such as Microsoft Office, Microsoft Visual Studio, and even Microsoft
Windows itself.

Another benefit of the modularity is the use of generic interfaces for plug-ins. A single interface may be
developed which allows old as well as new modules to be integrated seamlessly at run-time into pre-
existing applications, without any modification to the application itself. This concept of dynamic
extensibility is taken to the extreme with ActiveX.

While DLLs provide many benefits, they have a number of drawbacks, collectively called "DLL hell".
Currently, Microsoft .NET is promoted as a solution to the problems of DLL hell.

Features:
Memory management
In Win32, the DLL files are organized into sections. Each section has its own set of attributes, such as
being writable or read-only, executable (for code) or non-executable (for data), and so on.

The code in a DLL is usually shared among all the processes that use the DLL; that is, they occupy a single
place in physical memory, and do not take up space in the page file. If the physical memory occupied by a
code section is to be reclaimed, its contents are discarded, and later reloaded directly from the DLL file as
necessary.

In contrast to code sections, the data sections of a DLL are usually private; that is, each process using the
DLL has its own copy of all the DLL's data. Optionally, data sections can be made shared, allowing inter-
process communication via this shared memory area. However, because user restrictions do not apply to the
use of shared DLL memory, this creates a security hole; namely, one process can corrupt the shared data,
which will likely cause all other sharing processes to behave undesirably. For example, a process running
under a guest account can in this way corrupt another process running under a privileged account. This is an
important reason to avoid the use of shared sections in DLLs.

If a DLL is compressed by certain executable packers (e.g. UPX), all of its code sections are marked as
read-and-write, and will be unshared. Read-and-write code sections, much like private data sections, are
KNTU University Bakhtiari
1386
private to each process. Thus, DLL's with shared data sections should not be compressed if they are
intended to be used simultaneously by multiple programs, since each program instance would have to carry
its own copy of the DLL, resulting in increased memory consumption.

Import libraries
Linking to dynamic libraries is usually handled by linking to an import library when building or linking to
create an executable file. The created executable then contains an import address table (IAT) to which all
Dll function calls are referenced (each referenced Dll function contains its own entry in the IAT). At run-
time, the IAT is filled with appropriate addresses that point directly to a function in the separately-loaded
Dll.

Like static libraries, import libraries for DLLs are noted by the .lib file extension. For example,
kernel32.dll, the primary dynamic library for Windows' base functions such as file creation and memory
management, is linked to via kernel32.lib...

Symbol resolution and binding
Each function exported by a DLL is identified by a numeric ordinal and optionally a name. Likewise,
functions can be imported from a DLL either by ordinal or by name. The ordinal represents the position of
the functions address pointer in the DLL Export Address table. It is common for internal functions to be
exported by ordinal only. For most Windows API functions, only the names are preserved across different
Windows releases; the ordinals are subject to change. So, one cannot reliably import Windows API
functions by their ordinals.

Importing functions by ordinal provides only slightly better performance than importing them by name:
export tables of DLLs are ordered by name, so a binary search can be used to find a function. The index of
the found name is then used to lookup the ordinal in the Export Ordinal table. In 16-bit Windows, the name
table was not sorted, so the name lookup overhead was much more noticeable.

It is also possible to bind an executable to a specific version of a DLL, that is, to resolve the addresses of
imported functions at compile-time. For bound imports, the linker saves the timestamp and checksum of the
DLL to which the import is bound. At run-time Windows checks to see if the same version of library is
being used, and if so, Windows bypasses processing the imports. Otherwise, if the library is different from
the one which was bound to, Windows processes the imports in a normal way.

Bound executables load somewhat faster if they are run in the same environment that they were compiled
for, and exactly the same time if they are run in a different environment, so there's no drawback for binding
the imports. For example, all the standard Windows applications are bound to the system DLLs of their
respective Windows release. A good opportunity to bind an application's imports to its target environment
is during the application's installation.

Explicit run-time linking
DLL files may be explicitly loaded at run-time, a process referred to simply as run-time dynamic linking by
Microsoft, by using the LoadLibrary (or LoadLibraryEx) API function. The GetProcAddress API function
is used to lookup exported symbols by name, and FreeLibrary to unload the DLL. These functions are
analogous to dlopen, dlsym, and dlclose in the POSIX standard API.

Note that with implicit run-time linking, referred to as load-time dynamic linking by Microsoft, if the
linked DLL file cannot be found, Windows will display an error message and fail to load the application.
The application developer cannot handle the absence of DLL files linked implicitly by the compile-time
linker. On the other hand, with explicit run-time linking, developers have the opportunity to provide a
graceful fall-back facility.

The procedure for explicit run-time linking is the same in any language, since it depends on the Windows
API rather than language constructs.
KNTU University Bakhtiari
1386
Creating Fortran DLLs:
A dynamic-link library (DLL) contains one or more subprogram procedures (functions or subroutines) that
are compiled, linked, and stored separately from the applications using them. Because the functions or
subroutines are separate from the applications using them, they can be shared or replaced easily.

Like a static library, a DLL is an executable file. Unlike a static library where routines are included in the
base executable image during linking, the routines in a DLL are loaded when an application that references
that DLL is loaded (run time). A DLL can also be used as a place to share data across processes.

Advantages of using DLLs:
1. You can change the functions in a DLL without recompiling or relinking the applications that use
them, as long as the functions' arguments and return types do not change. This allows you to
upgrade your applications easily. For example, a display driver DLL can be modified to support a
display that was not available when your application was created.
2. When general functions are placed in DLLs, the applications that share the DLLs can have very
small executables.

3. Multiple applications can access the same DLL. This reduces the overall amount of memory
needed in the system, which results in fewer memory swaps to disk and improves performance.
4. Common blocks or module data placed in a DLL can be shared across multiple processes.
5. Easily features sharing between several languages to achieve more flexibility. For example, you
can use simple to implement GUI features of Visual Basic, while you have powerful calculation
capacity of Fortran.

Building DLLs in Fortran:

NOTE: ALL FOLLOWING PROCEDURES HAS BEEN ADAPTED TO COMPAQ VISUAL
FORTRAN COMPILER! SO IT CANNOT BE USED FOR OTHER COMPILERS! KEEP THIS IN
MIND!

To build a DLL in the visual development environment, specify the Fortran Dynamic-Link Library project
type. On the command line, specify the /Dll option.

You cannot make a QuickWin application into a DLL (see Using QuickWin) and QuickWin applications
cannot be used with Fortran run-time routines in a DLL.

Coding Requirements for Sharing Procedures in DLLs
A dynamic-link library (DLL) contains one or more subprograms that are compiled, linked, and stored
separately from the applications using them.

Coding requirements include using cDEC$ ATTRIBUTES DLLIMPORT and DLLEXPORT compiler
directives. Variables and routines declared in the main program and in the DLL are not visible to each
another unless you use DLLIMPORT and DLLEXPORT.

This section discusses aspects of sharing subprogram procedures (functions and subroutines) in a Fortran
DLL.

To export each DLL subprogram:

Within your Fortran DLL, export each subprogram that will be used outside the DLL. Add a cDEC$
ATTRIBUTES DLLEXPORT directive to declare that a function, subroutine, or data is being exported
outside the DLL. For example:
KNTU University Bakhtiari
1386


SUBROUTINE ARRAYTEST(arr)
!DEC$ ATTRIBUTES DLLEXPORT :: ARRAYTEST
REAL(4) arr(3, 7)
INTEGER i, j
DO i = 1, 3
DO j = 1, 7
arr (i, j) = 11.0 * i + j
END DO
END DO
END SUBROUTINE

Important notifications:
1- DLLs can only do process on data and be a subroutine or a function, which could be called from main
program. Because they are not independent executable programs, you cannot provide the user direct access
to DLL input, or provide user the results directly from DLL. This means that if you use following
statements inside DLL you will face run-time error:
WRITE(*,*)
READ(*,*)
Print* & etc
2- While DLLs cannot interact directly with user, they could be easily used to access system resources and
storage area like memory or HDD (Hard Disk Drive). For example, you can read from a file or write into it
inside your DLL:

Open (UNIT=10,FILE=C:\Input.dat)
Open (UNIT=12,FILE=C:\Output.dat)

.
.
READ(10,*) A,B,C
WRITE(12,*) D,E,F
.
.
3- The comment out phrase in the first line of the DLL is a very important part, which define the symbols
and the function or subroutine. In fact, it is not a comment, so except the name, do not change anything.

Calling Visual Fortran from Visual Basic:

When calling a Visual Fortran DLL from Visual Basic, important argument passing and data type
considerations are:

Visual Basic uses the STDCALL standard of argument passing with one exception: it does not append the
"@n" count to the name on x86 systems.


Within Visual Basic, you declare the name of the routine that will be called and the arguments to be passed
to it. Scalar numeric arguments can be directly passed from Basic and directly used by Fortran, but strings,
arrays, and types require some extra handling.

KNTU University Bakhtiari
1386
Declaring the Fortran Routine in Visual Basic

When you declare a Fortran routine in Basic the routine name is exported in exactly the same case as you
declared it. Optionally, you can specify a directory path to the Fortran DLL in the declaration.

The following Visual Basic example declares a Fortran subroutine named FortranCall that takes two single-
precision arguments:


Declare Sub FortranCall Lib "d:\MyProjects\FCall.dll" (byRef A1 as Single, byRef A2 as Single)

The following example declares a Fortran function named FortranFunc that takes two integer (32-bit)
arguments and returns a single precision value:

Declare Function FortranFunc Lib "d:\MyProject\FFun.dll" (byRef A1 as Long, ByRef A2 as Long) As
Single

Note: The name of your function inside DLL is case sensitive, so it is better to use capital letters on both
sides (VB and Fortran) to avoid any probable problem.

Data Type Considerations

When you pass data between Visual Basic and Visual Fortran, you need to keep in mind the calling
standard used by the two languages, the size of the data, and the on-disk format of the data. Remember that
in all case all data types should be passed by reference. If you violate the rules of passing arguments
between languages, you will be in the hell of a trouble!

The followings summaries the calling considerations for the data types:
Integer
By default, both Visual Basic and Visual Fortran pass integers by reference. The default integer size in
Basic is 2 bytes, equivalent to INTEGER(2) in Fortran. No extra action is required by either language to
access integer arguments. Remember that INTEGER*2 data type in Fortran is equal to INTEGER data
type in visual basic and INTEGER*4 data type in Fortran is equal to LONG data type in Visual Basic

Floating point (Real)
By default, both Visual Basic and Visual Fortran pass single- and double-precision floating-point numbers
by reference. The size of a single-precision floating-point number is 4 bytes in both languages. The size of
a double-precision floating-point number is 8 bytes in both languages. No extra action is required by either
language to access floating-point arguments. Remember that REAL*4 data type in Fortran is equal to
SINGLE data type in Visual Basic and REAL*8 data type in Fortran is equal to DOUBLE data type in
Visual Basic.

Logical
By default, both Basic and Fortran pass logical data by reference. The default logical size in Basic is two
bytes, equivalent to LOGICAL(2) in Fortran. No extra action is required by either language to access
logical arguments. Remember that LOGICAL*1 data type in Fortran is equal to BOLEAN data type of
visual basic.

Arrays
By default, Basic arrays are 0-based. Fortran arrays are 1-based by default. When you declare a Basic array
to be of size "n", n+1 elements are allocated, including the 0th element. This can be overridden, as show in
the Array Passing Examples.
KNTU University Bakhtiari
1386
To pass arrays of numbers from Basic to Fortran, whether they are integer or floating-point numbers, pass
the first element. In the Fortran code, declare the argument to be an array. Always pass the number of
elements in each dimension and reconstruct the array inside the visual Fortran
Visual Basic code:

Visual Basic declaration:
Declare Sub FortArray1 Lib "forttest" (ByRef A1 as Long, ByRef xNum as long, ByRef yNum as long)
Dim A1(1:3,1:5) as Long
Dim xNum as long, yNum as long
xNum=3
yNum=5
Call FortArray1(A1(1,1), 3,5)

Visual Fortran code:


Subroutine FortArray1 (Array1, xN,yN)
!DEC$ ATTRIBUTES DLLEXPORT, ALIAS : "FortArray1" :: FortArray1
INTEGER*4 xN,yN
INTEGER*4 array1(xN,yN)
Derived data types:
Basic-declared types can be passed from Basic to Fortran. The Basic-declared type will also have to be
declared in Fortran; care should be taken to keep the two structures the same. In Fortran, the TYPE should
be declared to be packed, usually PACK:2. You should be aware of the default sizes of the TYPE elements
in the two languages, and adjust the defaults accordingly. You can pass arrays of declared data types to
Fortran same as arrays of numbers.

Strings:
Never, ever waste your time to pass strings from Visual Basic to Fortran or Visual Basic to MFC & C++!
This is a wise advice, take it!
Sure, there are some ways to do so, and sometimes you have to do it, for example, when you need to pass a
file name, but circle around direct passing the string. There are several simple ways to avoid direct passing
strings when it seems unavoidable, but I will not mention it here, find it yourself!



Packing and running your program from a different machine:
If you want to pack your program and run it from another machine which has not Compaq Visual Fortran
installed on it, you will face the following error when you calling your DLL:
Error: The entry point for yourdllname.dll was not found.
You will get confused, because everything is ok on your machine and you cannot find the reason of the
error. I will give you the priceless solution here ( Dont think that Im too much snobbish at this session,
because this tip could save days or maybe weeks of your time!) :
Simply find followings DLLs inside Compaq Visual Fortran folder and copy them to windows/system32
folder in the target machine:
DFORMD.DLL
DFORRT.DLL

Extremely important notification:
If you have any doubt about the price of this tip ;), search the internet and see how people get mad when
they cannot understand why their programs do not work on the other machines while they have found no
solution!


KNTU University Bakhtiari
1386
Fortran Course: Session 10

Compaq Fortran Math Libraries
Compaq Fortran provides several functions and subroutines for supporting conventional math and statistic
analyze. These libraries could be categorized into tow main sections. The first section named IMSL (Math
Library) and the second called CXML(Compaq Extended Math Library). The functions and subroutines,
which have been provided by these libraries take benefits from highly optimized and fast algorithms to
solve wide variety of mathematical and numerical, analyze problems.


IMSL:
IMSL consists of several useful routines, which, many of them could also be found on the other Fortran
compilers. The IMSL MATH/LIBRARY is a collection of FORTRAN routines and functions useful in
research and mathematical analysis. Each routine is designed and documented to be used in research
activities as well as by technical specialists.
To use any of these routines, you must write a program in FORTRAN (or
possibly some other language) to call the MATH/LIBRARY routine. Each
routine conforms to established conventions in programming and documentation.
Compaq give first priority in development to efficient algorithms, clear documentation, and accurate
results. The uniform design of the routines makes it easy to use more than one routine in a given
application. In addition, you will find that the design consistency enables you to apply your experience with
one MATH/LIBRARY routine to all other IMSL routines that you use.
IMSL has been divided into several categories. Following classification can be found inn Compaq Fortran
IMSL help:
1- IMSL Math Library Volume 1&2, which includes following routines:
a. Linear solvers
b. Eignsystem analysis
c. Interpolation and approximation
d. Integration and different ion
e. Differential equations
f. Transforms
g. Nonlinear equations
h. Optimization
i. Basic matrix/vector operation
j. Utilities

2- IMSL special functions, which includes following routines:
a. Elementary functions
b. Trigonometric and hyperbolic functions
c. Exponential integrals and related functions
d. Gamma functions and related functions
e. Error function and related functions
f. Bessel functions
g. Kelvin functions
h. Airy functions
i. Elliptic integrals
j. Elliptic and related functions
k. Probability distribution functions and inverses
l. Mathieu functions
m. Miscellaneous functions
3- IMSL stat/library volume 1 ( for further details please refer to manual)
4- IMSL stat/library volume 2 ( for further details please refer to manual)

KNTU University Bakhtiari
1386
As can be seen, IMSL provides extreme variety of required routines for mathematical operation and
analysis.


CXML
The Compaq Extended Math Library (CXML) is a collection of high-performance,
computationally intensive mathematical subprograms designed for use in many
different types of scientific and engineering applications. CXML subprograms are
callable from any programming language. CXMLs subprograms cover the areas of Basic Linear
Algebra, Linear System and Eigenproblem Solvers, Sparse Linear System Solvers, Sorting, Random
Number Generation, and Signal Processing.
Basic Linear Algebra Subprograms - The Basic Linear Algebra Subprograms (BLAS) library
includes the industry-standard Basic Linear Algebra Subprograms for Level 1 (vector-vector
(BLAS1)), Level 2 (matrixvector (BLAS2)), and Level 3 (matrix-matrix (BLAS3)). Also
included are subprograms for BLAS Level 1 Extensions, Sparse BLAS Level 1, and Array
Math Functions (VLIB).
Signal Processing Subprograms - The Signal Processing library provides a basic set of signal
processing functions. Included are one-, two-, and three-dimensional Fast Fourier Transforms
(FFT), group FFTs, Cosine/Sine Transforms (FCT/FST), Convolution, Correlation, and
Digital Filters.
Sparse Linear System Subprograms - The Sparse Linear System library provides both direct
and iterative sparse linear system solvers. The direct solver package supports both symmetric
and nonsymmetrical sparse matrices stored using the skyline storage scheme. The iterative
solver package contains a basic set of storage schemes, preconditioners, and iterative solvers.
The design of this package is modular and matrix-free, allowing future expansion and easy
modification by users.
LAPACK subprograms - The Linear System and Eigenproblem Solver library provides the
complete LAPACK package developed by a consortium of university and government
laboratories. LAPACK is an industrystandard subprogram package offering an extensive set
of linear system and Eigen problem solvers. LAPACK uses blocked algorithms that are better
suited to most modern architectures, particularly ones with memory hierarchies. LAPACK
will supersede LINPACK and EISPACK for most users. Where appropriate, each
subprogram has a version to support each combination of real or complex arithmetic and
single or double precision. The supported floating-point format is IEEE, and additionally
VAX float on the OpenVMS platform.




Installation:
To install IMSL and CXML libraries, during installation choose Custom Install and make sure that IMSL
and CXML routines has been selected.

KNTU University Bakhtiari
1386
Documentation:
You can find documentation for IMSL inside:

Installation Directory\ DF98\IMSL\HELP \IMSL.PDF

In addition, you can find documentation for CXML inside:

Installation Directory \DF98\CXML\DOC\CXMLREF.PDF

IMSL Considerations:

For making routines accessible to compiler, implement following statement at the first line of the
procedure in which you want to use one of IMSL routines:

USE IMSL
There are also some other modules which could be used by your program from IMSL. Useful information
on this topic could be found in the readme.txt file inside IMSL directory. Some of them are:
Numerical_Libraries
IMSLF90
IMSLF77
IMSLF90
DFIMSL
MSIMSL

I suggest for solving a problem by using IMSL routines take following steps:
1- Analyze the problem carefully and design your approach
2- Find and select you desired routines from IMSL help and documentation.
3- Read carefully the help for the routines you want to use.
4- Make a new FORTRAN CONSULE APPLICATION.
5- Program your solution with at most modularity

Moreover, there are several good examples inside documentations, which you can use for learning how the
routines work.
Note: almost for all of the routines inside IMSL you have two versions: First for single precision data type,
and second for double precision data type. Be careful for choosing correct data type for arguments and
results.

CXML Consideration:

1-CXMLs Accuracy
To obtain the highest performance from processors, the operations in CXML
subprograms have been reordered to take advantage of processor-level parallelism.
Because of this reordering, some subprograms may have arithmetic
evaluation order different from the conventional evaluation order. This difference
in the order of floating point operations introduces round-off errors that imply
the subprograms can return results that are not bit-for-bit identical to the
results obtained when the computation is in the conventional order. However, for
well-conditioned problems, these round-off errors should be insignificant.
Significant round-off errors in application code that is otherwise correct indicates
that the problem is most likely not correctly conditioned. The errors could be
the result of inappropriate scaling during the mathematical formulation of
the problem or an unstable solution algorithm. Re-examine the mathematical
analysis of the problem and the stability characteristics of the solution algorithm.

2- DataTypes:
KNTU University Bakhtiari
1386
Extreme caution should be taken into account with data types. I experienced some errors and memory
leakages with CXML library routines. So be careful and do not afraid to make CXML into blame for the
errors!

3- Using the Libraries from Developer Studio
This section discusses discuss how to compile and link your program using the Developer Studio.
During the installation, the paths to the location of the object libraries and include files are automatically
defined. However, before attempting to build an application that accesses the libraries, the names of the
libraries must be specified for the linker. You can do this by performing the following steps:
a) Start the Developer Studio.
b) If you have not already defined a Project Workspace for your application, you must do so before
proceeding. If you have defined a Project Workspace, open it by selecting "Open Workspace..."
from the File pull-down menu.
c) Bring up the Project Settings dialog box by selecting "Settings..." from the Project pull-down
menu.
d) Click on the "Link" tab.
e) From the Category pull-down menu, select "Input".
f) Add the names of the CXML libraries. under "Object/Library Modules"(separated by spaces).
g) Click on "OK" to exit the dialog and save the settings.
The Microsoft Developer Studio is now set up to use the CXML libraries. For
further information about compiling and linking with Developer Studio, refer
to the "Building Programs and Libraries" section of the Compaq Visual Fortran
online documentation.
There is another way to includes CXML routines into your projects:
a) Inside developer studio, select Tools menu.
b) Inside Tools menu, select options.
c) Find the Directories Tab from options dialog box.
d) Under the combo box Show directories for select Include files.
e) Add new directory and browse to :
Installation Directory\ DF98\CXML\INCLUDE
f) Like what you have done in step d, Under the combo box Show directories for select Library
files.
g) Add new directory and browse to :
Installation Directory\ DF98\CXML\LIB
Then inside the procedure, which you want to use, some of CXML routines add following statement to the
first line:
INCLUDE "DXMLDEF.FOR"
Now the routines of CXML are visible for your program.
Remember that you can easily use CXML routines inside DLLs and even C programs and some other
languages.


KNTU University Bakhtiari
1386
Fortran Course: Session 11
Spreadsheet applications:
A spreadsheet is a rectangular table (or grid) of information, consisting of text and numbers, for
example financial information. A spreadsheet may furthermore contain formulas that give rules
for computing certain values in the table from other values, such as the total value of a column,
which is computed by adding the values above it.

The word came from "spread" in its sense of a newspaper or magazine item (text and/or graphics)
that covers two facing pages, extending across the center fold and treating the two pages as one
large one. The compound word "spread-sheet" came to mean the format used to present
bookkeeping ledgerswith columns for categories of expenditures across the top, invoices listed
down the left margin, and the amount of each payment in the cell where its row and column
intersectwhich were traditionally a "spread" across facing pages of a bound ledger (book for
keeping accounting records) or on oversized sheets of paper ruled into rows and columns in that
format and approximately twice as wide as ordinary paper.


Why we need to use spreadsheet applications:
There are several engineering problems which need to use a set of formulas that have a set of
parameters. When you need to change the parameters regularly to achieve the desired answer,
especially for small problems, write a program is a lengthy and expensive solution by terms of
time. Therefore, it is better to have a more flexible solution. Spreadsheets applications provide
this solution. You can use repeatable formulas, names and several more features to conduct your
calculations without spending your time on writing a program.


Excel :
Microsoft Excel (full name Microsoft Office Excel) is a spreadsheet application written and
distributed by Microsoft for Microsoft Windows and Mac OS X. It features calculation, graphing
tools, pivot tables, and a macro programming language called VBA (Visual Basic for
Applications). It is overwhelmingly the dominant spreadsheet application available for these
platforms and has been so since version 5 in 1993, and is bundled as part of Microsoft Office.
Excel is one of the most popular microcomputer applications to date.









Limitation:

There are some limitations for excel. You should consider them when you are using excel. You
can find some of these limitations on the following table:

Open workbooks Limited by available memory and system resources
KNTU University Bakhtiari
1386
Worksheet size 65,536 rows by 256 columns
Column width 255 characters
Row height +09 points
Page breaks 1000 horizontal and vertical
Length of cell contents (text) 32,767 characters. Only 1,02+ display in a cell; all 32,767
display in the formula bar.
Sheets in a workbook Limited by available memory (default is 3 sheets)
Colors in a workbook 56
Cell styles in a workbook +,000
Named views (view: A set of display and print settings that
you can name and apply to a workbook. You can create more
than one view of the same workbook without saving separate
copies of the workbook.) in a workbook
Limited by available memory
Custom number formats Between 200 and 250, depending on the language version of
Excel you have installed.
Names in a workbook Limited by available memory
Windows in a workbook Limited by system resources
Panes in a window +
Linked sheets Limited by available memory
Scenarios (scenario: A named set of input values that you
can substitute in a worksheet model.)
Limited by available memory; a summary report shows only
the first 251 scenarios
Changing cells in a scenario 32
Adjustable cells in Solver 200
Custom functions Limited by available memory
Zoom range 10 percent to +00 percent
Reports Limited by available memory
Sort references 3 in a single sort; unlimited when using sequential sorts
Undo levels 16
Fields in a data form 32
Custom toolbars in a workbook Limited by available memory
Custom toolbar buttons Limited by available memory



Useful Features:

Names:
You can define a name for a specific cell. Use following procedure to do so:
Menu => Insert => Name=>Define
After that, a dialog box will be opened and you can insert your name there, changing a cell name
or deleting a name from list. Remember that a cell name should not be the same with excel
intrinsic names such as A1, DE21 etc

Intrinsic functions:
KNTU University Bakhtiari
1386
Several intrinsic functions inside excel could be used easily. These includes math functions (such
as sin, cos, tan, atan etc), array functions (such as sum, average etc) and several statistical
functions.

User defined formulas:

You can easily define user-defined formulas, inside formula bar. Each cell with General
formatting could be started by = and then you can select or type parameters of a formula and
your desired operations. The language conventions of writing a formula are following Visual
Basic For Application rules. Basic operators are listed in table below:

^
Power
/
Division
*
Multiply
+
Sum
-
Subtract

example:
If you type in cell B2 the following text:
=A1*(B1^2)+A2*B1+C1
Every time you change the value of cell B1, the result of this quadric function will be
automatically changes in cell B2 and you can see it.

User Defined Functions:

You can define your user-defined functions inside excel. The user-defined functions will be saved
in a module (similar to visual basic) and could be used easily in the workbook like intrinsic
functions. This ability helps you to define functions, which need to have loop and conditional
operators.




Autofill:
One of the most amazing features of Excel is its intelligent autofill function. Depends on what
you want to do by dragging the small black point (rectangle) under the selected cell (or cells) you
can easily fill other cells with similar formula or numerical relation.

Links:
You can easily make links cells between different worksheets in a workbook our even with
different workbook on your computer or network.

Charts:
Excel is user-friendly software for drawing simple graphs. Its 2d line and xy graphs are fine and
there is a good curve fit with polynomials up to order 5.


KNTU University Bakhtiari
1386
Tecplot 360:

What is Tecplot:
Tecplot is a Computational Fluid Dynamics (CFD) and numerical simulation software package
used in post-processing simulation results.

Common tasks associated with post-processing analysis of flow solver (e.g. Fluent, STAR-CD,
OpenFOAM) can include such tasks as:

1- Calculating grid quantities (e.g. aspect ratios, skewness, orthogonality and stretch factors)
2- Normalizing data, Deriving flow field functions like pressure coefficient or vorticity magnitude
3- Verifying solution convergence
4- Estimating the order of accuracy of solutions
5- Interactively exploring data through cut planes (a slice through a region), iso-surfaces (3-D
maps of concentrations), particle paths (dropping an object in the "fluid" and watching where it
goes).
Because of the widespread functionality of Tecplot, here we concentrate on Data Format in
Tecplot. Moreover we currently explaining Data Format for ASCII files (not binary).

ASCII File Format for Tecplot360:
File Header

In the file header of your data file, you may specify an optional title that is displayed in the
headers of Tecplot frames. The title line begins with TITLE=, followed by the title text enclosed
in double-quotes. You may also assign a name to each of the variables by including a line that
begins with VARIABLES=, followed by each variables name enclosed in double quotes. The
quoted variable names should be separated by spaces or commas. Tecplot calculates the number
of variables (N) from the list of variable names. If you do not specify the variable names (and
your first zone has POINT data packing), Tecplot sets the number of variables equal to the
number of numeric values in the first line of zone data for the first zone, and names the variables
V1, V2, V3, and so forth.

Simple ordered data (2D-3D):
Initially, Tecplot uses the first two variables in data files as the X- and Y-coordinates, and the
third variable for the Z-coordinate of 3D plots. You may, however, order the variables in the data
file any way you want, since you can interactively reassign the variables to the X-, Y-, and or Z-
axes using Tecplot dialogs. Example:

TITLE= Temperature
VARIABLES= Time Mach Density

0.000000000000000E+000 0.654474452249884 1.89335268259981
8.505862099875004E-006 0.654572109895683 1.89195052126602
1.701172419975001E-005 0.654669398884875 1.89054888056494
2.551758629962501E-005 0.654766318704351 1.88914776049756
When you want to load above data set into Tecplot360, choose 2D Cartesian. If you want to
change the axis, for example if you need to draw density values (by default, Mach number will be
displayed) for data above, simply:
Menu=> Plot => Assign XY => choose your desired variable for each axis
KNTU University Bakhtiari
1386
In addition, you need to know that for more complicated graphs such as finite element data, we
will need more complex header, which will be mentioned later.


Finite Element Data (2D) - Triangular Elements:

An example of triangle element type finite-element data with POINT datapacking is listed below.
There are two variables (X, Y) and five data points. In this example, each row of the data section
corresponds to a node and each column to a variable. Each row of the connectivity list
corresponds to a triangular element and each column specifies a node number. This data set is
plotted in figure below. Each data point is labeled with its node number.
Data set for above mesh mentioned below:

VARIABLES = "X", "Y", "Temperature", "Pressure"
ZONE N=5, E=3, DATAPACKING=POINT, ZONETYPE=FETRIANGLE
1.0 1.0 273.0 123000
2.0 3.0 365.0 150000
2.5 1.0 441.0 160000
3.5 5.0 365.0 140000
4.0 1.0 223.0 120000

1 2 3
3 2 4
3 5 4

You can see different contours (temperature or pressure) by:

Menu=>Plot =>contours

Then in the opened dialog box, you can choose desired variable.

Finite Element Data (2D) - Quadrilateral Elements:
KNTU University Bakhtiari
1386
Creating a finite-element data set is generally more complicated than creating a similar-sized
ordered data set. In addition to specifying all the data points, you must also specify the
connectivity list. Consider the data shown in this table.

Node X Y P T
A 0.0 1.0 100.0 1.6
B 1.0 1.0 150.0 1.5
C 3.0 1.0 300.0 2.0
D 0.0 0.0 50.0 1.0
E 1.0 0.0 100.0 1.4
F 3.0 0.0 200.0 2.2
G 4.0 0.0 400.0 3.0
H 2.0 2.0 280.0 1.9


You can create a POINT Tecplot data file for this data set as follows (a 2D mesh plot of this data
set is shown in figure below):



Data set for above mesh mentioned below:


TITLE = "Example: 2D Finite-Element Data"
VARIABLES = "X", "Y", "P", "T"
ZONE N=8, E=4, DATAPACKING=POINT, ZONETYPE=FEQUADRILATERAL
0.0 1.0 100.0 1.6
1.0 1.0 150.0 1.5
3.0 1.0 300.0 2.0
0.0 0.0 50.0 1.0
KNTU University Bakhtiari
1386
1.0 0.0 100.0 1.4
3.0 0.0 200.0 2.2
4.0 0.0 400.0 3.0
2.0 2.0 280.0 1.9
1 2 5 4
2 3 6 5
6 7 3 3
3 2 8 8



The ZONE record describes completely the form and format of the data set: there are eight nodes,
indicated by the parameter N=8; four elements, indicated by the parameter E=4 and the elements
are all quadrilaterals, as indicated by the parameter ZONETYPE=FEQUADRILATERAL.

Vous aimerez peut-être aussi