Book:%20Fortran%2095-2003%20for%20Scientists%20and%20Engineers,%20by%20S.%20J%20Chapman - PowerPoint PPT Presentation

About This Presentation
Title:

Book:%20Fortran%2095-2003%20for%20Scientists%20and%20Engineers,%20by%20S.%20J%20Chapman

Description:

Book: Fortran 95-2003 for Scientists and Engineers, by S. J Chapman Transparencies prepared by Anthony T. Chronopoulos – PowerPoint PPT presentation

Number of Views:227
Avg rating:3.0/5.0
Slides: 321
Provided by: uts53
Learn more at: http://www.cs.utsa.edu
Category:

less

Transcript and Presenter's Notes

Title: Book:%20Fortran%2095-2003%20for%20Scientists%20and%20Engineers,%20by%20S.%20J%20Chapman


1
Book Fortran 95-2003 for Scientists and
Engineers, by S. J Chapman
  • Transparencies prepared by Anthony T.
    Chronopoulos

2
CHAPTER 1
  • CS1073

3
Chapter 1 Intro. to Computers and the Fortran
Language
  • The Computer
  • In summary, the major components of the computer
    are
  • CPU
  • Main Memory
  • Secondary Memory
  • Input Devices (e.g. keyboard, tapes etc)
  • Output Devices (e.g. display, monitor, tapes etc).

4
Chapter 1 Intro. to Computers and the Fortran
Language
  • The CPU
  • The Central Processing Unit is "heart (or better
    brain) of a computer.
  • The CPU consists of three main parts
  • The Control Unit - coordinates activities of the
    computer
  • The Arithmetic Logic Unit (ALU) - performs the
    calculations
  • Registers - store a small amount of data and
    instructions

5
Chapter 1 Intro. to Computers and the Fortran
Language
  • Main Memory (RAM)
  • It is larger than the Registers and smaller than
    the hard drive.
  • It temporarily stores the program currently being
    run by the computer and also the data required by
    the programs.
  • RAM is volatile, i.e. when power is interrupted,
    then what was stored in RAM is lost.

6
Chapter 1 Intro. to Computers and the Fortran
Language
  • Secondary Memory
  • It is a permanent (non-volatile) storage.
  • The hard drive is the best example, but also USB,
    CDs, tapes, etc. The size of hard drives is
    larger than that of RAM.  However, accessing data
    stored on a hard drive (or other secondary
    memory) takes much longer (5-10 times) than from
    RAM.

7
Chapter 1 Intro. to Computers and the Fortran
Language
  • Computer Languages
  • Each computer has its own machine language
    (Assembly) used to execute very basic
    operations.  Operations are load and store
    (data, to and from memory), and add, subtract,
    multiply, or divide. 
  • The problem with a machine language is that it is
    very difficult to program and use, and also it
    can be unique for a computer.

8
Chapter 1 Intro. to Computers and the Fortran
Language
  • Thus, computer scientists design high-level
    language
  • that are easy to program and use. The programs
    must
  • be converted to a machine-language (by compilers
    and
  • linkers) for the computer to run them. Examples
    are
  • Fortran, C, C, Java etc.
  • The benefit of a high-level language (e.g.
    Fortran) is that a program and can be compiled
    on any machine that has a Fortran compiler. 

9
Chapter 1 Intro. to Computers and the Fortran
Language
  • Data Representation in a Computer
  • Data is represented by millions of switches,
    each of which can be either ON (1) or OFF (0). 0
    and 1 are the two binary digits (bits).
  • We use a combination of 0's and 1's to represent
    the other numbers (and characters as well).The
    smallest common combination of bits (0's and 1's)
    is called a byte.  A byte is a group of 8 bits. A
    word is a group of 2, 4, or 8 bytes. Our PCs have
    4-byte words.

10
Chapter 1 Intro. to Computers and the Fortran
Language
  • The Binary Number System
  • The number system used by humans is the decimal
    system.  The decimal system is a base10 system.
  • There are 10 digits (0-9). Each digit in a number
    represents a power of 10.
  • The number 221 is
  • 2 102 2 101 1 100
  • (where 10i is 10 raised to exponent i
    0,1,2,..).

11
Chapter 1 Intro. to Computers and the Fortran
Language
  • Similarly, converting a number from binary (base
    2) to decimal (base 10).
  • The number 101
  • 1 22 0 21 1 20   4 0 1 5
  • If n bits are available, then those bits can
    represent 2n possible values.
  • e.g. One byte (n8 bits) can represent 256
    possible values.  Two bytes (n16 bits) can
    represent 65,536 possible values.

12
Chapter 1 Intro. to Computers and the Fortran
Language
  • Which of the following ranges would best describe
    the possible values of a byte?
  • (1) 0 ,.., 255 (2) 1 ,.., 256 (3) -127 ,.., 128
  • (4) -128 ,.., 127 . The answer is (4). 
  • The reason is that the computer must store both
  • positive and negative integers. The following
  • example illustrates how this can be achieved.

13
Chapter 1 Intro. to Computers and the Fortran
Language
Example from the car odometer/milometer. (Note
content not in Book will not be used in Exams)
Milometer readings during travel.
(a) 0 0 0 0 0 0 0 0 initial milometer reading
(b) 0 0 0 0 0 0 0 2 after two miles
(c) 0 0 0 0 0 0 0 1 after reversing one mile
(d) 0 0 0 0 0 0 0 0 after reversing one more mile
(e) 9 9 9 9 9 9 9 9 after reversing one more mile
14
Chapter 1 Intro. to Computers and the Fortran
Language
e.g. Storage of 8-digit integers, in base10
system
(a) 5 0 0 0 0 0 0 0 represents -50 000 000
(b) 5 0 0 0 0 0 0 1 represents -49 999 999
(c) 9 9 9 9 9 9 9 9 represents -1
(d) 0 0 0 0 0 0 0 0 represents 0
(e) 0 0 0 0 0 0 0 1 represents 1
(f) 4 9 9 9 9 9 9 9 represents 49 999 999
15
Chapter 1 Intro. to Computers and the Fortran
Language
e.g. Storage of (4-bit) integers e.g. Storage of (4-bit) integers
1000 -8
1001 -7
1110 -2
1111 -1
0000 0
0001 1
0010 2
0111 7
When using the binary system, the effect is that
if the first binary digit (or bit) is a one
then the number is negative, while if it is zero
the number is positive.
16
Chapter 1 Intro. to Computers and the Fortran
Language
  • Two other number systems that are also useful are
    octal (base 8) and hexadecimal (base 16).
  • Table 1-1 shows the conversion between these
    systems for the decimals 0,1, ,15

17
Chapter 1 Intro. to Computers and the Fortran
Language
  • Types of Data
  • Three common types of data are stored in a
    computer's memory character, integer, real
  • Each type has unique characteristics and takes up
    a different amount of memory.

18
Chapter 1 Intro. to Computers and the Fortran
Language
  • Character Data
  • A typical system for representing character data
    may include the following
  • Letters A through Z and a through z
  • Digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • Miscellaneous symbols, e.g. (", ', ?, ., lt, gt, ,
    , )

