720 likes | 845 Views
Week 2. Organizational mattersFortran 90 (subset F): BasicsExample programs in detail. Top-down programming. 4 basic stepsSpecify the problem clearlyAnalyse the problem and break it down into its fundamental elementsCode the program according to the plan developed at step 2Test the program exh
E N D
2. Week 2 Organizational matters
Fortran 90 (subset F): Basics
Example programs in detail
3. Top-down programming 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
4. Program = Data Types + Algorithms Data types: what you work on
Algorithms: what you do with them
5. Structure of a program(in Fortran 90) Heading (program, module, etc.)
specification part
execution part
subprogram part
end program statement
6. Data Types Five basic types:
integer
real
complex
character
logical
Data types of ‘container’ classes
7. Integers a whole number (positive, negative or zero)
no decimal point
Examples0123-23456+123789
8. Integers 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.)
9. Reals Numbers with decimal fractions
There has to be decimal point
Examples1.23456-0.0019875678.
Another representation:1.952e30.1952e4123.456e-8
10. Reals 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
11. Character Sequence of symbols from the Fortran character set
Enclosed between double quotes
Examples"This is a string""I do, I don't""1234abc345"
12. Character strings 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)
13. Logical Can take only two values:
.TRUE.
.FALSE.
14. Complex 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 + i b 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.
15. Identifiers 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
16. Identifiers ExamplesCurrentDecay_Ratepressurean_identifier_with_a_long_namethe_best_program
17. Constants 10293845 is an integer constant
12.3456 is a real constant
"What a nice day!" is a character constant
18. Variables 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
19. Variables
20. Declarations of Variables
21. implicit none
22. Variable initialization
23. Named constants
24. Arithmetic operations Variables and constants can be processed by using operations and functions appropriated to their types.
Operations
27. Arithmetic operator priorities Operator Priority
** High
* and / Medium
+ and - Low
Examples:
W=c/d*b
Total=2**3+5*2=18
W=x+z-y
31. Library functions 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
32. Assignment statement Form:variable = expression
Assigns the value of expression to variable
Assignment is not a statement of algebraic equality; it is a replacement statement
ExamplesDensity = 2000.0Volume = 3.2Mass = Density*VolumeWeightRatio = log(Mass/90.)
33. Programs need to communicate with users! Two kinds of I/O (for the moment!):
Formatted I/O
List-directed I/O
List-directed outputprint *, output-listwrite (unit=*, fmt=*) output-list
List-directed inputread *, input-listread (unit=*, fmt=*) input-list
34. List-directed I/O Examplesprint *, "Tell me your birthday"write (unit=*, fmt=*) a, b, c**2read *, day, month, year
35. Names & Declarations 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
36. Type Declarations 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
37. Type Declarations 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.
38. Type properties: Kind & Length 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
39. Type properties: Kind & length 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
40. Constants 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.
41. Constants 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 !)
42. 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.
43. Simple Input & Output 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
44. 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
45. NUMBER REPRESENTATION 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
46. NUMBER REPRESENTATION 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.
47. NUMBER REPRESENTATION 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
48. Mixed-mode assignment 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 !
49. Program style and design 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
50. Program style and design 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
51. Steps involved in Programming Requirement Specification: eliminate ambiguities. Clearly understand the problem
Analyze the problem : Understand the inputs, outputs and processes used for manipulating the data, formulas and constraints
Design: Write the algorithm (flowchart or pseudocode) to represent the solution
Testing and verification : Check the algorithm.
Implement the algorithm : Write a program
Testing and Verification: Check the program
Documentation
52. 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
53. How Computers Solve Problems 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
54. ALGORITHMS AND FLOWCHARTS A typical programming task can be 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
55. Algorithms (source : wikipedia) 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.
56. What is an Algorithm? 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.
57. Problem Solving 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
58. Expressing the Algorithms 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
59. Pseudo Code “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
60. Pseudocode 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.
61. 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.
62. Flowcharts 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
63. Flowcharts 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.
64. Flowcharting Shapes Every flowchart has to start with a TERMINAL shape containing the caption START and has to end with another TERMINAL shape containing the caption of END.
INPUT shape is used to indicate manual input or reading values from keyboard.
OUTPUT shape is used to indicate producing printed output to the user.
DISPLAY shape is used to indicate that a value is sent to the monitor.
65. Flowcharting Shapes PROCESS shape is used to represent assignments and manipulations of data such as arithmetic operations.
DECISION shape represents the comparison of two values. Alternating course of actions is followed depending on the result of the criteria.
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.
FLOWLINE symbol is used to show the direction of the program flow between other symbols.
66. Flowcharting Shapes
67. Flowchart Symbols
68. Example 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.
69. Pseudocode 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”
70. Algorithm 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
71. Example
72. Example 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)
73. Example 2 Algorithm
Step 1: Input Lft
Step 2: Lcm ? Lft x 30
Step 3: Print Lcm