# SUMMARY OF FORTRAN, Statements and Examples

Document Sample

```					FORTRAN SUMMARY

0
Identifiers
Identifiers such as program names and variable names must begin with a letter
which may be followed by up to 30 letters, digits, or underscores.

Program structure
Program heading (PROGRAM statement)
Specification part (type declaration)
Execution part     (executable statements)
Subprogram part
END PROGRAM statement

Any character following an exclamation mark (!)---except within a string
constant---and running to the of the line from a comment.

Program statement
PROGRAM program-name

Example:

PROGRAM Projectile

Purpose:
The PROGRAM statement names the program.

Declaration of Variables
REAL :: list
INTEGER :: list
CHARACTER (LEN = n) :: list or CHARACTER (N) ::LIST

Examples:

REAL :; InitialHeight, Height, InitialVelocity, Velocity
INTEGER :: MaxCastings, NumCastings
CHARACTER(10) :: FirstName, LastName, Initial*1

1
Purpose:
Type statements declare the type of values that variables will have.

IMPLICT NONE Statement
IMPLICT NONE

Purpose:
Cancels the naming convention.

Initialization Declarations
type-specifier :: var1 = const1, . . . , varn = constn

Where each vari is a variable and each consti is a constant expression.

Example:

INTEGER:: Count = 1
REAL :: Sum_x = 0.0, Sum_y = 0.0
CHARACTER(20) :: Name = "John Q. Doe"

Purpose:
Initializes each variable vari with the corresponding constant value in consti at
compile time.

PARAMETER Attribute
type-specifier, PARAMETER :: namei = consti , . . . , namen = constn
where each namei is an identifier and each consti is a constant expression.

Example:
INTEGER, PARAMETER :: Limit = 100
REAL, PARAMETER :: Pi = 3.1411593
Purpose:
Associates each namei with the constant consti.

2
Operations
Operator      Operation
-           subtraction
*          multiplication
/             division
**          Exponentiation
Functions
Function                               Description
ABS(X)                                 Absolute value of X
COS(X)                                 Cosine of X radians
EXP(X)                                 Exponential function
FLOOS(X)                               Greatest integer<= X
FRACTION(X)                            Fractional part (mantissa) of X
INT(X)                                 Integer part of X
LOG(X)                                 Natural logarithm of X
MAX(X1 . . . , Xn)                     Maximum of X1, . . . ,Xn
Min(X1, . . . ,Xn)                     Minimum of X1, . . . , Xn
MOD(X,Y)                               X(mod Y ); X - INT (X/Y) * Y
NINT(X)                                X rounded to nearest integer
REAL(X)                                Conversion of X to real type
SIN(X)                                 Sine of X radians
SQRT(X)                                Square root of X
TAN(X)                                 Tangent of X radius

Assignment Statement
variable = expression

Examples:

Count = 0
Height = 4.5 * Acceleration * Time ** 2 & + InintialVelocity + Time +
InitialHeight
Velocity= Acceleration * Time + InitialVelocity
Name = "John Q. Doe"

Purpose:
assign the value of the expression to the specified variable.

3
Input statement
For iteractive input:

Or

For input from file:

READ (unit-number, *) inout-list-of-variables

Example:

READ *, InitialHeight, InitialVelocity
READ (12,*) InitialHeight, InitialVelocity, time

Purpose:
The READ statement reads values for the variables in the input list.

Output statement
For interactive output:

PRINT *, output-list-of-expressions
WRITE(*,*) output-list-of-expressions

For output to a file:

WRITE (unit-number,*) output-list-of-expressions

Examples:

PRINT *, “Enter the initial height and velocity:”

PRINT * , “At time”, Time , “seconds”
PRINT *, “the vertical velocity is”, velocity , “m/sec”
PRINT *, “and the height is:, Height, “meters”

WRITE(13,*) “At time”, Time , “seconds”
WRITE(13,*) “ the vertical velocity is”, Velocity , “m/sec”

4
WRITE(13,*) “ and the height is “, Height, “meters”

Purpose:
The PRINT and WRITE statements display the value of the expressions in the
output list.

OPEN statement
OPEN (UNIT= unit-number, FILE= file-name, STATUS = status)
Examples:

OPEN (UNIT = 12, FILE = “fig2-6.dat”, STATUS =“OLD”)
OPEN (UNIT = 13, FILE = “fig2-6.out”, STATUS =“NEW”)

Purpose:
The OPEN statement assigns a unit number to a disk file, which may already
exist (status is OLD) or which will be created (status is NEW), and makes it
accessible for input/output

STOP Statement
STOP

Or

STOP constant

Where constant is an integer constant or a character constant.

Purpose:
Stops execution of the program. In the second form, the specified constant will
be displayed.

END PROGRAM Statement
END PROGRAM program-name

Purpose:
The END PROGRAM statement marks the end of a program and stops
execution.

5
Program Format
 A line may have a maximum of 123 characters.
 A line may contain more than one statement, provided the statements are
separated by semicolons.
 An ampersand (&) must be placed at the end of each line that is continued
to the next line. At most 39 continuation lines are permitted.
 If a character string must be continued from one line to the next, an
ampersand must be placed at the end of the line containing the first part of
the string and another ampersand must be placed before the first character
of the continuation of the string.
 A statement label must be an integer with at most five digits and must
precede the statement and be separated from it by at least one blank.

PROGRAMMING POINTERS
In the section we consider some aspect of program design and suggest
guidelines for good programming style. We also point out some errors that may
occur when writing Fortran programs.

Program Style and Design

1- In the example in this text, we adopt certain style guidelines for Fortran
programs, and you should write your program in a similar style. The
following standards are used (others are described in the programming
pointers of subsequent chapters):
 When a statement is continued from one line to another, indent the
continuation line(s).
 Document each program with comment lines at the beginning of the
program to explain the purpose of the program and hat the variable
represent. You should also include in this documentation your name,
date, course number, assignment number, and so on.
 Break up long expressions into simpler sub expressions.
 Insert a blank comment line between the opening documentation and
specification statements at the beginning of the program and between
these statements and the rest of the program.
 To improve readability, insert a blank space between items in a Fortran
statement such as before and after assignment operators and arithmetic
operators.
2- Programs cannot be considered correct until hey have been validated
using test data, Test all programs with data for which the results are
known or can be checked by hand calculation.
3- Programs should be readable and understandable.

6
 Use meaningful identifiers that suggest what each identifier represents.
For example,

Distance = Rate * Time

Is more meaningful than

D=R*T
Or

Z7 = Alpha * X

Also, avoid “cute” identifier, as in

HowFar = GoGo * Squeal

 Do not use “ magic numbers” that suddenly appear without explanation,
as in the statement

Output = 0.1758 * Amount + 1.34E-5

If these numbers must be changed, someone must search through the program to
determine what they represent and which ones should be changed and to locate
all their occurrences. It is thus better to associate them with named constants, as
in

REAL, PARAMETER :: Rate = 0.1758, Error = 1.34E-5

Or assign them to variables, as in

REAL :: Rate = 0.1758, Error = 1.34E-5

 Use comments to describe the propose of a program, the meaning of
variables, and the purpose of key program segments. However, do not
clutter the program with needless comments; for example, the comment in

! Add 1 to Count
Count = Count + 1

is not helpful in explanation the statement that follows it and so should be
omitted.

 Label all output produced by a program. For example,

7

PRINT *, “Rate= “, Rate, “ Time – “, Time

PRINT *, Rate, Time
4- Programs should be general and flexible, they should solve a class of
problems rather than one specific problem. It should be relatively easy to
modify a program to solve a related problem without changing much of
the program. Avoiding the use of magic numbers, as described in 3, is
important in this regard.

Potential Problems

1- Do not confuse I or 1 (lo west “ell”) and 1 or 0 (zero) and o (the letter
“oh”). For example, the statement

PROGRAM Dilute

Produces an error, because the numeral 0 is used in place of the o. Many
programmers distinguish between these in handwritten program by writing
the numeral 0 as Φ.
2- String constant must be enclosed between double quotes or between
apostrophes. If the beginning quote and the ending quote are different or
if either is missing, an error will result.
3- If a string constant must be broken at the end of a line, an ampersand (&)
must be placed after the last character on that line and another ampersand
before the first character on the next line.
4- All multiplications must be indicated by *. For example, 2 * N is valid,
but N is not
5- Division of integers produces an integer. For example, 1 / 2 has the value
0. Similarly, if N is an integer variable greater than 1, 1/N will have the
value 0.
6- Parentheses in expressions must be paired. For each left parenthesis there
must be a matching right parenthesis that appears later in the expression.
7- The values of named constants may not be changed. Any attempt to do so
produces a compile-time error.
8- All variables are initially undefined. Although some compilers may
initialize variable to specific value (e.g., 0 for numeric variables), it
should be assumed that all variables are initially undefined. For example,
the statement Y= X + 1 Usually produces a “garbage” value for Y if X has
not previously been assigned a value.

8
9- Initializations in declarations are done only once, during compilation,
before execution of the program begins. In particular, this means that the
variables are not reinitialized while the program is being executed.
Potential problem 6 in the Programming Pointers Section of Chapter 4
explains this problem in detail.
10-        A value assigned to a variable must be of a type that is appropriate
to the type of the variable. Thus, entering the value 2.7 for an integer
variable Number in the statement

may generate an error message. However, an integer value read for a real
variable is automatically converted to real type.
11-       Mixed=mode assignment must be used with care. For example if
A.B. and C are real variables but Number is an integer variable, the
statement

Number = - B + SQRT(B * * 2 - 4.0 * A * C)

Calculates the real value of the right side correctly but when assigns only the
integer part to Number. This happens, for example when the types of these
variables are determined by Fortran’s naming convocation.
12-        In assignment statements and in list-directed input, if a character
value being assigned or read has a length greater than that specified for
the character variable, the rightmost characters are truncated. If the value
has a length less than that specified for the variable, blanks are added at
the right. Thus, if string is declared by

CHARACTER(10) :: String

the statement

String =”ABCDEFGHIJKLMNO’’

Will assign the string “ABCDEFGHIJ” to string, and

string=”ABC”

Will assign the string “ABC ъ ъ ъ ъ ъ ъ ъ “ to String. An acronym
sometimes used to remember this is
 APT: for assignment (and list-directed input),both blank-padding and
truncation occur on the right.

9
13-       The types of all variables should be declared in type statements and
the IMPLICIT NONE statement should be used to ensure this . If
IMPLICIT NONE is not used any variables whose type is not explicit
specified will have its type determined by the FORTRAN naming
convention. Thus if the variable Number has not been declared to be of
real ,the function reference SQRT (number) cause an error, since SQRT
requires a real argument and number is of integer type according to the
naming convention . If A,B,C and number have not been declared
execution of the statement

Number = -B + SQRT(B * * 2 – 4.0 * A * C)

Produces the result described in potential problem 12,According to
FORTRAN’s naming conventions. A, B and C are real variables, so the real
value of the expression on the right side is calculated correctly, but only its
integer part is assigned to Number because the naming convention specifies
that it is an integer variable.
14-          comma must precede the input/output list in input/output
statements of the form

PRINT *, output-list

 New characters including lowercase letters have been added to the Fortran
character set.
 More than one statement may be placed on a line. A semicolon is used to
separate such statement.
 In-line comments that begin with an exclamation point(!) and extend to
the end of the line are allowed.
 Continuation of a statement can be indicated by using an ampersand (&)
as the last non-blank character in the line being continued or the last non-
blank character before the exclamation mark that marks the beginning of a
comment.
 A program may have a sub program section that immediately precedes the
END statement.
 The End statement may have the form END PROGRAM name, where
name is the name used in the program heading.

10
State the problem

Select method for solution

Draw a flow chart for the solution

Write a computer program

Write the program and correct the errors

Draw a flow chart for the solution

Get result

11
Flow chart symbols

To start and end the program

Input data and output result

For calculations

For decision

For subroutines

For directions

For connections

A hexagon indicates the beginning of a
repetitions structure.

12
Draw a flowchart to solve a second order equation
Ax2+ Bx + C = 0
For all case use the formula
 B  B 2  4 AC
x
2A

START

READ A B C

D=B*B
F=4*A*C
G = DF

 BG                                         B  J (G)
X1 =                                         X1 =
2A                  ( D –F )                   2A
 B G                                        B  J (G)
X2 =                                         X2 =
2A                                             2A

WRITE X1 , X2

STOP

13

```
DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 6 posted: 5/26/2012 language: English pages: 14
waheed anjum http://