19
Chapter 1 Intro. to Computers and the Fortran
Language
  • In the past, it has been common to use just one
    byte of memory to represent a maximum of 256
    characters (ASCII).
  • To represent characters found in many languages,
    one can use use 2 bytes of memory which allows
    65,536 possible characters (Unicode).

20
Chapter 1 Intro. to Computers and the Fortran
Language
  • Integer Data
  • Integer data ( e.g. -1, -355, 0, 1993) are
    represented exactly on computers. However, only a
    finite number can be stored. Most machines will
    use 4 bytes of  memory to represent integers. 
  • Smallest n-bit integer -2(n-1)
  • Largest n-bit integer 2(n-1) - 1
  • e.g. n32 for 4-byte numbers.

21
Chapter 1 Intro. to Computers and the Fortran
Language
  • With 4 bytes of memory we can represent numbers
    in the approx. range -2.15billion,
    2.15billion.
  • Outside this range we get arithmetic overflow.
  • Integer data limitations (1) No fractional
    parts.
  • (2) It is not possible to represent very large
    positive integers or very small negative
    integers.

22
Chapter 1 Intro. to Computers and the Fortran
Language
  • Real Data
  • The real data type stores numbers in a format
    similar to scientific notation.
  • For example, the speed of light in a vacuum is
    about 299,800,000 meters per second.  The number
    in scientific notation would be 2.998 108 
    (m/s) meters per second.

23
Chapter 1 Intro. to Computers and the Fortran
Language
  • A format similar to scientific notation will be
    used to represent real numbers in FORTRAN.
  • Real numbers occupy 4 bytes of memory.  These 4
    bytes will be divided as follows
  • 3 byte for the fraction (or mantissa)
  • 1 byte exponent
  • The mantissa will be a number between -1 and 1.
  • The exponent will contain the power of 2 required
    to scale the number to its actual value.

24
Summary Numbers represented on the computers
Integer numbers are stored in the computer as
they are (e.g. 1321 ). The real numbers are
converted. Consider any non-zero real number as
a fraction lying between 0.1 and 1.0, called the
mantissa, which is multiplied or divided by 10 a
certain number of times, where this number is
called the exponent. e.g. 17877.0 (in fraction,
base10 form) 0.17877x105

The same technique as was used for integers to
distinguish positive and negative numbers
will be used for both the mantissa and the
exponent.
25
Chapter 1 Intro. to Computers and the Fortran
Language
  • Precision and Range
  • Precision refers to the number of significant
    digits that can be preserved in a number (on a
    computer).
  • Based on the number of bits (or bytes) in the
    mantissa,
  • 3 byte mantissa gives about 7 significant digits
    (between 1.0 and -1.0) e.g. 12345678.4 is stored
    as
  • 12345678.0. The difference (i.e. 0.4) is called
    the round-off error.

26
Chapter 1 Intro. to Computers and the Fortran
Language
  • Range is the difference between the largest and
    smallest numbers that can be represented.
  • The number of bits in the exponent e.g.
  • 1-byte exponent (with the 3-byte mantissa) allows
    a range of approximately 10-38 to 1038 (i.e.
    10-38 , 1038 )

27
Chapter 1 Intro. to Computers and the Fortran
Language
  • Evolution of Fortran
  • Fortran I Fig. 1-5
  • Fortran 77 Fig. 1-6
  • Fortran 90/2003 Fig 1-7

28
Chapter 1 Intro. to Computers and the Fortran
Language
  • Recommended Problems (not to be handed in)
  • Page 12 , Quiz 1 (answers are on the back)
  • 1(a),2(a),6,7

29
CHAPTER 2
  • CS1073

30
Chapter 2 Basic Elements of Fortran
  • 2.2 The Fortran Character Set (Table 2-1)
  • The following are valid in a Fortran 90/95
    program
  • alpha-numeric a-z, A-Z, 0-9, and _ (the
    underscore)
  • arithmetic symbols , -, , /,
  • miscellaneous symbols e.g.
  • , comma
  • . decimal point
  • lt less than
  • etc

31
Chapter 2 Basic Elements of Fortran
  • 2.3 Structure of a FORTRAN Statement
  • A program consists of a series of statements
    designed to accomplish the goal to be
    accomplished.
  • There are two basic types of statements
  • Executable statements describe the actions taken
    by the program (additions, subtractions,
    multiplications, divisions).
  • Non-executable statements provide information
    necessary for proper operation of the program.

32
Chapter 2 Basic Elements of Fortran
  • Rules on Fortran statements
  • Each line may be up to 132 characters long.
  • A statement too long to fit in a single line may
    be continued on the next line by ending the
    current line with an (ampersand). e. g.
  • output input1 input2 ! sum the inputs
  • output input1 ! Also, sum the inputs
    input2

33
Chapter 2 Basic Elements of Fortran
  • The above two statements are equivalent.
  • Commenting your code is very important.  To
    comment in FORTRAN, one uses the exclamation
    point (!).
  • All comments after the ! are ignored by the
    compiler

34
Chapter 2 Basic Elements of Fortran
  • One can use labels in some statements. A label
    can be any number between 1 and 99999.
  • Statement labels are less common in modern
    FORTRAN. 

35
Chapter 2 Basic Elements of Fortran
  • 2.4 Structure of a FORTRAN Program
  • A FORTRAN program can be divided into three
    sections
  • Declarations - This section consists of a group
    of non-executable statements at the start of the
    program.
  • Execution - This section consists of one or more
    statements describing the actions to be performed
    by the program.
  • Termination - This section consists of a
    statement (or statements) telling the computer to
    stop/end running the program.

36
Chapter 2 Basic Elements of Fortran
  • The program (in Fig. 2-1) reads two numbers as
    input, multiplies them, and prints out the result
  • PROGRAM my_first_program
  • ! Purpose
  • ! To illustrate some of the basic features of
    a Fortran program.
  • !
  • ! Declare the variables used in this program.
  • INTEGER i, j, k ! All variables
    are integers
  • ! Get two values to store in variables i and j
  • WRITE (,) 'Enter the numbers to multiply '
  • READ (,) i, j

37
Chapter 2 Basic Elements of Fortran
  • ! Multiply the numbers together
  • k i j
  • ! Write out the result.
  • WRITE (,) 'Result ', k
  • ! Finish up.
  • STOP
  • END PROGRAM my_first_program

38
Chapter 2 Basic Elements of Fortran
  • Discussion of Program Above
  • The first statement of this program begins with
    the word PROGRAM.  This is a non-executable
    statement that specifies the name of the program
    to the FORTRAN compiler.
  • The name may be up to 31 characters long and be
    any combination of alphabetic characters, digits,
    and the underscore.
  • The first character must be a letter.
  • The PROGRAM statement must be the first line of
    the program.

39
Chapter 2 Basic Elements of Fortran
  • The Declaration Section
  • This section begins with a comment stating that
    variable declarations are to follow.
  • The declaration begins with the data type
    (INTEGER) followed by two colons and then the
    variable name.
  • A comment follows the variable name.  Every
    variable must be commented as to its purpose in
    the program.
  • These statements are non-executable.

