Вы находитесь на странице: 1из 35

BIL 106 E

Introduction to Sci&Eng Computing


(Fortran)
Lecture 2
by
Dr. Murat Cinar
DATA TYPES + ALGORITHMS =
PROGRAMS
A Fortran program contains a specification part in which the
names and types of constants and variables used to store input
and output values as well as intermediate results are declared.
This is followed by an execution part, which contains the
statements that carry out the steps of the algorithm.

The general form of a program in Fortran is


FORTRAN Program

heading
specification part
execution part
subprogram part
END PROGRAM statement
DATA TYPES + ALGORITHMS =
PROGRAMS
Fortran provides five basic data types:
integer
real
complex
character
logical
Integer
An integer is a whole number (positive, negative, or zero) and may be
represented in Fortran by a string of digits that does not contain
commas or a decimal point; negative integer constants must be
preceded by a minus sign, but a plus sign is optional for nonnegative
integers.
0
137 are valid integer constants
-2516
+17745

9,999 (Commas are not allowed in numeric constants.)


16.0 (Integer constants may not contain decimal points.)
--5 (Only one algebraic sign is allowed.)
7- (The algebraic sign must precede the string of digits.)
Real
Another numeric data type is the real type. Constants of this type may be
represented as ordinary decimal numbers or in exponential notation. In the
decimal representation of real constants, a decimal point must be present, but no
commas are allowed. Negative real constants must be preceded by a minus sign,
but the plus sign is optional for nonnegative reals.
2.34
-0.01536 are valid real constants
+56.473
12,345 (Commas are not allowed in numeric constants.)
63 (Real constants must contain a decimal point.)

The exponential representation of a real constant consists of an integer or decimal


number, representing the mantissa or fractional part, followed by an exponent
written as the letter E with an integer constant following. For example, the real
constant 337.456 may also be written as 3.37456E2 which means 3.37456 x102
or it may be written in a variety of other forms, such as

0. 337456E3 337. 456E0 33745.6E-2 337456E-3


Character Strings
Character constants, also called strings, are sequences of symbols from the Fortran
character set.
The sequence of characters that comprise a character constant must be enclosed
between double quotes or between apostrophes (single quotes), as long as the
same character is used at the beginning and the end. The number of such
characters is the length of the constant. For example,

"PDQ123-A" is a character constant of length 8;

"John Q. Doe" is a character constant of length 11, because blanks are characters
and are included

Apostrophes could also be used to enclose the characters; for example,

'John Q. Doe

But not a mix of apostrophes and double quotes.


Identifiers
Identifiers are names used to identify programs, constants, variables, and other
entities in a program. In standard Fortran, identifiers must begin with a letter,
which may be followed by up to 30 letters, digits, or underscores
Mass
Rate are valid Fortran identifiers,
Velocity
Speed_of_Light

R2-D2 (Only letters, digits, and underscores are allowed in identifiers.)


6Feet (Identifiers must begin with a letter.)

One should always use meaningful identifiers that suggest what they represent. Fortran
90 makes no distinction between upper case and lower case (except in character
constants). A common practice-and one that we use in the sample programs in this text-
is to write all Fortran key words (e.g., READ and PRINT) in upper case and all
programmer-defined identifiers in lower case, usually capitalizing the first letter.
Variables
In mathematics, a symbolic name is often used to refer to a quantity. For example,
the formula,

These symbolic names, A, l, and w, are called variables.

When a variable is used in a Fortran program, the compiler associates it with a


memory location. The value of a variable at any time is the value stored in the
associated memory location at that time. Variable names are identifiers and thus
must follow the rules for forming valid identifiers.

The type of a Fortran variable determines the type of value that may be assigned to
that variable. It is therefore necessary to declare the type of each variable in a
Fortran program. This can be done using type statements:
Variables
Declarations of Variables
Form:

type-specifier :: list

where type-specifier is usually one of the following:

