BIL106E
Introduction to Scientific & Engineering Computing – Week 2
Introduction to
Scientific & Engineering
Computing – Week 2
Week 2
Introduction to Scientific & Engineering Computing – Week 2
Organizational matters
Fortran 90 (subset F): Basics
Example programs in detail
Top-down programming
Introduction to Scientific & Engineering Computing – Week 2
4 basic steps
– Specify the problem clearly
– Analyse the problem and break it down into its
fundamental elements
– Code the program according to the plan developed
at step 2
– Test the program exhaustively, and repeat steps 2
and 3 as necessary until the program works in all
situations that you can envisage
Program = Data Types + Algorithms
Introduction to Scientific & Engineering Computing – Week 2
Datatypes:
what you work on
Algorithms:
what you do with them
Structure of a program
(in Fortran 90)
Introduction to Scientific & Engineering Computing – Week 2
Heading (program, module, etc.)
specification part
execution part
subprogram part
end program statement
Data Types
Introduction to Scientific & Engineering Computing – Week 2
Five basic types:
– integer
– real
– complex
– character
– logical
Data types of „container‟ classes
Integers
Introduction to Scientific & Engineering Computing – Week 2
a whole number (positive, negative or
zero)
no decimal point
Examples
0
123
-23456
+123789
Integers
Introduction to Scientific & Engineering Computing – Week 2
An Integer is a whole number (positive, negative, or zero)
and does not contain commas or a decimal point.
Examples for valid integer numbers are:
1
137
-1126
+17735
the followings are the examples for valid integer number:
8,675 (Commas are not allowed in numerical constants)
26.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.)
Reals
Introduction to Scientific & Engineering Computing – Week 2
Numbers with decimal fractions
There has to be decimal point
Examples
1.23456
-0.001987
5678.
Another representation:
1.952e3
0.1952e4
123.456e-8
Reals
Introduction to Scientific & Engineering Computing – Week 2
A real constant must contain a decimal point, but no commas
are allowed. Valid real constants are:
1.623
-0.03275
+55765
invalid real constants
15,627 (commas are not allowed in numerical constants.)
786 (Real constants must contain a decimal point.)
a real constant can be represented by an exponential. An
exponent written as the letter E with an integer constant
following. For example: 6527.4684 may also be written
as
6.5274684E3 which means 6.5274684X103
or similarly; 65.274684E2
0.65274684E4 and 65274.684E-1
Character
Introduction to Scientific & Engineering Computing – Week 2
Sequence of symbols from the
Fortran character set
Enclosed between double quotes
Examples
"This is a string"
"I do, I don't"
"1234abc345"
Character strings
Introduction to Scientific & Engineering Computing – Week 2
Character constants, also called strings, are sequences of
symbols from the ANSI standard character set for Fortran.
The number of a character constant between double quotes
is the length of the constant
For example:
”PDQ123-A” (Character constant of length 8)
”John Q. Doe” (Character constant of length 11)
Introduction to Scientific & Engineering Computing – Week 2
Logical
• .TRUE.
• .FALSE.
Can take only two values:
Complex
Introduction to Scientific & Engineering Computing – Week 2
A complex number is represented as a pair of real (i.e.,
floating point) numbers. The first component of the pair
represents the real part of the complex data object, and
the second represents the imaginary part. For example;
Z=a+ib Z = (a,b)
NOTE: Since you don‟t have enough background on complex
numbers, you are not responsible from complex numbers and
its related examples.
Identifiers
Introduction to Scientific & Engineering Computing – Week 2
Names used to identify programs,
constants, variables, etc.
Identifiers must Begin with a letter
This can be followed by up to 30
letters, digits, undescores
Be careful with the case: lower or
upper case letters
Identifiers
Introduction to Scientific & Engineering Computing – Week 2
Examples
Current
Decay_Rate
pressure
an_identifier_with_a_long_name
the_best_program
Constants
Introduction to Scientific & Engineering Computing – Week 2
10293845 is an integer constant
12.3456 is a real constant
"What a nice day!" is a character
constant
Variables
Introduction to Scientific & Engineering Computing – Week 2
Variables are value containers
Compiler associates with a variable a
memory location
Value of a variable at any time is the
value stored in the associated
memory location at that time
Introduction to Scientific & Engineering Computing – Week 2
1234567
Message
Variables
Hello World
23456
MEMORY
123.56
Payment
Declarations of Variables
Introduction to Scientific & Engineering Computing – Week 2
Form:
type-specifier :: list
Declares that the identifiers in the list have the
specified type
Type statements must appear in the specification
part of the program
Examples
integer :: number_years, counts, months
real :: Mass, Velocity, Acceleration
character (len=12) :: MyName, YourName
implicit none
Introduction to Scientific & Engineering Computing – Week 2
It should be placed at the beginning
of the specification part
You have to declare all variables you
will be using in the program!
Variable initialization
Introduction to Scientific & Engineering Computing – Week 2
All variables are initially undefined
Initialization in the declarations
Examples:
real :: W=1.2, z=5.678, mass=4.56
integer :: year=1998, count=0
Named constants
Introduction to Scientific & Engineering Computing – Week 2
Form:
type-specifier, parameter :: list
Examples
integer, parameter :: INITCOUNT = 30
real, parameter :: G = 9.81
It's a good idea to write named constants in upper
case
Arithmetic operations
Introduction to Scientific & Engineering Computing – Week 2
Variables and constants can be
processed by using operations and
functions appropriated to their types.
Operations
Operator Operation
Introduction to Scientific & Engineering Computing – Week 2
+ Addition, unary plus
- Subtraction, unary
minus
* Multiplication
/ division
** exponentiation
Operations
Introduction to Scientific & Engineering Computing – Week 2
Examples
To calculate B2 - 4AC
B**2 - 4*A*C
Types are important:
9/4 = 2
9.0/4.0 = 2.25
Mixed-mode expressions:
3 + 8.0/5 3 + 8.0/5.0 3 + 1.6 3.0 +
1.6 4.6
Arithmetic operator
priorities
Introduction to Scientific & Engineering Computing – Week 2
Operator Priority
** High
* and / Medium
+ and - Low
Examples:
W=c/d*b
Total=2**3+5*2=18
W=x+z-y
Priority rules
Introduction to Scientific & Engineering Computing – Week 2
All exponentiations are performed first;
consecutive exponentiations are performed
from right to left
All multiplications and divisions are
performed next; in the order in which they
appear from left to right
Additions and subtractions are performed
last, in the order in which they appear
from left to right
Some examples
Introduction to Scientific & Engineering Computing – Week 2
2 ** 3 ** 2 = 512
10/5 *2 = 2 * 2 = 4
To calculate 51/3
5.0**(1.0/3.0)
but not
5.0**(1/3) 5.0**0 1.0
What are the evaluation steps of the following equation?
Introduction to Scientific & Engineering Computing – Week 2
k = x**2*4 + y / 2.0 * z ** 2 – (x**y / y + 2 * t)
6 3
5 1
7 2
8 4
9
10
11
Library functions
Introduction to Scientific & Engineering Computing – Week 2
abs(x) Absolute value of x
cos(x) Cosine of x radians
exp(x) Exponential function
int(x) Integer part of x
sqrt(x) Square root of x
Assignment statement
Introduction to Scientific & Engineering Computing – Week 2
Form:
variable = expression
Assigns the value of expression to variable
Assignment is not a statement of algebraic
equality; it is a replacement statement
Examples
Density = 2000.0
Volume = 3.2
Mass = Density*Volume
WeightRatio = log(Mass/90.)
Programs need to
communicate with users!
Introduction to Scientific & Engineering Computing – Week 2
Two kinds of I/O (for the moment!):
– Formatted I/O
– List-directed I/O
List-directed output
print *, output-list
write (unit=*, fmt=*) output-list
List-directed input
read *, input-list
read (unit=*, fmt=*) input-list
List-directed I/O
Introduction to Scientific & Engineering Computing – Week 2
Examples
print *, "Tell me your birthday"
write (unit=*, fmt=*) a, b, c**2
read *, day, month, year
Names & Declarations
Introduction to Scientific & Engineering Computing – Week 2
A data object is a constant that never changes or a
variable that can change during program execution.
Data object may have names. For example, Average, X, Y,
Einstein, or Potential_Energy.
Names in a program must conform to 3 rules:
1) A name may contain up to 31 letters, digits, and underscore
characters
2) The first character of a name must be a letter
3) Imbedded blank characters are not permitted in a name
IMPORTANT: keywords such as program, write, and end are not
actually names
Type Declarations
Introduction to Scientific & Engineering Computing – Week 2
Every variable and named constant must appear in a type
declaration
The type of a Fortran variable determines the type of value that
may be assigned to that variable.
In every F program, the specification statement implicit none must
immediately follow the program statement
program Research
implicit none
.
.
.
end program Research
Type Declaration Form
Type name ::List of names
Consider the following example
Type Declarations
Introduction to Scientific & Engineering Computing – Week 2
implicit none
integer :: Counts, Loop_Index
real :: Current, Resistance, Voltage
Names defined as part of the F language, including keywords and
intrinsic function names (such as sin, tan, abs, etc.), must be
written in lower case. Names that you invent can use any
combination of upper and lower case, but each name must be
written consistently.
Type properties: Kind & Length
Introduction to Scientific & Engineering Computing – Week 2
Kind : A variable of any numerical type has a kind type
parameter, which designates a subtype or variant of the type.
– Each type has a default computer representation
– For each numerical data type, F defines a set of integers to be
used as kind type parameter values (i.e., the number 4 for real
representation, number 8 for the higher-precision variant)
Length : A variable of character data type has a string length
property.
– A character type declaration must specify string length
A type declaration appears in parentheses after the type name. If
no
kind parameter is specified, F selects the default computer
representa-
tion
Type name (Type properties) :: List of names
Type properties: Kind & length
Introduction to Scientific & Engineering Computing – Week 2
Other data attributes may be specified between the
type properties and the double colon.
Type name (Type properties), Attributes :: List
of names
Example:
integer, parameter :: ARRAY_SIZE=12, SL=20
character (Len=SL), save :: Element_Name
integer, dimension (ARRAY_SIZE) :: chart, list
Constants
Introduction to Scientific & Engineering Computing – Week 2
A constant in a program may have an explicit form, or it may be
represented by a name.
EXPLICIT CONSTANTS
A constant in a program has a fixed value during the execution of
the program. Consider the cases that:
1) A value may need to be changed before the program is executed
again.
2) A constant in a declaration, such as the size of an array or the
length of a character string, may need to be revised.
Therefore we prefer to use a named constant instead of an
explicit constant to prevent searching for all the appearances
of a certain constant within the program which is a tedious and
an error-prone task.
Constants
Introduction to Scientific & Engineering Computing – Week 2
The name of a constant looks like the name of a variable and
it must be listed in the type declaration
The keyword parameter designates a named constant
Houdini Principle: Don‟t use magic numbers
– use a named constant rather than a explicit constant
– give always explanations ( use !)
Declaration for a Named Constant
Declaration of a named constant is as follows:
Type name, parameter :: List of initializations
where each list item has the form
Name = Value definition
The value definition is an explicit constant.
Examples:
integer, parameter :: LENGTH=12
real, parameter :: PLANK=6.6260755e-34, PI=3.141593
real, parameter :: GRAVITY=9.807, AVAGADRO=6.0221367e23, &
twoPI=2.0*PI
integer, parameter :: A=20, HIGH=30, NEON=67
character (Len=2), parameter :: units=”Cm”
ATTENTION: Continuation line with ampersand symbol.
Simple Input & Output
Introduction to Scientific & Engineering Computing – Week 2
Read (unit = *, fmt = *) Input List
Write (unit = *, fmt = *) Output List
An asterisk as the unit in a read or write control list designates
the default input device (the keyboard) or the default output
device (The terminal screen)
An asterisk as the format designates list-directed formatting.
Input data values for on-line list-directed input are entered at
the computer keyboard in free form. Consecutive values must
be separated by blanks.
For example:
read (unit = *, fmt = *) Radii, I, Current, Top
can be entered as
9.75 10 15.32
765.3
Simple Input & Output
IMPORTANT: The items in an input list must be variable names.
write (unit = *, fmt = *) ” Please enter the diameter of a circle”
read (unit = *, fmt = *) Diameter
write (unit = *, fmt = *) ” Diameter = ”, Diameter, ”circumference =”, &
3.1416*Diameter, ”Area = ”, 3.1416*Diameter**2
NUMBER REPRESENTATION
Introduction to Scientific & Engineering Computing – Week 2
NUMERICAL PRESICION AND RANGE
There is an increasing demand for high precision
Computer hardware representation varies from 8-bit to 128 bit
word length
Precision requirements should be considered for both different
type of computer hardware and problem type we have.
For example: 9 decimal digits of numerical precision can be
satisfied by 1) Single-precision arithmetic if the computer word
length is 64 bits, 2) double-precision arithmetic if the word
length is 32 bits.
A Kind option provides flexible control of integer and real
precision and range.
– 1) Each data type has a default computer representation
– 2) The kind type parameter of a data object determines its
computer representation
NUMBER REPRESENTATION
Introduction to Scientific & Engineering Computing – Week 2
– 3) Each kind is designated by a different integer kind selector
value.
– 4) A kind value may be specified in the type declaration for a
variable or named constant.
A typical convention is that the kind selector value is the
number of bytes (e.g., 4 or 8) occupied by the computer
representation.
But it is recommended that these processor-dependent values
not be used as kind selectors because of the problems that
result when a program is moved to a different processor.
Therefore use named constants instead of explicit integer
constants
The intrinsic inquiry function selected_real_kind(P) returns
the kind value for a processor representation that supplies at
least P decimal digits of precision.
NUMBER REPRESENTATION
Introduction to Scientific & Engineering Computing – Week 2
Example: selected_real_kind(6) returns a processor kind value
that provides at least 6 decimal digits of precision
A numerical constant may be followed by an underscore and a kind
selector:
678_SHORT
12_LONG
3.141592_HIGH
The kind selector must be a named constant of integer type
EXAMPLES:
integer, parameter :: NORMAL = selected_int_kind(9), &
LOW = selected_real_kind(6), HIGH = selected_real_kind(15)
integer (kind = NORMAL) :: First, Second
Mixed-mode assignment
Introduction to Scientific & Engineering Computing – Week 2
Assume that,
b is a real variable whose value is 100.0, while c and d are
integers having the values 9 and 10, respectively.
a = b*c/d
result is 90.0
a = c/d*b
a gets 0 value.
This phenomenon is known as integer division
show program list_directed_input_example !
Program style and design
Introduction to Scientific & Engineering Computing – Week 2
A program must be correct, readable, and understandable. The
basic principles for developing a good program are as
follows:
1) Programs cannot be considered correct until they have been
validated using test data.
2) Programs should be well structured
• Use a top-down approach when developing a program for a complex
problem.
• Strive for simplicity and clarity
3) Each program unit should be documented
Include opening documentation
Use comments
Use meaningful identifiers
Label all output
4) A program should be formatted in a style that enhances its
readability
Program style and design
Introduction to Scientific & Engineering Computing – Week 2
5) Programs should be readable and understandable
• Do not use magic numbers
• Use comments to describe the purpose of a program and variables
6) Programs should be general and flexible
Steps involved in
Programming
Introduction to Scientific & Engineering Computing – Week 2
1. Requirement Specification: eliminate
ambiguities. Clearly understand the problem
2. Analyze the problem : Understand the inputs,
outputs and processes used for manipulating
the data, formulas and constraints
3. Design: Write the algorithm (flowchart or
pseudocode) to represent the solution
4. Testing and verification : Check the
algorithm.
5. Implement the algorithm : Write a program
6. Testing and Verification: Check the program
7. Documentation
Introduction to Scientific & Engineering Computing – Week 2
How People Solve Problems
• A Problem exists when what we have
(Data) is not the same as what we
want (information)
• People create a solution (called an
Algorithm) which manipulates Data
into Information
• People do this quickly and often in a
complex way
How Computers Solve
Problems
Introduction to Scientific & Engineering Computing – Week 2
• Computers also use Algorithms to
solve problems, and change data into
information
• Computers can only perform one
simple step at a time
• Complex “Human” Algorithms must be
broken down into simple step-by-step
instructions BEFORE they can be
translated into computer code
ALGORITHMS AND FLOWCHARTS
A typical programming task can be
Introduction to Scientific & Engineering Computing – Week 2
•
divided into two phases:
• Problem solving phase
• produce an ordered sequence of steps
that describe solution of problem
• this sequence of steps is called an
algorithm
• Implementation phase
• implement the program in some
programming language
Algorithms (source : wikipedia)
Introduction to Scientific & Engineering Computing – Week 2
• In mathematics, computing, linguistics and related
disciplines, an algorithm is a procedure (a finite set of
well-defined instructions) for accomplishing some task
which, given an initial state, will terminate in a defined
end-state.
• Algorithms are essential to the way computers process
information, because a computer program is essentially
an algorithm that tells the computer what specific steps
to perform (in what specific order) in order to carry out
a specified task, such as calculating employees‟
paychecks or printing students‟ report cards.
What is an Algorithm?
Introduction to Scientific & Engineering Computing – Week 2
• An algorithm is the plan for writing a
program.
• Steps required for solving a problem are
listed by using an algorithm tool.
• Algorithm tools make program solutions
more clear, more understandable, and
easier to remember.
• Algorithms are written according to rules
so that other programmers are also able
to read and understand the solution
easily.
Problem Solving
Introduction to Scientific & Engineering Computing – Week 2
• Problem Solving is the ability to
understand what you have, what you
want, and creating a set of
instructions to change what you have
into what you want
• Good Problem Solving Skills are based
on knowledge, experience and logic
• Good Programmers NEVER make
assumptions
Expressing the Algorithms
Introduction to Scientific & Engineering Computing – Week 2
• A “Standard” way of describing an
algorithm must exist if we expect our
solution to be understood by others
easily
• There are standards in programming:
• PSEUDOCODE
• FLOWCHARTS
• PROGRAMMING LANGUAGE
Pseudo Code
Introduction to Scientific & Engineering Computing – Week 2
• “Pseudo” means “pretend” or “false”
• Pseudo Code is pretend or false
computer code; generic English-like
terms that are somewhat like
computer code
• Pseudo Code is not as standardized as
flowcharts, and does not facilitate the
breaking down of problems as well as a
flowchart does
Pseudocode
Introduction to Scientific & Engineering Computing – Week 2
• Pseudocode is structured english that is used as
an alternative method to flowcharts for planning
structured programs.
• There are no general accepted standards for
pseudocodes.
• We will work with a form that has minimum number
of rules and is essentially language-independent.
• Pseudo-code instructions are written in English,
• they can be easily understood and reviewed by users.
• The only syntax rules to be concerned with
involve the LOOP and SELECTION structures.
• They must be used as CAPITALISED words.
Introduction to Scientific & Engineering Computing – Week 2
Pseudocode (wikipedia)
Pseudocode (derived from pseudo and code)
is a compact and informal high-level
description of a computer programming
algorithm that uses the structural
conventions of programming languages, but
omits detailed subroutines, variable
declarations or language-specific syntax.
The programming language is augmented
with natural language descriptions of the
details, where convenient.
Flowcharts
Introduction to Scientific & Engineering Computing – Week 2
• A Flowchart is a Visual
Representation of an algorithm
• A Flowchart uses easy-to-
understand symbols to represent
actions on data and the flow of data
• Flowcharts aid in breaking down a
problem into simple steps
Flowcharts
Introduction to Scientific & Engineering Computing – Week 2
• Flowcharts are graphical tools, containing
a set of shapes, each expressing a
different action in a sequence of
program execution.
• There are many different shapes that
are used for specific purposes, to avoid
complexity, in this course, only a limited
subset of these shapes will be shown and
used in applications.
Flowcharting Shapes
Introduction to Scientific & Engineering Computing – Week 2
• Every flowchart has to start with a TERMINAL shape Start
containing the caption START and has to end with another
End
TERMINAL shape containing the caption of END.
• INPUT shape is used to indicate manual input or reading Student Id
values from keyboard.
Student
• OUTPUT shape is used to indicate producing printed output Transcript
to the user.
• DISPLAY shape is used to indicate that a value is sent to the cgpa
monitor.
Flowcharting Shapes
Introduction to Scientific & Engineering Computing – Week 2
• PROCESS shape is used to represent assignments and
manipulations of data such as arithmetic operations. Num 3
• DECISION shape represents the comparison of two values.
Alternating course of actions is followed depending on the
result of the criteria. cgpa > 2.00
• CONNECTOR symbol is used to show the connections of two
pages, when your design occupies more then one page. Also
used to collect together flow lines of decision shape. A
• FLOWLINE symbol is used to show the direction of the
program flow between other symbols.
Flowcharting Shapes
Introduction to Scientific & Engineering Computing – Week 2
Conn
Process Display
ector
Output Terminal
Input
Decision Flow lines FOR
Flowchart Symbols
Introduction to Scientific & Engineering Computing – Week 2
Name Symbol Use in Flowchart
Oval Denotes the beginning or end of the program
Parallelogram Denotes an input operation
Rectangle Denotes a process to be carried out
e.g. addition, subtraction, division etc.
Diamond Denotes a decision (or branch) to be made.
The program should continue along one of
two routes. (e.g. IF/THEN/ELSE)
Hybrid Denotes an output operation
Flow line Denotes the direction of logic flow in the program
Example
Introduction to Scientific & Engineering Computing – Week 2
Example 1: Write an algorithm to
determine a student‟s final grade and
indicate whether it is passing or
failing. The final grade is calculated
as the average of four marks.
Pseudocode
Introduction to Scientific & Engineering Computing – Week 2
Pseudocode:
• Input a set of 4 marks
• Calculate their average by summing
and dividing by 4
• if average is below 50
Print “FAIL”
else
Print “PASS”
Algorithm
Introduction to Scientific & Engineering Computing – Week 2
• Detailed Algorithm
• Step 1: Input M1,M2,M3,M4
Step 2: GRADE
(M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
Example
Introduction to Scientific & Engineering Computing – Week 2
START Step 1: Input M1,M2,M3,M4
Step 2: GRADE (M1+M2+M3+M4)/4
Input Step 3: if (GRADE <50) then
M1,M2,M3,M4 Print “FAIL”
else
Print “PASS”
GRADE(M1+M2+M3+M4)/4
endif
N IS Y
GRADE<5
0
PRINT PRINT
“PASS” “FAIL”
STOP
Example
Introduction to Scientific & Engineering Computing – Week 2
• Write an algorithm and draw a
flowchart to convert the length in
feet to centimeter.
Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by
multiplying LFT with 30
• Print length in cm (LCM)
Example 2
Introduction to Scientific & Engineering Computing – Week 2
START
Algorithm Input
• Step 1: Input Lft
Lft
• Step 2: Lcm Lft x 30
Lcm Lft x 30
• Step 3: Print Lcm
Print
Lcm
STOP
Flowchart