40
Chapter 2 Basic Elements of Fortran
  • The Execution Section
  • The first statement in this section is the WRITE
    statement that tells the user to enter the input.
  • The second statement will read the input and
    assign the values to the corresponding variables.
  • The third statement multiplies the two variables
    and the product is assigned to a third variable.
  • The last executable statement prints the
    product to the screen.

41
Chapter 2 Basic Elements of Fortran
  • The Termination Section
  • The STOP statement tells the computer to stop
    running the program. 
  • The use of the STOP command is optional here. 
  • The END PROGRAM statement informs the compiler
    that no more statements exist.

42
Chapter 2 Basic Elements of Fortran
  • Compiling and Executing the FORTRAN Program
  • Before a program can be run (executed) it must be
    compiled into an executable program.
  • In this process the code may also be linked to
    various system libraries.

43
Chapter 2 Basic Elements of Fortran
  • 2.5 Constants and Variables
  • A constant is a data object that is defined
    before a program is executed and it does/can not
    change during the execution of the program.
  • Constants are used in developing a good/correct
    programs in solving math problems (e.g.
  • the circle constant PI ).

44
Chapter 2 Basic Elements of Fortran
  • A variable is a data object that can change value
    during the execution of a program.
  • Referring to the sample program above
  • The data objects i,j,k are variables.
  • Each variable (or constant) must have a unique
    name inside the program.

45
Chapter 2 Basic Elements of Fortran
  • The names may contain up to 31 characters and any
    combination of alphabetic characters, digits, and
    the underscore.
  • The first character must always be alphabetic.
  • The name we assign a variable (or constant)
    should be meaningful in terms of the purpose that
    it is used to solve the problem (e.g.
  • time, distance, grade etc).

46
Chapter 2 Basic Elements of Fortran
  • 2.5.1 - 2.5.3 Types of Data
  • There are five intrinsic (or "built-in") types of
    data
  • Integer
  • Real
  • Character
  • There are two other intrinsic types that will be
    introduced later (Logical, Complex).

47
Chapter 2 Basic Elements of Fortran
  • Integers
  • Integers are numbers without a decimal point.
  • e.g. -999 , 17, 1234 (not allowed 1,234 , 17.
    )
  • No commas may be embedded within an integer
    constant.
  • If the number is positive, the sign is
    optional, but the - is required to for negative.
  • Integer variables contain the value of an integer
    data type.
  • There is a maximum and a minimum value that an
    integer can take.  The range is determined by how
    much memory is (in terms of no. of bytes) given
    to a variable of the integer type.

48
Chapter 2 Basic Elements of Fortran
  • Real Numbers
  • Real (or floating-point) numbers represent values
    with a fraction.
  • Real constants can be written with or without an
    exponent. e.g. 10. , -999.9, 1.0E-3 (i.e. 0.001
    or .001 )
  • Not allowed 1,000. , 111E3, -12.0E1.5, 1.0x
  • 10-3

49
Chapter 2 Basic Elements of Fortran
  • The mantissa should contain a decimal point.  A
    real variable is a variable that contains the
    value of a real data type.
  • There is a maximum and a minimum value that a
    real var/constant can take.  The range is
    determined by how much memory is (in terms of no.
    of bytes) given to a variable of the real type.

50
Chapter 2 Basic Elements of Fortran
  • Characters
  • A character constant is a string of characters
    enclosed in a single or double quotes.
  • Any characters representable on a computer (not
    just the Fortran characters) are legal in a
    character context (i.e. if enclosed in quotes).
  • e.g. this is, , , 3.1345

51
Chapter 2 Basic Elements of Fortran
  • Mismatching or using an odd number of quotes are
    common mistakes in programming.
  • e.g. not correct character this is , this is
  • A character variable is a variable containing a
    value of character data type. e.g. c this is
  • Character variables/constants with more than one
    character are often referred to as strings.
  • The character constant '8' is different from the
    integer constant 8.

52
Chapter 2 Basic Elements of Fortran
  • 2.5.4, 2.10 Variables and the IMPLICIT NONE
  • Checking a constant (e.g.7, 3.14156, 'John'), it
    is easy to determine which type it may be. 
    However, for a variable, we must assign a type
    to that variable.  Assigning a type reserves the
    memory needed to store the data expected (e.g.4
    bytes for 7 , 3.14156 and
  • 2 bytes/letter for 'John').

53
Chapter 2 Basic Elements of Fortran
  • There is a default type given to all variables
    for which a type is not explicitly given. This is
    used in Fortran versions before Fortran 90. In
    this case, the first letter of the names of
    variables or constants determines the type.
  • Prior to Fortran 90 Var/const names with
    letters i,j,k,l,m,n as first letter imply INTEGER
    , where as the rest of the letters imply REAL.
  • Note Fortran upper/lower case is the same. We
    use lower case for vars names e.g. i, x, c
  • and upper case for key-words (e.g. READ(,),
    STOP).

54
Chapter 2 Basic Elements of Fortran
  • In Fortran 90/95, 2003 we declare the type of
  • The REAL, INTEGER for all var/constants e.g.
  • INTEGER height
  • REAL second
  •  The IMPLICIT NONE used after the keyword
    PROGRAM means that we must specify a type for
    each variable you declare.

55
Chapter 2 Basic Elements of Fortran
  • e.g.
  • PROGRAM test_1
  • i123
  • time 10.0 ! Here time i is time is REAL type
  • OR
  • PROGRAM test_1
  • IMPLICIT NONE
  • INTEGER i
  • REAL time
  • i123
  • time10.0

56
Chapter 2 Basic Elements of Fortran
  • Character types are declared similarly, e.g.
  • CHARACTER(len5) name
  • The above will declare a variable called name
    that can be up to 5 characters long.  If the
  • (len   ) is omitted, the length is assumed to be
    1.
  • An alternative is e.g.
  • CHARACTER(20) last_name

57
Chapter 2 Basic Elements of Fortran
  • 2.5.5 Keeping Constants, Consistent
  • If we need a named constant in our program e.g.
    circle PI 3.141593
  • We declare a constant in FORTRAN using the
    PARAMETER after the type. e.g
  • INTEGER, PARAMETER num 80
  • REAL, PARAMETER PI 3.141593
  • CHARACTER(len 7) , PARAMETER ERROR error
    1

58
Chapter 2 Basic Elements of Fortran
  • 2.6 Assignment Statements and Arithmetic
    Calculations
  • An assignment statement calculates a
    Math-expression on the right of the equal sign
    and assigns it to the variable on the left of
    the equal sign.
  • variable_name expression/value
  • e.g. i i1

59
Chapter 2 Basic Elements of Fortran
  • Binary Operators (, -, , /, )
  • We can use the arithmetic operators above to
    program calculations.
  • x 3 4
  • y ab
  • z radius 2
  • The values (expressions) are resolved and
    assigned to the variables on the left.