INTEGER
REAL
COMPLEX
CHARACTER (length specifier)
LOGICAL

list is a list of identifiers, separated by commas.

Purpose:
Declares that the identifiers in list have the specified type. Type statements must
appear in the specification part of the program.
Variables
Basic forms of the type statements used to declare integer variables and real variables are,
REAL :: list
INTEGER :: list
Thus, the statements
INTEGER :: NumValues, Factorial, Sum
REAL :: Mass, Velocity

One form of the type statement used to declare character variables is,
CHARACTER(LEN = n) :: list
or
CHARACTER(n) :: list
where n is an integer constant specifying the length of character constants to be assigned
to the variables in the list. The names in the list must be separated by commas. The
length specifier may be omitted, in which case the length of the values for the variables
in the list is 1. For example, the type statement
CHARACTER (15) : : FirstName, LastName
CHARACTER (15) : : FirstName, LastName*20, Initial*1, Street
The IMPLICIT NONE statement
Most programming languages require that the types of all variables be explicitly. In
Fortran, however, any variable whose type is not explicitly declared in a type statement
will be assigned a type according to an implicit naming convention: any undeclared
identifier whose name begins with I, J, K, L, M, or Nor their lowercase equivalents will be
typed as integer, and all others will be typed as real.
An unfortunate consequence of this naming convention is that failing to declare the type of
a variable is not an error, because the variables will be implicitly typed. Fortran 90
provides the IMPLICIT NONE statement, which cancels the naming convention:

IMPLICIT NONE statement


Form:

IMPLICIT NONE

Purpose:
Cancels the naming convention. This statement must appear at the beginning of
specification part of the program.
Variable Initialization

It is important to note that in Fortran, all variables are initially undefined. Although some
compilers may initialize a variable with a particular value (e.g., 0 for numeric variables),
this is not always true. It should be assumed that all variables are initially undefined, and
they therefore should be initialized in the program.

Initial values can be assigned to variables (at compile time) in their declarations:

For example, to initialize the values of variables w, X, Y, and z to 1 .0, 2. 5, 7.7 3 , and -2.
956, respectively, we could use the statements

REAL :: W = 1.0, X = 2.5, Y = 7.73, Z = -2.956


Variable Initialization
Initialization in Declarations
Form:

type-specifier :: list

where
type-specifier is as described earlier and list is a list of assignments of the form

Variable = ConstantExpression

Separated by commas

Purpose:
Declares each Variable to have the specified type and initializes it with
the given ConstantExpression at compile time.

REAL :: W = 1.0, X=2.5, Y=7.73, Z=-2.956


The PARAMETER Attribute
Certain constants occur so often that they are given names. For example, the name "pi" is
commonly given to the constant 3.14159 ....., and the name "e" to the base 2.71828 ......, of
natural logarithms. Fortran allows the Programmer to specify that an identifier names a
constant by including Parameter attribute in the declaration of that Identifier.
Declaration of Named Constants
Form:

type-specifier, PARAMETER :: list

where
type-specifier is as described earlier and list is a list of assignments of the form

Variable = constant-expression

Separated by commas

Purpose:
Associates each identifier with the specified constant value constant-expression. The
value of a named constant cannot be changed; any attempt to do so will cause a
compile-time error.
The PARAMETER Attribute
For example, the declarations

INTEGER, PARAMETER :: Limit = 50


REAL, PARAMETER :: Pi = 3.141593, TwoPi = 2.0 * Pi
CHARACTER(2), PARAMETER :: Units = "cm"

2 .0 * Pi associate the names Limit with the integer 50, Pi and TwoPi with the real constants
3.141593 and 6.283186, respectively, and Units with the character string "cm. The last
declaration can also be written

CHARACTER (*) , PARAMETER : : Units = "cm"

