Home Work 1
• Problem: Write a flow Chart to find the area of
an arbitrarily shaped plane figure
• Figure defined by X,Y coordinates of vertices
Introduction to Computer Programming 1
Input options
• How do we get the information into the
program?
• Consider possible cases
3
2 3
2 3
2 4
4 5
1 5 1 4
1 5
• For an arbitrary set of coordinates the figure
is obvious, but in others it is not
Introduction to Computer Programming 2
Input options (Cont)
• So how do we handle this?
• Force the user to input or read the values in
the correct order?
• What if user makes a mistake and generates
a figure with crossing lines?
3 3
2 4
4 2
1 5 1 5
Introduction to Computer Programming 3
Input options (Cont)
• By considering scenarios before hand we can
make a robust program
• What you have decided to assume
• Ask user number of points that will be
entered? Or read list until End-of-file?
• Maximum number of points user can enter
Introduction to Computer Programming 4
Calculation of Area
1. Area = axh/2
2. Area = axbxsin(C)/2
3. Area = a2xsin(B)xsin(C)/(2xsin(B+C))
4. Area = sqrt(sx(s-a)x(s-b)x(s-c))
where s=(a+b+c)/2 is the semi-perimeter
Introduction to Computer Programming 5
Other Issues
• Forming triangles
• Output
• What units will say the area is in?
• Should we tell the user if lines cross?
Introduction to Computer Programming 6
Introduction to
Fortran
7
I DON’T KNOW WHAT THE PROGRAMMING
LANGUAGE OF THE YEAR 2000 WILL LOOK LIKE,
BUT I KNOW IT WILL BE FORTRAN. (1960)
CHARLES ANTHONY RICHARD HOARE
Introduction to Computer Programming 8
FORTRAN (Formula
Translation)
• History
• Developed between 1954-1957 at IBM
• FORTRAN II released in 1958
• FORTRAN IV released in 1962 (standard for next 15
years)
• FORTRAN 66 ANSI standard
• FORTRAN 77 standard in 1977
• Fortran 90 Added new features
• In 1997 Fortran 95 released (started phasing out
some FORTRAN 77 features)
Introduction to Computer Programming 9
Fortran References
• http://www.fortran.com/fortran/F77_std/rjcnf0001.html
• http://h21007.www2.hp.com/dspp/files/unprotected/Fortran/docs
/lrm/dflrm.htm
• http://docs.cray.com/books/007-3692-003/html-007-3692-
003/007-3692-003-toc.html
• You can get tons of other online books, just Google Fortran
online books
Introduction to Computer Programming 10
How Does Fortran Work?
• FORTRAN is a complied language so the source
code (what you write) must be converted into
machine code before it can be executed
FORTRAN FORTRAN Link with Executable
Compiler Libraries File
Program
Executable
Source Code Object Code Code
Libraries
Make Changes Test & Debug Execute
in Source Code Program Program
Introduction to Computer Programming 11
Source Code
• In principle you have several options
for where to write your FORTRAN
programs.
• You can use
1. Fortran editor
2. Any windows editor
Introduction to Computer Programming 12
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.
Program Structure
• Your program should have the following
form:
PROGRAM program-name
IMPLICIT NONE
[specification part]
[execution part]
[subprogram part]
END PROGRAM program-name
Introduction to Computer Programming 14
Program Structure
• A Fortran program consists of one or more program
units
• A program unit is usually a sequence of statements
that define the steps necessary to perform
calculations
• A program unit can be either
– Main program (Start with PROGRAM )
– Subroutine subprogram (Start with SUBROUTINE )
– Function subprogram (Start with FUNCTION )
– Block data program unit (Start with BLOCKDATA )
• An executable program contains one main program,
and, optionally, any number of the other kinds
Introduction to Computer Programming 15
Statements
• The basic unit of the Fortran language is the statement,
which has a specific meaning to the processor
• There are two types of statements
– Executable
– Non executable
• An executable statement specifies an action to be
performed
• A nonexecutable statement describes program
attributes, such as the arrangement and characteristics
of data
• All non-executable commands must appear before the
executable ones
Introduction to Computer Programming 16
Statements
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
Statements
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
Statements
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.
Statements Examples
Executable Non executable
CALL DATA
CLOSE CHARACTER
DO SUBROUTINE
DO WHILE REAL
END DO INTEGER
IF (exp) THEN COMPLEX
STOP FUNCTION
READ COMMON
WRITE EXTERNAL
Introduction to Computer Programming 20
Example First Program
• This program 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
! Multiply the numbers together
k = i * j
! Write out the result.
WRITE (*,*) 'Result = ', k
! Finish up.
STOP
END PROGRAM my_first_program
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.
Discussion of Program Above
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.
Discussion of Program Above
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.
Discussion of Program Above
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.
The Compilation Process
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.
• Compiling the program is the first step in testing a program
after it is written
• The compiler checks if the program is written correctly (the
syntax is correct)
• It won’t spot mistakes that are “grammatically correct”
Introduction to Computer Programming 26
Basic Fortran
1. Alphabets (Character Sets)
2. Constants (data)
3. Identifiers
4. Variables and Their Types
5. Variable Declarations
6. Assigning a Constant a Name - PARAMETER attribute
7. Initializing Variables
8. Arithmetic Operators
9. Simple Mode Arithmetic Expressions
10. Mixed Mode Arithmetic Expressions
11. The Assignment Statement
12. Intrinsic Functions
13. List-Directed Input: The READ Statement
14. List-Directed Output: The WRITE Statement
Introduction to Computer Programming 27
Character Sets
• Fortran supports the following characters:
• All uppercase and lowercase letters (A- Z &
a- z)
• The numerals 0 through 9
• The underscore ( _ )
• The following special characters
Introduction to Computer Programming 28
Character Sets
Character Name Character Name
blank or Blank (space) or
: Colon
<Tab> tab
Exclamation
= Equal sign !
point
+ Plus sign " Quotation mark
- Minus sign % Percent sign
* Asterisk & Ampersand
/ Slash ; Semicolon
( Left parenthesis < Less than
) Right parenthesis > Greater than
, Comma ? Question mark
Period (decimal
. $ Dollar sign
point)
' Apostrophe
Introduction to Computer Programming 29
Constant (Data Types)
• Fortran contains five basic data types:
– INTEGER
– REAL
– COMPLEX
– CHARACTER
– LOGICAL
• The character type is used to store and
process strings of characters
• The logical type is used to store and process
logical data (true or false)
Introduction to Computer Programming 30
Integer Data Type
• An Integer is a whole number (positive,
negative or zero)
Examples:
Correct Incorrect
0 0.
137 5,334
-2439 --5
+1933 4-
Introduction to Computer Programming 31
Real Data Type
• Numbers of type Real are numbers that are
expressed with decimal points or in
exponential notation
Examples:
Correct Incorrect
1.43278 12,345
-0.0132 63
+56.55 1.27e3.1
1.
6.023e023
1.0e-009
Introduction to Computer Programming 32
Double Precision Data Type
• Double Precision is a subset of the Real
data type and is used when a higher degree
of precision is desired.
• For example, compute the fraction 22.0/7.0
on a 32-bit desktop
Real 3.142857
Double Precision 3.14285707473755
- In this example, the number of significant
digits is increased from 7 to 14.
Introduction to Computer Programming 33
Complex Data Type
• A complex number is represented as a pair
of real constants: (a,b)
• where a and b represent the real and
imaginary parts of the complex number
respectively
Examples:
Fortran Representation Common Notation
(1.0, 1.0)
(-6.0, 7.2)
(7.88, -1.1)
Introduction to Computer Programming 34
Logical Data Type
• There are only two possible values for the
data type logical:
– .true.
– .false.
• Note that the periods must appear as part of
the logical constant
Introduction to Computer Programming 35
Identifiers
• Identifiers are names used to identify
– constants,
– variables, and
– other entities in a program
• Identifiers must begin with a letter, which may be
followed with up to 30 letters, digits, or underscores
• Fortran is not case sensitive (except in character
constants)
– VELOCITY= Velocity = vEloCIty
• Identifiers should reflect the thing it represents
Introduction to Computer Programming 36
Examples of Identifiers
Correct Incorrect
mass 3mass
rate .rate.
velocity1 specific-discharge
specific_discharge student height
head0 less_than_10%
student_height verbal+quantitative
Good Bad
speed_of_light sol
student_height studhit
conductivity con
GRE_score gres
Introduction to Computer Programming 37
Variables
• A variable is an association between a Fortran identifier (name)
and a memory location containing a number
• Since variable names are identifiers, they must follow the same
rules as identifiers
• Fortran variables can be any of the five data types that we have
just defined:
– INTEGER
– REAL
– COMPLEX
– CHARACTER
– LOGICAL
• How does the compiler know what type of variable you want, once you
give it a name?
Introduction to Computer Programming 38
Type Statement
• Type statements take the form:
– TYPE :: list (F90)
• or:
– TYPE list (F77)
• where TYPE is one of the five data types
• and list is a list of Fortran variable names, each
separated by a comma
• Type statements (sometimes called declaration
statements) must appear before the first executable
statement in a program
Introduction to Computer Programming 39
Examples of Type Statements
Correct
INTEGER :: i, student_number, counter
REAL :: x, y, conductivity
INTEGER i,j,k
REAL head, velocity
Incorrect
INTEGER :: i j k counter
REAL , red, yellow, green
Introduction to Computer Programming 40
Implicit Type Declaration
• If you don’t declare variables in type statements,
there is a Fortran default way of declaring them
• Variables that start with the letters:
– a-h, o-z
– are typed as reals
• Variables that start with the letters:
– i,j,k,l,m,n
– are typed as integers
• Using implicit declaration is somewhat old-fashioned,
but more importantly, will lead to mixed model
arithmetic which can often be the source of problems
and bugs in programs
Introduction to Computer Programming 41
IMPLICIT NONE Statement
• To avoid implicit declaration, the first statement in
your program should be:
– IMPLICIT NONE
• which tells the compiler not to implicitly type any
variables
• You must therefore explicitly declare each and every
variable with type declaration statements
• This helps avoid problems with mixed-mode
arithmetic and is considered “modern” programming
practice
Introduction to Computer Programming 42
Fortran Arithmetic
Fortran Usual Notation
• addition: a + b
• subtraction: a - b
• multiplication: a * b
• division: a / b
• exponentiation: a**b
Introduction to Computer Programming 43
Variables Initialization
• Do not assume the compiler or computer
will put some value, say 0, into a variable.
• There are at least three ways to put a value
into a variable:
– initializing it when the program is run
– using an assignment statement
– reading a value from keyboard or other device
with a READ statement.
Introduction to Computer Programming 44
Variables Initialization
• Examples:
• REAL :: Offset = 0.1, Length = 10.0, tolerance = 1.E-7
• CHARACTER(LEN=2) :: State1 = "MI", State2 = "MN"
• INTEGER, PARAMETER :: Quantity = 10, Amount = 435,
Period = 3
Introduction to Computer Programming 45
The Assignment Statement
• The assignment statement has the following
form:
variable = expression
Example
INTEGER :: Total, Amount, Unit
Unit = 5
Amount = 100
Total = Unit * Amount
Introduction to Computer Programming 46
Mixed-Mode Arithmetic
• You can combine integer and real quantities in
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
• In most cases, mixed-mode expressions are
considered bad programming
• The following example shows why:
1.0/4 → 1.0/4.0 → 0.25
3.0 + 8/5 → 3.0 + 1 → 4.0
3 + 8.0/5 → 3 + 8.0/5.0 → 3 + 1.6 → 3.0 + 1.6 → 4.6
Introduction to Computer Programming 47
Priority in Fortran Expressions
• Arithmetic expressions are evaluated according to
the following Priority Rules:
• All exponentiations are performed first, consecutively
from right to left.
1. All multiplications and divisions are performed
next, in the order in which they appear, from left to
right.
2. The additions and subtractions are performed last,
in the order in which they appear from left to right.
Examples
2 ** 3 ** 2 = 2 ** 9 = 512
10 – 8 – 2 = 2 – 2 = 0
10/5 * 2 = 2 * 2 = 4
2 + 4/2 = 2 + 2 = 4
2 + 4 ** 2 / 2 = 2 + 16 / 2 = 2 + 8 = 10
Introduction to Computer Programming 48
Priority in Fortran Expressions
(cont.)
• The standard order of evaluation can be modified by
using parentheses to enclose sub-expressions within
an expression
Example
(5 * (11 – 5) **2) * 4 + 9
-> (5 * 6 ** 2) * 4 + 9
-> (5 * 36) * 4 + 9
-> 180 * 4 + 9
-> 720 + 9
-> 729
Introduction to Computer Programming 49
Fortran Intrinsic Functions
• Fortran provides many of the common mathematical
operations and functions.
• For example, the square root of a real number can be
taken by:
SQRT(argument)
where argument is a real-valued constant, variable or expression.
Correct Incorrect
SQRT(7.0) SQRT(7)
Introduction to Computer Programming 50
Some of the Common Fortran Intrinsic
Functions
Function Description Argument Value Type
Type
ABS(x) Absolute value of x Integer or Same as
real argument
COS(x) Cosine of x radians Real Real
EXP(x) Exponential function Real Real
INT(x) Integer part of x Real Integer
FLOOR(x) Greatest integer x Real Integer
FRACTION(x) Fractional part of x Real Real
LOG(x) Natural logarithm of x Real Real
MAX(x1,…,xn) Maximum of (x1,…,xn) Integer or Same as
real argument
MIN(x1,…,xn) Minimum of (x1,…,xn) Integer or Same as
real argument
Introduction to Computer Programming 51
Some of the Common Fortran Intrinsic
Functions
Function Description Argument Value Type
Type
MOD(x,y) x mod y; x – INT(x/y)*y Integer or Same as
real argument
NINT(x) x rounded to nearest integer Real Integer
REAL(x) Conversion of x to real type Integer Real
SIN(x) Sine of x radians Real Real
SQRT(x) Square root of x Real Real
TAN(x) Tangent of x radians Real Real
Introduction to Computer Programming 52
Simple Input/Output
• There are some important rules governing how input
works:
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.
Introduction to Computer Programming 53
Listed-Directed Input: The
READ Statement
• List-directed input is carried out with the
Fortran READ statements.
• The READ statement can read input values
into a set of variables from the keyboard.
• The READ statement has the following forms:
READ(*,*) var1, var2, ..., varn
READ(*,*)
Introduction to Computer Programming 54
Listed-Directed Output: The
WRITE Statement
• Listed-directed output is carried with the
Fortran WRITE statement.
• The WRITE statement can display the results
of a set of expressions and character strings.
• In general, WRITE displays the output on the
screen.
• he WRITE statement has the following forms:
WRITE(*,*) exp1, exp2, ..., expn
WRITE(*,*)
Introduction to Computer Programming 55
Program Flow
• The rule is very simple:
1. The computer starts executing your program at
the first executable statement (after having
processed all type declarations).
2. It then executes each line of executable code in
the order that it appears in your program.
3. Execution continues until the computer
encounters a STOP or an END statement.
4. Order of statement execution can be changed,
which will be the subject of the next lesson.
Introduction to Computer Programming 59