60
Chapter 2 Basic Elements of Fortran
  • Unary Operators
  • Unary operators (just a single operand) , but the
    negate operator is one that is most common.
  • x 2
  • x -a
  • Here, take the value on the right, apply the
    operator and assign it to the variable on the
    left.

61
Chapter 2 Basic Elements of Fortran
  • Arithmetic rules in FORTRAN
  • No two operators can occur side by side.  e. g.
  • x a -b is illegal.  x a (-b) is
    allowed.
  • Implied multiplication is illegal e. g. x yz
  • instead x y z, is legal.
  • Parentheses can be used to enforce precedence in
    an expression. e. g. 2((82)/5) 2(10/5)
    22 4

62
Chapter 2 Basic Elements of Fortran
  • 2.6.1 Integer Arithmetic
  • Integer arithmetic involves only integer data.
  • Integer arithmetic always produces an integer
    result.
  • With division, the fractional part is truncated
    by the computer. e.g. 7/4 1 , 4/4 1 , 3/4 0

63
Chapter 2 Basic Elements of Fortran
  • Integers should never be used to calculate
    real-world quantities, such as distance, speed,
    or time.  Integers should only be used for things
    that are intrinsically integer in nature, such as
    counters.

64
Chapter 2 Basic Elements of Fortran
  • 2.6.2 Real Arithmetic
  • Real (or floating-point) arithmetic involves
    real data.
  • e.g. 7./4. 1.75 , 4./4. 1. , 3./4. 0.75
  • 1./3. 0.3333333
  • Note 3.(1./3.) is not equal to 1. (on some
    computers)
  • But 2.(1./2.) 1.

65
Chapter 2 Basic Elements of Fortran
  • 2.6.3 Hierarchy of operations
  • 1. Contents of ( ) are evaluated first,
    starting from the innermost and going outward.
  • 2. Exponentials are evaluated, from right to
    left.
  • 3. Multiplies/divides are evaluated, from left to
    right.
  • 4. Adds/subtracts are evaluated, from left to
    right.
  • e.g. a3.,b2.,c5.,d4.,e10.,f2.,g3.
  • output abcde/(fg1)
  • output 27.25

66
Chapter 2 Basic Elements of Fortran
  • 2.6.4 Mixed-Mode Arithmetic
  • Integer arithmetic result is an integer.
  • Real numbers arithmetic result is a real number.
  • What if we mix real/integers ?
  • In memory, the integer and real number are stored
    differently.  So, the machine must first convert
    the integer into its real number equivalent
    before performing an operation.  This conversion
    will allow real number arithmetic to be
    performed.

67
Chapter 2 Basic Elements of Fortran
  • Examples
  • 1 1/4 1
  • 1 3.0/4 1.75
  • 1. 3/4 1.
  • The computer converts an integer to a real, there
    are cases when we want control when a conversion
    should be made.  Fortran simple functions (see
    Table 2-3, x is real and i is integer)  e.g.
    x2.9 (truncate, round, select nearest integer
    below/above x) INT(x)2, NINT(x)3, FLOOR(x)2,
    CEILING(x)3, INT(-x)-2, NINT(-x)-3,
    FLOOR(-x)-3, CEILING(-x)-2

68
Chapter 2 Basic Elements of Fortran
  • 2.6.5 Mixed-Mode Arithmetic and Exponentiation
  • Cases (I) result yn, y REAL, n INTEGER
  • Converts to result yyy (n times)
  • e.g (-2.)2 result is 4. (II) result yx,
    y REAL, x REAL . We need the Math formula yx
    exp(xlny) and functions for natural
    exponential/log functions. This is done for us by
    Fortran for y gt0 e.g. 4.(-0.5) is legal.
    (III) (-2.)2.0 is illegal and gives run-time
    error.

69
Chapter 2 Basic Elements of Fortran
  • 2.7 Intrinsic Functions
  • In Math, a function is an expression that accepts
    one or more input values and calculates a single
    result from them.  e.g.
  • f(x) 3 2x x 2
  • For an x value, can one evaluate this function?
  • There are a number of standard (library)
    functions that are available in Fortran, such
    functions are called intrinsic functions.  Later
    this semester we will be writing our own
    functions, which are called user-defined
    functions.

70
Chapter 2 Basic Elements of Fortran
  • The function f(x) accepts a value x and it
    computes the result.  The value x is called the
    argument of the function. 
  • e.g. f(x, y) x y 2 , has arguments, x and
    y.
  • A set of intrinsic math functions are listed in
    Table 2-4 (trigonometric, sqrt, log, exp, max,
    min). Please make use in the Fortran programs.
    e.g. y SIN(theta)

71
Chapter 2 Basic Elements of Fortran
  • This statement will take the sine of theta (in
    radians) and assign the result to y.
  • Variable y should be real and theta can be
    real or integer.
  • Can theta be in degrees?
  • If so, it must be converted to radians,
    multiplying the value in degrees by 3.14159/180.

72
Chapter 2 Basic Elements of Fortran
  • y SIN(theta (3.141593/180.))
  • The factor DEG2RAD 3.141593/180. will be
    evaluated first and multiplied by theta.  This
    value (theta in radians) will then be used in
    the SIN function.
  • Table 2-3 and Table 2-4 list some common
    intrinsic functions.
  • Argument type (Real, Integer, or Character)
  • Result type (Real, Integer, or Character)
  • Notice that some (generic) functions (e.g. ABS(x)
    ) can accept either type and return either type
    depending on the type of the input argument.

73
Chapter 2 Basic Elements of Fortran
  • 2.8 List-Directed Input and Output
  • To make assignments and do computations, we need
    input for the calculations and to output the
    results.
  • The term list-directed input means that the types
    of the variables in the variable list determine
    the required format of the input data.

74
Chapter 2 Basic Elements of Fortran
  • The READ statement is in the form
  • READ (, ) input_list
  • where the input_list is the list of variables
    into which the values being read are stored.
  • The (, ) contain control information for the
    read ( more details, in chapter 5).

75
Chapter 2 Basic Elements of Fortran
  • Examples of input of data
  • PROGRAM input_example
  • INTEGER i, j
  • REAL a
  • CHARACTER (len12) chars
  • READ (,) i, j,a,chars ! e.g. 1,2,3., this
    course
  • END PROGRAM input_example

76
Chapter 2 Basic Elements of Fortran
  • PROGRAM input_example_2
  • INTEGER i, j,k,l
  • READ (,) i, j
  • READ (,) k,l
  • END PROGRAM input_example_2
  • e.g.
  • 1,2,3,4
  • 5,6,7
  • Then the values stored are i1, j2, k5,l6

77
Chapter 2 Basic Elements of Fortran
  • The list-directed output statement is in the
    form
  • WRITE (, )  output_list
  • Again, the term list-directed implies that the
    types of the values in the output list of the
    write statement determine the format of the
    output data.