Here the asterisk (*) is an assumed length specifier indicating that the length of the named
constant (Units) being declared is to be the length (2) of the string constant ("cm") with which it
is being associated. The names Limit, Pi, TwoPi, and Units can be used anywhere in the program
that the corresponding constant value can be used (except as noted later in the text). For example,
a statement such as

XCoordinate =Rate * COS(TwoPi * Time)


is equivalent to
XCoordinate Rate * COS(6.283186 * Time)
Operations
In Fortran, addition and subtraction are denoted by the usual plus ( +) and minus (-) signs.
Multiplication is denoted by an asterisk ( * ). This symbol must be used to denote every
multiplication; thus, to multiply N by 2, we must use 2 * N or N * 2, not 2N. Division is
denoted by a slash(/), and exponentiation is denoted by a pair of asterisks (**). For
example, the quantity B2 - 4AC is written as,

B ** 2 4 * A * C

When two constants or variables of the same type are combined using one of the four basic
arithmetic operations ( +, -, *, /), the result has the same type as the operands. For
example, the sum of the integers 3 and 4 is the integer 7, whereas the sum of the real
numbers 3.0 and 4.0 is the real number 7 .0. This distinction may seem unimportant until
one considers the division operation. Division of the real constant 9.0 by the real constant
4.0,
9.0/4.0
produces the real quotient 2.25, whereas dividing the integer 9 by the integer 4,
9/4
produces the integer quotient 2, which is the integer part of the real quotient 2.25.
Operations Mixed mode Expressions
It is possible to combine integer and real quantities using arithmetic operations.
Expressions involving different types of numeric operands are called mixed-mode
expressions. When an integer quantity is combined with a real one, the integer quantity is
converted to its real equivalent, and the result is of real type.

1.0 / 4 -> 1.0/4.0 -> 0.25


3.0 + 8 / 5 -> 3.0 + 1 -> 3.0 + 1.0 -> 4.0
3 + 8.0 / 5 -> 3 + 8.0 / 5.0 -> 3 + 1.6 -> 3.0 + 1.6 -> 4.6

The last two examples show why using mixed-mode expressions is usually considered
poor programming practice. The only expressions in which operands of different types
should be used are those in which a real value is raised to an integer power. For such
expressions, exponentiation is carried out using repeated multiplication, as the following
examples illustrate:

2.0 ** 3 -> 2.0 * 2.0 * 2.0 -> 8.0


(-4.0) ** 2 -> (-4.0) * (-4.0) -> 16.0

If, however, the exponent is a real quantity, exponentiation is performed using logarithms.
For example, 2.0 ** 3.0 is evaluated as e3.0ln(2.0). A real exponent should never
be used in place of an integer exponent.
Operations Priority Rules
Arithmetic expressions are evaluated in accordance with the following priority rules:

1. All exponentiations are performed first; consecutive exponentiations are performed


from right to left.
2. All multiplications and divisions are performed next, in the order in which they appear
from left to right.
3. The additions and subtractions are performed last, in the order in which they appear
from left to right.

The standard order of evaluation can be modified by using parentheses to enclose sub-
expressions within an expression. These sub-expressions are evaluated first in the standard
manner.

The symbols + and - can also be used as unary operators; for example, +X and - (A + B)
are allowed. But unary operators must be used carefully, because Fortran does not allow
two operators to follow in succession. (Note that * * is interpreted as a single operator
rather than two operators in succession.)

For example, the expression N * -2 is not allowed; rather, it must be written as N * (-2 ).
The unary operations have the same low priority as the corresponding binary operations.
Operations Functions
Fortran provides library functions for many of the common mathematical operations and
functions. For example, many computations involve the square root of a quantity.
Consequently, Fortran provides a special function to implement this operation. This
function is denoted by SQRT and is used by writing

SQRT (argument)

where argument is a real-valued constant, variable, or expression. For example, to


calculate the square root of 7, we would write

SQRT(7.0)

but not SQRT (7)


If B * * 2 - 4 . 0 * A * C is a nonnegative, real-valued expression, its square root can be
calculated by writing