78
Chapter 2 Basic Elements of Fortran
  • Example of output
  • PROGRAM output_example
  • INTEGER ix
  • REAL theta
  • ix1
  • theta3.141593
  • WRITE(,) ix , ix
  • WRITE(,) theta , theta, COS(theta) ,
    COS(theta)
  • END PROGRAM output_example
  • Result printed is ix1
  • theta3.141593
    COS(theta) -1.0

79
Chapter 2 Basic Elements of Fortran
  • 2.9 Initialization of Variables
  • Initialization statements by three methods (1)
    assignment, (2) READ, (3) part of type
    declaration e.g.
  • PROGRAM init123 ! Three methods to initialize
  • INTEGER i, j,k3 ! initialize
  • i1 ! initialize
  • READ (,) j ! initialize
  • WRITE(,) i, j,k
  • END PROGRAM input_example

80
Chapter 2 Basic Elements of Fortran
  • 2.9 The IMPLICIT NONE statement
  • e.g.
  • PROGRAM test_1
  • ! IMPLICIT NONE
  • REAL time10.0
  • WRITE(,) Time , tmie
  • END PROGRAM test_1
  • Wrong result is Time 0.0 . But with IMPLICIT
    NONE, we get a compile error.

81
Chapter 2 Basic Elements of Fortran
  • 2.11 Program Examples (Fig 2-6, Fig2-8)
  • Example 2-3 (Fig 2-6) Design a FORTRAN program to
    read an input temperature in degrees Fahrenheit
    (F), to convert in Kelvin (K), and to write out
    the result.
  • What does this program output?
  • The temperature in kelvins.
  • What is the input?
  • The temperature in Fahrenheit.

82
Chapter 2 Basic Elements of Fortran
  • How is the conversion done?
  • Temperature in Kelvins (5./9.) (T (in F)
    32.) 273.15
  • So, what variables are we looking at?
  • Temperature in K (REAL)
  • Temperature in F (REAL)
  • A Kelvins conversion constant (273.15)

83
Chapter 2 Basic Elements of Fortran
  • How will we know if the program works correctly?
  • We know 212 Fahrenheit is equal to 373.15 K,
  • and -110F is equal to 194.26 K. 
  • The algorithm steps
  • 1. Prompt user for input.
  • 2. Read in data from user.
  • 3. Calculate to Temperature in Kelvins
  • 4. Print output and Terminate the program.

84
Chapter 2 Basic Elements of Fortran
  • Sample Runs of the Program
  •  Enter the temperature in Fahrenheit-110The
    temperature -110.0 F is 194.26111 kelvins.
  •  Enter the temperature in Fahrenheit212The
    temperature 212.0 F is 373.15 kelvins.

85
Run Fortran Programs
  • Fortran commands to
  • (1) Compile (gives .o files)
  • (2) Link (the possibly several .o files into
    .exe file)
  • (3) Execute ( run the .exe file)
  • Note In gfortran on MS windows, (1) and (2) are
    combined into a single step.

86
Chapter 2 Basic Elements of Fortran
  • Example 2-4 (Electr. Engineer., Fig 2-8) Design a
    FORTRAN program to calculate Real, Reactive and
    Apparent power. Equations of circuit
  • IV/Z (2-3) (Z is load
    impedance)
  • PV I cos(theta) (2-4) ! power
  • QV I sin(theta) (2-5) ! reactive power
  • SV I (2-6) ! apparent power
  • PF cos(theta) (2-7) ! power factor

87
Chapter 2 Basic Elements of Fortran
  • The algorithm steps
  • 1. Prompt user for input.
  • 2. Read-in data from user.
  • 3. Calculate p q, s, pf ( (React., Real,
    Apparent) powers, power factor)
  • 4. Print output and Terminate the program.
  • Test with inputs of known results V120, Z5,
  • Theta30 degrees then I24, P2494, Q1440,
  • S2880, PF0.86603

88
Chapter 1 Intro. to Computers and the Fortran
Language
  • Recommended Problems (not to be handed in)
  • Page 35 , Quiz 2-1 (answers are on the back)
    2,4,12,15,18,21,23,24
  • Page 45 , Quiz 2-2 (answers are on the back)
    2(b,e,h), 3(c,d), 4(b,d,e), 5,6,7
  • Page 53 , Quiz 2-3 (answers are on the back),
    2,3, 4, 5,6,7,8
  • Exercises pp.73-76 (do as many of) 2-1,..,2-9

89
CHAPTER 3 Program Design and
Branching
  • CS1073

90
Chapter 3
  • Program Design and Branching Structures
  • Many problems are just too large to program
    directly their solutions. Top-Down design means
    to start with a large task and break it down into
    smaller ones (subtasks), which we can program
    independently.
  •   Key Ideas in Top-Down Design (1) Divide the
    larger task into smaller sub-tasks. (2) Code and
    test each sub-task. (3) Put together the solution.

91
Chapter 3
  • Steps of Program Design in the Top-Down Approach
  • 1. State the problem.
  • 2. Define inputs and outputs.
  • 3. Design the algorithm.
  • 4. Turn the solution into Fortran statements.
  • 5. Test (and debug) the Fortran program.
  • Which step would require the most time? Step 5! 
  • How can we reduce the time for this step?  By
    spending more time on steps 1-4.

92
Chapter 3
  • The constructs to build an algorithm use either
    flowcharts or pseudocode. We will use the
    pseudocode, which describes the steps in English
    and mathematical formulas ready to be programmed.
  • Example (pseudocode to convert the
    temperatures)
  • Prompt the user for the input temperature in
    Fahrenheit
  • Read temperature in degrees Fahrenheit (temp_f)
  • temp_k ? (5. / 9.) (temp_f - 32.) 273.15
  • Write temperature in Kelvin degrees

93
Chapter 3
  • 3.3 Logical Constants, Variables, and Operators
  • The logical data type can store one of two
    values .TRUE. or .FALSE. A logical variable is
    a variable containing a value of the logical data
    type and can be declared as follows
  • PROGRAM example
  • LOGICAL log1, log2 ! logical vars
  • LOGICAL, PARAMETER logconst.TRUE.
  • Executable statements

94
Chapter 3
  • Logical vars/consts are used in branch
    statements (using IF). e.g. For computing cubic
    roots, for x gt0
  • PROGRAM example_IF
  • IMPLICIT NONE
  • LOGICAL log1
  • REAL x8. , cube_root
  • log1 ( x gt 1.E-10) ! logical var logical
    expression
  • IF(log1) THEN
  • cube_root EXP(LOG(x)/3.0 )
  • ELSE
  • cube_root 0.0
  • ENDIF
  • WRITE (,) 'log1', log1, 'cube_root',
    cube_root
  • END PROGRAM example_IF
  • Note In Math x 1/3 e(log(x)/3), and we
    must have xgt0

95
Chapter 3
  • 3.3.3 Relational Operators
  • Relational logic operators are operators with two
    numeric (or character) operands that produces a
    logical result. The new style operators were
    introduced with FORTRAN 90.
  • e.g. gt (ABS(x) gt 1.E-10)
  • Table 3-1 (next page) contains all the relational
    logic operators in Fortran 90 and the old
    versions (Fortran 77).