SQRT(B ** 2 - 4.0 * A * C)

If the value of the expression B * * 2 - 4 . 0 * A * c is negative, an error will result because


the square root of a negative number is not defined.
Operations Functions
To calculate the square root of an integer variable Number, it is necessary to convert its
value to a real value using the type conversion function REAL before using

SQRT: SQRT(REAL(Number))

The Nth root of a real variable X can be computed by using

X ** (1.0 / REAL(N))

and the Nth root of an integer variable NUM by us

REAL(NUM) ** (1.0 /REAL(N))


Operations Functions
The Assignment Statement
The assignment statement is used to assign values to variables and has the form

Assignment Statement
Form:

Variable = expression

where
variable is a valid Fortran identifier and expression may be a constant,
another variable to which a value has previously been assigned, or a formula to be
evaluated.

Purpose:
Assigns the value of expression to variable.
The Assignment Statement
For example, suppose that XCoordinate and YCoordinate are real variables and
Number and Term are integer variables, as declared by the following statements:

REAL :: XCoordinate, YCoordinate


INTEGER :: Number, Term

These declarations associate memory locations with these variables. This might be
pictured as follows, with the question marks indicating that these variables are
initially undefined.

XCoordinate = 5.23
YCoordinate = SQRT(25. 0)
Number = 17
Term = Number / 3 + 2
XCoordinate = 2.0 * XCoordinate
The Assignment Statement
Because there are different types of numeric variables and constants, it is possible to have
not only mixed-mode arithmetic, as described in the preceding section, but also mixed-
mode assignment. This occurs when the type of the value being assigned to a variable is
different from the type of the variable. If an integer-valued expression is assigned to a real
variable, the integer value is converted to a real constant and then assigned to the variable.
Thus, If the integer variable N has the value 9, and Alpha and Beta are real variables, the
statements,

Alpha = 3
Beta = (N + 3 ) / 5

assign the real value 3.0 to Alpha and the real value 2.0 to Beta. In the case of a real-
valued expression assigned to an integer variable, the fractional part of the real value is
truncated, and the integer part is assigned to the variable.
The Assignment Statement

For example, if the real variable X has the value 5.75, and I, Kappa, and Mu are integer
variables, the statements

I = 3 .14159
Kappa = X / 2.0
Mu = 1.0 / X

assign the integer values 3, 2, and 0 to the variables I, Kappa, and Mu, respectively. If it is
necessary to truncate the fractional part of a real valued expression and assign only the
integer part, it would be better to indicate this explicitly by writing, for example,

Kappa = INT(X / 2.0)


The Assignment Statement

An assignment statement may also be used to assign a value to a character variable. To


illustrate, suppose that the character variables String, Truncated, and Padded are declared
by the type statement

CHARACTER (5) :: String, Truncated, Padded*10

The assignment statement

String = "alpha"

assigns the value "alpha" to String. In this example, the declared length of the variable
is equal to the length of the value assigned to this variable. If, however, the lengths do not
match, the values are padded with blanks or truncated as necessary.
The Assignment Statement
If the declared length of the variable is greater than the length of the value being assigned,
trailing blanks are added to the value; thus the statement

Padded = "particle"

assigns the value "particle" to the variable Padded (where denotes a blank
character). If the declared length of the variable is less than the length of the value being
assigned, the value is truncated to the size of the variable, and the left most characters are
assigned; thus the statement

Truncated = "temperature"

assigns the value "tempe" to the variable Truncated. It is important to remember that the
assignment statement is not a statement of algebraic equality; rather, it is a replacement
statement. Some beginning programmers forget this and write the assignment statement
A = B

when the statement

B = A
Input - Output
In the preceding section we considered the assignment statement, which enables us to
calculate the values of expressions and store the results of these computations by assigning
them to variables. For example, if a projectile is launched from an initial height of
InitialHeight meters with an initial vertical velocity of InitialVelocity m/sec and a vertical
acceleration of Acceleration m/sec 2, then the equations,