96
Chapter 3, Table 3-1Relational logic operators
97
Chapter 3
  • Examples Operation Result
  • 3lt4 .TRUE.
  • 3 /4 .TRUE.
  • 3gt4 .FALSE.
  • A lt B .TRUE. (because
    characters are evaluated in alphab. order)
  • Also, (72) lt (101) .TRUE.
  • 72 lt 101 .TRUE.
  • 4 4. .TRUE.
  • 4 ltA illegal (compile
    error)

98
Chapter 3
  • 3.3.4 Combinational Logic Operators
  • Combinational logic operators are operators with
    one or two logical operands that yield a logical
    result.
  • The operators are
  • .AND., .OR., .NOT., .EQV., .NEQV.
  • Examples Let a,b,c,d be real/integer variables.

99
Chapter 3
  • (altb) .OR. (cltd)
  • ( , ) can be omitted
  • e.g. altb .OR. cltd !But may confuse us so use
    ( , )
  • (altb) .OR. (cltd)
  • e.g. For a 2 , b 3 , c 5 , d 3 the value
    of the logical expressions above is .TRUE.
  • Let the logical expressions l1 (a lt b) and
    l2 (c lt d) , the results of the operators are
    in
  • Tables 3-3(A,B) (which are called truth tables).

100
Chapter 3
  • Table 3-3, Combinational operators
  • log1 log2 log1.OR.log2 log1.AND.log2
    .NOT.log1
  • true true true true
    false
  • true false true false
    false
  • false true true false
    true
  • false false false false
    true
  • log1 log2 log1.EQV.log2 log1.NEQV.log2
  • true true true false
  • true false false true
  • false true false true
  • false false true false

101
Chapter 3
  • . NOT. is a unary operator gives .TRUE. for value
    .FALSE. and vice-versa
  • e.g. The following expressions are equivalent
    (e.g. for values of variables a 2 , b 3,
    c5)
  • log1 .NOT. (altb .AND. bltc)
  • log2 agtb .OR. bgtc
  • i.e. log1.EQV.log2 .TRUE.

102
Chapter 3
  • e.g. Mixed operations (ab) lt (cd) .OR. 3gt4
  • Precedence order
  • 1. arithmetic operators (, , etc, evaluated
    left-to-right)
  • 2. relational operators ( lt , , etc,
    evaluated from left to right)
  • 3. .NOT.
  • 4. .AND. (evaluated from left to right)
  • 5. .OR. (evaluated from left to right)
  • 6. .EQV. and .NEQV. (evaluated from left to
    right)

103
Chapter 3
  • Note combinational operators are illegal to use
    with real/integer/character e.g.
  • 4 .AND. 3 (compile-error)
  • 3.3.5 Logical values for Input/Output statements
  • When entering data, using READ(,), if the first
    entered character is T then .TRUE. is read in
  • similarly for .FALSE.
  • 3.3.6 Significance of Logical variables/expression
    s
  • They are mostly used with IF statements.

104
Chapter 3
  • 3.4 Control constructs Branches
  • Branches in Fortran allow us to execute
    (depending on the value true/false of logical
    values/expressions) specific parts of the program
    and skip other parts.
  • The block IF construct is
  • IF (logical_expression) THEN
  • ELSE IF (logical_expression) THEN
  • IF(.NOT. (a lt b. AND. b lt c)) ! Example of block
    IF
  • x a b !
    e.g. a3,b4, c5
  • ELSE IF (a lt b. AND. b lt c)
  • x c b
  • ENDIF

105
Chapter 3 , 3.4.2 The ELSE and ELSE IF
3.4.2 The ELSE and ELSE IF IF (criterion_1)
THEN action_1 ELSE IF (criterion_2)
THEN action_2 ELSE IF (criterion_3)
THEN action_3 ELSE action_4 END IF A
minimal block IF IF (criterion)
THEN action END IF
106
Chapter 3
  • Example of Fortran program The quadratic
    equation (PROGRAM roots, Fig-3-10).
  • Examples of inputs to test the program
  • x25x6 0, roots -2, -3
  • x24x4 0, roots -2 (double)
  • x22x5 0, roots -12i, -1-2i (complex)

107
Chapter 3
  • Example of Fortran program Evaluating a
    function of two variables (PROGRAM funxy,
    Fig-3-12).
  • Test the program
  • f(2,3) 5
  • f(-2,3) 7
  • f(2,-3) 11
  • f(-2,-3) 13

108
Chapter 3
  • 3.4.4 The named block IF constructs
  • name IF (logical expression) THEN
  • statement1
  • ELSE IF (logical expression) THEN
  • statement1
  • ELSE
  • statement1
  • END IF

109
Chapter 3
  • 3.4.5 Notes concerning use of block IF
    constructs
  • Block IF may be nested
  • outer IF (xgt0.) THEN
  • statement1
  • inner IF (ylt0.) THEN
  • statement1
  • END IF inner
  • statement1
  • END IF outer

110
Chapter 3
  • 3.4.6 The logical IF statement
  • e.g. IF(xlt0.) y-1
  • Note Better to avoid it and use Block IF,
    instead.
  • 3.4.7 The SELECT CASE construct
  • deals with many alternatives are mutually
    exclusive.
  • The case selector must be integer, character,
    or logical
  • expression. But real expressions are not
    allowed.

111
Chapter 3
  • nameSELECT CASE (case expression)
  • CASE (case selector) !mutually
    exclusive case
  • block of Fortran statements
  • CASE (case selector) !mutually
    exclusive case
  • block of Fortran statements
  •   .
  • .
  • END SELECT name

112
Chapter 3
  • Example of Fortran program Use SELECT CASE to
    select the day of the week
  • (PROGRAM day_of_week, Fig-3-14).
  • Test e.g.
  • 1
  • Day Sunday

113
Chapter 3
  • Example of Fortran program Use characters in a
    SELECT CASE construct
  • (PROGRAM weekday_weekend, Fig. 3-15).
  • Test e.g.
  • Tuesday
  • Day Type weekday

114
Chapter 3
  • Example Assigning letter grades
  • 90lt grade A
  • 80lt grade lt89 B
  • 70lt grade lt79 C
  • 61lt grade lt69 D
  • 0lt grade lt60 F

115
Chapter 3
  • (a) Solution without nested (start from highest
    grade and create mutual exclusive logical
    exressions)
  • IF (grade gt 90) THEN
  • WRITE(,) The grade is A
  • ELSE IF (grade gt 80) THEN
  • WRITE(,) The grade is B
  • ELSE IF (grade gt 70 ) THEN
  • WRITE(,) The grade is C
  • ELSE IF (grade gt 61 ) THEN
  • WRITE(,) The grade is D
  • ELSE
  • WRITE(,) The grade is F
  • END IF

116
Chapter 3
  • (b) Solution using nested IF
  • (in textbook p. 111), to be avoided because it
    may lead to errors.
  • (c) Solution using SELECT CASE
  • left as an exercise (not to be handed in).

117
Chapter 3
  • 3.5 Debugging Fortran programs
  • We can insert WRITE(,) statements into the
  • program to print out important vars at key
    points of the program. e.g. Verify correctness of
    block IF
  • WRITE(,) At if1 var1 , var1
  • if1 IF(sqrt(var1) gt1.) THEN
  • WRITE(,) At if1 sqrt(var1) gt1.
  • ELSE IF(sqrt(var1) lt1.) THEN
  • WRITE(,) At if1 sqrt(var1) lt1.
  • ELSE
  • WRITE(,) At if1 sqrt(var1) 1.
  • END IF if1

118
Chapter 3
  • When we locate in which part of the program the
    error occurs. We check the statements to discover
    it. Examples of common errors with IF statements
  • Check the relational operators e.g. maybe gt
  • is needed instead of gt , etc.
  • 2. When we test for equality of real
    vars/consts (unlike integers), we can not use
    .
  • We must use e.g. IF(ABS(x-10.) lt 0.000001) THEN
  • IF(x10.), for x real, may be false because in
    some computer x0.9999999 (which is 10.0).

119
Chapter 3
  • Recommended Problems (not to be handed in)
  • Page 95 , Quiz 3-1 (answers are on the back)
    1(a,b,d,f,h), 2
  • Page 117 , Quiz 3-2 (answers are on the back)
  • 1,2,4,6,7
  • Page 123-124, Exercises 3-1, 3-2, 3-4, 3-6, 3-7

120
Chapter 4 LOOPS AND CHARACTER MANIPULATION
  • Objectives
  • Know how to create and use while loops.
  • Know how to create and use counting loops.
  • Know when to use while loops, and when to use
    counting loops.
  • Know the purpose of the CONTINUE and EXIT
    statements, and how to use them.
  • Understand loop names, and why they are used.
  • Learn about character assignments and character
    operators.
  • Learn about substrings and string manipulations.

121
While Loop
  • The While Loop
  • DO
  • ... !
  • IF (logical_expr) EXIT ! Code block
  • ... !
  • END DO
  • The block of statements between the DO and END DO
    are repeated indefinitely until the logical_expr
    becomes true and the EXIT statement is executed.
    After the EXIT statement is executed, control
    transfers to the first statement after the END
    DO.

122
Statistical Analysis
  • Example The average and standard deviation of
    set of numbers ( xi is sample i out of N
    samples)

123
Problem
  • 1. State the problem Calculate the average and
    the standard deviation of a set of , if
    measurements are either positive or zero, and if
    we do not know in advance how many measurements
    there are. A negative input value will mark the
    end of the set of measurements.
  • 2. Define the inputs and outputs The inputs are
    a number of positive or zero real
    (floating-point) numbers.

124
Algorithm
  • 3. Design the algorithm (steps)
  • Accumulate the input data
  • Calculate the mean and standard deviation
  • Write out the mean, standard deviation, and
    number of points

125
PseudoCode
  • The pseudocode for these steps is
  • Initialize n, sum_x, and sum_x2 to 0
  • WHILE
  • Prompt user for next number
  • Read in next x
  • IF x lt 0. EXIT
  • n ? n 1
  • sum_x ? sum_x x
  • sum_x2 ? sum_x2 x2
  • End of WHILE

126
PseudoCode
  • Pseudocode to Calculate the mean and standard
    deviation.
  • x_bar ? sum_x / REAL(n)
  • std_dev ?SQRT((REAL(n)sum_x2 - sum_x2) /
    (REAL(n)REAL(n-1)))
  • Write out the results
  • Write out the mean value x_bar
  • Write out the standard deviation std_dev
  • Write out the number of input the n data points

127
Turn the algorithm into Fortran statements
  • PROGRAM stats_1
  • IMPLICIT NONE
  • INTEGER n 0 ! The number of input
    samples.
  • REAL std_dev 0. ! The standard deviation of
    the input samples.
  • REAL sum_x 0. ! The sum of the input
    values.
  • REAL sum_x2 0. ! The sum of the squares of
    the input values.
  • REAL x 0. ! An input data value.
  • REAL x_bar ! The average of the input
    samples.

128
Turn the algorithm into Fortran statements
  • DO ! While Loop to read input values.
  • ! Read in next value
  • WRITE (,) 'Enter number '
  • READ (,) x
  • WRITE (,) 'The number is ', x
  • ! Test for loop exit
  • IF ( x lt 0 ) EXIT
  • ! Otherwise, accumulate sums.
  • n n 1
  • sum_x sum_x x
  • sum_x2 sum_x2 x2
  • END DO

129
Turn the algorithm into Fortran statements
  • ! Calculate the mean and standard deviation
  • x_bar sum_x / real(n)
  • std_dev sqrt( (real(n) sum_x2 - sum_x2) /
    (real(n) real(n-1)) )
  • ! Tell user.
  • WRITE (,) 'The mean of this data set is',
    x_bar
  • WRITE (,) 'The standard deviation is ',
    std_dev
  • WRITE (,) 'The number of data points is', n
  • END PROGRAM stats_1

130
Test the program
  • For input values 3, 4, and 5
  • 3.
  • The number is 3.000000
  • Enter number
  • 4.
  • The number is 4.000000
  • Enter number
  • 5.
  • The number is 5.000000
  • Enter number
  • -1.
  • The number is -1.000000
  • The mean of this data set is 4.000000
  • Enter number
  • The standard deviation is 1.000000
  • The number of data points is 3

131
The DO WHILE Loop
  • There is an alternate form of the while loop in
    Fortran 95/2003, called the DO WHILE loop. The
    DO WHILE construct has the form
  • DO WHILE (logical_expr)
  • ... ! Statement 1
  • ... ! Statement 2
  • ... ! ...
  • ... ! Statement n
  • END DO
  • Good Programming Practice Do not use DO WHILE
    loops in new programs. Use the more general while
    loop instead.

132
The Iterative or Counting Loop
  • DO index istart, iend, incr
  • Statement 1 !
  • ... ! Body
  • Statement n !
  • END DO
  • Loop index variable index
  • Loop parameters (constants or variables)
    istart, iend, incr
  • Note All these variables or constants must be
    declared before the loop as INTEGER .

133
The Iterative or Counting Loop
  • How loop works
  • 1. Evaluate parameters istart, iend, and incr
  • 2. Index ? istart If indexincr lt iendincr,
    the program executes the statements within the
    body of the loop.
  • 3. recalculate index index incr
  • 4. If indexincr lt iendincr, goto to 2. above
    and repeat .

134
The Iterative or Counting Loop
  • The number of times the count loop (without an
    IF () EXIT) is executed is given by the integer
    arithmetic expression
  • (iend-istartincr)/incr
  • Also, the count loop will not be executed if for
    all index values for which
  • indexincr gt iendincr

135
Examples
  • DO i 1, 10
  • Statement 1
  • ...
  • Statement n
  • END DO
  • DO i 1, 10, 2
  • Statement 1
  • ...
  • Statement n
  • END DO

136
Examples
  • DO i 1, 10, -1
  • Statement 1
  • ...
  • Statement n
  • END DO
  • DO i 3, -3, -2
  • Statement 1
  • ...
  • Statement n
  • END DO