And

give the Height in meters and the vertical Velocity in meters per second (m/sec) at any Time in
seconds after launch. Assignment statements to implement these equations are easy to write:

Height = 0.5 * Acceleration * Time ** 2 + &


InitialVelocity * Time + InitialHeight
Velocity = Acceleration * Time + InitialVelocity

(The ampersand & at the end of the first line of the first assignment statement indicates that
this statement is continued on the next line.)
Input - Output

Fortran provides two types of input/output statements.

In the first type, the programmer must explicitly specify the format in which the data is
presented for input or, in the case of output, the precise format in which it is to be
displayed.

In the second type of input/output, certain predetermined standard formats that match the
types of items in the input/output list are automatically provided by the compiler.

It is this second type, known as list-directed input/output, that we consider in this section.
Input - Output
List-Directed Output Statement
Form:

PRINT *, output-list

or

WRITE (* , * ) output-list

where output-list is a single expression or a list of expressions separated by


commas. Each of these expressions is a constant, a variable, or a formula. These
statements may also be used with no output list:

PRINT *

or

WRITE (* , * )
Purpose:
Displays the values of the items in the output list. Each output statement produces a
new line of output. If the output list is omitted, a blank line is displayed.
Input - Output
For example, the PRINT statements

PRINT *, "At time", Time, "seconds"


PRINT *, "the vertical velocity is", Velocity, "m/s"
PRINT *, "and the height is", Height, "meters"
could be used to display values of Time, Height, and Velocity. Execution of these
statements will produce output similar to the following

At time 4.5000000 seconds


the vertical velocity is 45.8700752 m/s
and the height is 4.0570767E+02 meters

Note that each PRINT statement produces a new line of output. The exact format and
spacing used to display these values are compiler-dependent, however; for example, in
some systems, all three real values might be displayed in exponential notation, and the
number of spaces in an output line might be different from that shown.
Input - Output
List-Directed Input Statement
Form:

READ *, input-list

or

READ (* , *) input-list

where input-list is a single variable or a list of variables separated by commas.

Purpose:
Obtains values (usually from the keyboard) and assigns them to the variables in the
input list.
Input - Output
The following rules apply:
1. A new line of data is processed each time a READ statement is executed.

2. If there are fewer entries in a line of input data than there are variables in the input
list, successive lines of input are processed until values for all variables in the list
have been obtained.

3. If there are more entries in a line of input data than there are variables in the input
list, the first data values are used, and all remaining values are ignored.

4. The entries in each line of input data must be constants and of the same type as the
variables to which they are assigned. (However, an integer value may be assigned
to a real variable, with automatic conversion taking place.)

5. Consecutive entries in a line of input data must be separated by a comma or by one


or more spaces.
Input - Output
For example, the statement,

READ *, InitialHeight , InitialVelocity, Time

can be used to obtain and assign values to the variables InitialHeight, Initial Velocity,
and Time. These values will be entered during program execution. For example, to
assign the values 100.0, 90.0, and 4.5 to the variables InitialHeight, Initial Velocity, and
Time, respectively, the following line of input data could be used:

100.0, 90.0, 4.5

Spaces could be used as separators in place of the commas,

100.0 90.0 4.5

or more than one line of data could be used:

100.0 90.0
4.5
Input - Output

In an interactive mode of operation, the values assigned to variables in an input list are
entered during program execution. In this case, when a READ statement is
encountered, program execution is suspended while the user enters values for all the
variables in the input list. Program execution then automatically resumes. Because
execution is interrupted by a READ statement, and because the correct number and
types of values must be entered before execution can resume, it is good practice to
provide some message to prompt the user when it is necessary to enter data values.

This is done by preceding each READ statement with a PRINT or WRITE statement
that displays the appropriate prompts.

Вам также может понравиться