137
Examples
  • The Factorial Function To illustrate the
    operation of a counting loop, we will use a DO
    loop to calculate the factorial function. For
    integer numbers n (in mathematics) the factorial
    function is defined as
  • n! 1 if n 0
  • n! n (n-1) (n-2) ... 3 2 1 if
    n gt 1
  • e.g. for n4 then n!432124.
  • The Fortran code to calculate n factorial for
    ngt0 is
  • n_factorial 1 ! We use the variable name
    n_factorial for n!
  • DO i 1, n
  • n_factorial n_factorial i
  • END DO

138
Examples
  • If n is 5, the DO loop parameters will be istart
    1, iend 5, and incr 1. The factorial will
    be
  • 12345 120
  • Example 4-3Calculating the Day of Year
  • 1. Years evenly divisible by 400 are leap years.
  • 2. Years evenly divisible by 100 but not by 400
    are not leap years.
  • 3. All years divisible by 4 but not by 100 are
    leap years.
  • 4. All other years are not leap years.
  • See the program Figure 4-6 (PROGRAM doy).

139
Examples (Programming Pitfalls)
  • DO i 3, 2
  • ...
  • END DO
  • Since (iend-istartincr)/incr (2-31)/10, the
    DO loop will never be executed.
  • Count down loops
  • DO i 3, 1, -3
  • ...
  • END DO
  • Since(iend-istartincr)/incr (1-3(-3) )/(-3)
    -5/(-3) 1, the DO loop will be executed only
    once (for i3).

140
Examples (Program Pitfalls)
  • Good Programming Practice
  • Never modify the value of a DO loop index
    variable while inside the loop.
  • Never depend on a loop index variable to retain a
    specific value after a DO loop completes
    normally. So, avoid using it in statements after
    the loop (see the examples in the next page).

141
Examples (Program Pitfalls)
  • INTEGER i ! Branch out of the loop
    before completion
  • DO i 1, 5
  • ...
  • IF (i gt 3) EXIT
  • ...
  • END DO
  • The value of the index variable i3 when the
    loop is completed.
  • INTEGER i
  • DO i 1, 5
  • ...
  • END DO
  • WRITE (,) i
  • The value of the index variable i is undefined
    when the loop is completed.

142
The CYCLE and EXIT Statements
  • There are two additional statements which can be
    used to control the operation of while loops and
    counting DO loops CYCLE and EXIT.
  • If the CYCLE statement is executed in the body
    of a DO loop, the execution of the current
    iteration of the loop will stop, and control will
    be returned to the top of the loop. The loop
    index will be incremented, and execution will
    resume again if the index has not reached its
    limit.

143
The CYCLE and EXIT Statements
  • Example with CYCLE
  • PROGRAM test_cycle
  • INTEGER i
  • DO i 1, 5
  • IF ( i 3 ) CYCLE ! If true go next to
    start of the loop
  • WRITE (,) i
  • END DO
  • WRITE (,) End of loop!
  • END PROGRAM test_cycle

144
The CYCLE and EXIT Statements
  • If the EXIT statement is executed in the body of
    a loop, the execution of the loop will stop and
    control will be transferred to the first
    executable statement after the loop. An example
    of the EXIT statement in a DO loop is shown
    below.
  • PROGRAM test_exit
  • INTEGER i
  • DO i 1, 5
  • IF ( i 3 ) EXIT ! If true go next to end of
    the loop
  • WRITE (,) i
  • END DO
  • WRITE (,) End of loop!
  • END PROGRAM test_exit

145
Named Loops
  • name DO
  • Statement
  • Statement
  • ...
  • IF ( logical_expr ) CYCLE name
  • ...
  • IF ( logical_expr ) EXIT name
  • ...
  • END DO name
  • Good Programming Practice Assign a name to any
    large and complicated loops in your program to
    help you keep the parts of the construct
    associated together in your own mind.

146
Named Loops
  • name DO index istart, iend, incr
  • Statement
  • Statement
  • ...
  • IF ( logical_expr ) CYCLE name
  • ...
  • END DO name

147
Nesting Loops
  • It is possible for one loop to be completely
    inside another loop. If one loop is completely
    inside another one, the two loops are called
    nested loops.
  • The following example shows two nested DO loops
    used to calculate and write out the product of
    two integers.

148
Nesting Loops
  • PROGRAM nested_loops
  • INTEGER i, j, product
  • DO i 1, 3
  • DO j 1, 3
  • product i j
  • WRITE (,) i, ' ', j, ' ', product
  • END DO
  • END DO
  • END PROGRAM nested_loops

149
Nesting Loops
  • The results are
  • 1 1 1
  • 1 2 2
  • 1 3 3
  • 2 1 2
  • 2 2 4
  • 2 3 6
  • 3 1 3
  • 3 2 6
  • 3 3 9
  • When a Fortran compiler encounters an END DO
    statement, it associates that statement with the
    innermost currently open loop. Good Programming
    Practice Assign names to all nested loops so
    that they will be easier to understand and debug.

150
Nesting Loops
Compiling a named loop helps us find errors
PROGRAM bad_nested_loops_2 INTEGER i,
j, product outer DO i 1, 3
inner DO j 1, 3 product i j
WRITE
(,) i, ' ', j, ' ', product END DO outer
END PROGRAM bad_nested_loops_2 ba
d_nested_loops_2.f90(7) Error The block
construct names must match, and they do not.
OUTER END DO outer ------- bad_nested_loops_2.f
90(3) Error An unterminated block
exists. outer DO i 1, 3 compilation aborted
for bad_nested_loops_2.f90 (code 1)

151
Nesting Loops
  • If two loops are to be nested, one of them must
    lie completely within the other one. e.g. of DO
    loops are incorrectly nested
  • outer DO i 1, 3
  • ...
  • inner DO j 1, 3
  • ...
  • END DO outer
  • ...
  • END DO inner
  • Good Programming Practice Assign names to all
    nested loops so that they will be easier to
    understand and debug.

152
Nested Loops with CYCLE or EXIT
  • If a CYCLE or EXIT statement appears inside an
    unnamed set of nested loops, then the CYCLE or
    EXIT statement refers to the innermost of the
    loops containing it. e.g.
  • PROGRAM test_cycle_1
  • INTEGER i, j, product
  • DO i 1, 3
  • DO j 1, 3
  • IF ( j 2) CYCLE
  • product i j
  • WRITE (,) i, ' ', j, ' ', product
  • END DO
  • END DO
  • END PROGRAM test_cycle_1

153
Nested Loops with CYCLE or EXIT
  • The resulting output values are
  • 1 1 1
  • 1 3 3
  • 2 1 2
  • 2 3 6
  • 3 1 3
  • 3 3 9

154
Nested Loops with CYCLE or EXIT
  • PROGRAM test_cycle_2 ! Skip remainder of the code
    block of the inner DO
  • INTEGER i, j, product
  • outer DO i 1, 3
Write a Comment
User Comments (0)
About PowerShow.com