ENGR-25_Lec-09_Programming-1_Program

advertisement
Engr/Math/Physics 25
Chp4 MATLAB
Programming-1
Bruce Mayer, PE
Registered Electrical & Mechanical Engineer
BMayer@ChabotCollege.edu
Engineering/Math/Physics 25: Computational Methods
1
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Learning Goals
 Write MATLAB Programs That can
MAKE “Logical” Decisions that Affect
Program Output
 Write Programs that Employ
LOOPing Processes
• For → No. Loops know a priori
• while → Loop Terminates based on
Logic Criteria
 Use the MATLAB DeBugger to
Correct Errors (time permitting)
Engineering/Math/Physics 25: Computational Methods
2
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
What’s an “Algorithm”
 A postage stamp
issued by the USSR
in 1983 to
commemorate the
1200th anniversary
of Muhammad
al-Khowarizmi,
after whom
algorithms are
named.
Engineering/Math/Physics 25: Computational Methods
3
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Algorithm Defined
 ALGORITHM  an ORDERED SEQUENCE of
PRECISELY defined instructions that
performs some task in a finite amount of time.
• ORDERED means that the instructions can be
NUMBERED, but an algorithm must have the
ability to ALTER the order of its instructions using a
CONTROL structure.
 There are three categories of algorithmic
operations → Next Slide:
Engineering/Math/Physics 25: Computational Methods
4
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Algorithmic Operations
1. SEQUENTIAL OPERATIONS →
Instructions executed in order
2. CONDITIONAL OPERATIONS →
Control structures that first ask a question to
be answered with a true/false response and
then select the next instruction based on
the answer
3. ITERATIVE OPERATIONS (LOOPS):
Control structures that repeat the execution
of a block of instructions
Engineering/Math/Physics 25: Computational Methods
5
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Structured Programming

STRUCTURED PROGRAMMING 
A technique for organizing and coding
computer programs in which a hierarchy of
modules is used, each having a single
entry and a single exit point, and in which
control is passed downward through the
structure withOUT UNconditional branches
to higher levels of the structure. Three types
of control flow are used: (1) sequential, (2)
test, and (3) iteration.
Engineering/Math/Physics 25: Computational Methods
6
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Structured Program Advantages
1. Structured programs are easier to write
because the programmer can study the
overall problem first and then deal with the
details later.
2. Modules (functions) written for one
application can be used for other applications
(this is called reusable code).
3. Structured programs are easier to debug
because each module is designed to
perform just one task and thus it can be
tested separately from the other modules.
Engineering/Math/Physics 25: Computational Methods
7
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Structured Program Advantages
4. Structured programming is effective in a
teamwork environment because several
people can work on a common program,
each person developing one or more
modules.
5. Structured programs are easier to
understand and modify, especially if
meaningful names are chosen for the
modules and if the documentation clearly
identifies the module’s task.
Engineering/Math/Physics 25: Computational Methods
8
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Developing Computer Solns
1. State the problem concisely
•
Use Math Eqns/Relns Whenever possible
2. Specify the data to be used by the program.
This is the “input.”
•
In physical Problems These are typically
–
–
–
–
Boundary Conditions
Initial Conditions
Constraints
Parameters
3. Specify the information to be generated by
the program. This is the “output.”
Engineering/Math/Physics 25: Computational Methods
9
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Developing Computer Solns cont
4. Work through the solution steps by hand or
with a calculator;
•
•
Use a simpler set of data if necessary
Test for EXTREME cases with
Input or Output = ±∞, 0, ±1
5. Write and Run the program
•
Correct Compile/Execution Time Errors
•
•
Missing Comma or Parens, MisTyped Var names, etc.
Correct RunTime Errors
•
e.g., NaN’s, inf’s, Divide-by-Zero, Complex
Numbers, etc.
Engineering/Math/Physics 25: Computational Methods
10
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Developing Computer Solns cont
6. Check the output of the program with your
hand solution(s)
7. Run the program with your input data and
perform a reality check on the output.
•
Output MUST NOT Violate the Laws of Physics;
e.g., in Statics (ENGR36)
– a CABLE canNOT support NEGATIVE Tension (you
can’t PUSH something with a ROPE)
– Objects canNOT have NEGATIVE Weight or Mass (at
least not until we figure out AntiGravity methods)
• In ENGR43 Physical Resistors, Capacitors, and
Inductors can NOT have NEGATIVE Values
Engineering/Math/Physics 25: Computational Methods
11
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Developing Computer Solns cont
8. If you will use the
program as a
general tool in the
future, test it by
running it for a
range of reasonable
data values;
•
Perform a Reality
Check on the results
Engineering/Math/Physics 25: Computational Methods
12
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Effective Documentation
1. Proper selection of variable names to reflect
the quantities they represent
•
Use DESCRIPTIVE and/or LONG names
2. Use of comments within the program
•
Also helps CLARIFY the WRITING of the Code
3. Use of structure charts
•
Like an ORG Chart for
your Software Program
– Structure charts show how
variables pass between
modules in a computer
program.
Engineering/Math/Physics 25: Computational Methods
13
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Anatomy of a Structure Chart Module
the called module
Engineering/Math/Physics 25: Computational Methods
14
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Example: Pizza Pricing Problem
 Write a
program to
find the UNIT
price for a
given pizza.
The size of
the pizza will
be provided in
inches. The
result must be
cost/inch2
Engineering/Math/Physics 25: Computational Methods
15
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Effective Documentation cont
4. Use of flowcharts
•
Each flowchart has one starting point and one or
more ending points that are drawn with a rounded
rectangle or oval.
– Steps, actions, or tasks are drawn with rectangles. It
helps to use verbs in describing the steps.
– Decisions are drawn with diamonds with labels at the
exits. The arrows show the order the steps are taken.
•
The shapes in the flowchart are often numbered
to make it easier to refer to them
•
Drawing a flowchart of a software component
makes the flow of control easier to understand
Engineering/Math/Physics 25: Computational Methods
16
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
FlowCharting
Example
 Basic House Painting
• Note the Cascade of
Decision-Diamonds
Engineering/Math/Physics 25: Computational Methods
17
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Effective Documentation cont
5. A verbal description of the program,
often in pseudocode.
•
Generic way of describing
an algorithm, without use
of any specific
programming language
•
Helps programmers to
PLAN an algorithm
Not an actual programming
Language, but may borrow
syntax from popular programming languages
Styles vary
•
•
Engineering/Math/Physics 25: Computational Methods
18
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
PseudoCode Example
 Example Problem: Calculate the bill when
someone buys a specific no. of some item:
 PseudoCode:
• PROMPT for number of items being purchased
• READ number of items being purchased
• PROMPT for price per item
• READ price per item
• CALCULATE subtotal
• CALCULATE tax
• CALCULATE total
• DISPLAY total
Engineering/Math/Physics 25: Computational Methods
19
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
PsuedoCode: Common Terms
 To Describe input, output, computations,
etc., the following terms are often used:
• Input: INPUT, READ, GET
• Output: PRINT, DISPLAY, SHOW
• Compute: COMPUTE, CALCULATE, DETERMINE
• Initialize: SET, INIT
• Add one: INCREMENT,
BUMP, STEP
• Decisions: TEST,
IF/THEN/ELSE,
WHILE/DO
Engineering/Math/Physics 25: Computational Methods
20
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
PsuedoCode Algorithms
 Ensure that the the task is
completely specified
 Issues to Consider
• What data is known before the program runs?
• What data must be input by the user?
• What computations will be
performed on the data?
• What data will be output
(displayed) to the user?
Engineering/Math/Physics 25: Computational Methods
21
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
ax  bx  c  0
2
Solve
Quadratic
Equation
 PsuedoCode
1. Get coeffs a, b, & c
2. Let d = b2 − 4ac
3. If d < 0 print 'no real solutions'
and go to step 5
4. Let X1 = (−b + SQRT(d))/(2a)
5. Let X2 = (−b − SQRT(d))/(2a)
6. Print X1 and X2
7. Stop
Engineering/Math/Physics 25: Computational Methods
22
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
PsuedoCode Example

Real World Problem:
•

Known Values
•

Child Age
Calculations
•

Pay Rate = 75 ¢/year
Inputs
•

Calculate the allowance for two children,
based upon 75¢ per year-of-age
Allowance = Age x Rate
Outputs
•
Allowances for each child
Engineering/Math/Physics 25: Computational Methods
23
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
PsuedoCode Example cont

Careful PseudoCode Algorithm:
•
•
•
•
•
PROMPT for Age of Child1
READ Age of Child1
PROMPT for Age of Child2
READ Age of Child2
CALCULATE
– Allowance for Child1 = [Age of Child1] x Rate
•
CALCULATE
– Allowance for Child2 = [Age of Child2] x Rate
•
•
DISPLAY Allowance for Child1
DISPLAY Allowance for Child2
Engineering/Math/Physics 25: Computational Methods
24
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Program Design - FlowChart
 Flowchart  a graphical representation of
algorithms
• Rectangle is used for calculations
• Parallelogram is used for input and output
• Circle is used as connector
• Diamond is used as decision
• Symbols are connected by arrows to represent the
order of the operations;
i.e., the direction of
program flow
Engineering/Math/Physics 25: Computational Methods
25
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
FlowChart Symbols – Calc’s
 Calculations (e.g.
arithmetic
expressions) are
shown in rectangles
• Example:
Total = Cost + Tax
• Example
Num = Num + 1
– add one to the current
value of Num and make
that the new value of
Num
Num = Num + 1
Total = Cost + Tax
Engineering/Math/Physics 25: Computational Methods
26
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
FlowChart Symbols – In/Out Put
 Data input and output are
shown in parallelograms
 Input  a read operation of
data from a peripheral device
to memory
READ Num
• e.g., a user typing in data
at a keyboard
 Output  a write operation of
data to a peripheral device from
memory
WRITE Num
• e.g., data displayed to the monitor
Engineering/Math/Physics 25: Computational Methods
27
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
FlowChart Symbols – Decisions
 Decisions are shown within
Diamonds and specify a
condition to be tested
 Based on the condition being
TRUE or FALSE, the next
operation will be determined
 A decision is composed of :
Gross > 50000
True
Rate = 0.28
Rate = 0.31
• A condition
• An operation to be done if
condition is TRUE
• Possibly an operation to be done
if condition is FALSE
Engineering/Math/Physics 25: Computational Methods
28
False
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
FlowChart Symbols – Start/End
 Every algorithm starts
somewhere and terminates
somewhere
 Every flowchart must have
one start symbol and
one end symbol
 Start and Stop symbols are ovals
• A start symbol denotes the start of
the algorithm
start
input num
square = num x num
print square
stop
• An end symbol indicates the
algorithm has terminated
Engineering/Math/Physics 25: Computational Methods
29
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
start
FlowChart Example
prompt Age1
input Age1
 Sequential-FlowChart for the
Previous Pseudocode Algorithm:
prompt Age2
input Age2
Allow1 = Age1 x Rate
Allow2 = Age2 x Rate
Print Allow1
•
•
•
•
•
PROMPT Age of Child1
READ for Age of Child1
PROMPT Age of Child2
READ for Age of Child2
CALCULATE
– Allowance for Child1 = Age of Child1 x Rate
• CALCULATE
– Allowance for Child2 = Age of Child2 x Rate
Print Allow2
stop
• DISPLAY Allowance for Child1
• DISPLAY Allowance for Child2
Engineering/Math/Physics 25: Computational Methods
30
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Common FlowChart Symbols
Common Flowchart Symbols
Terminator. Shows the starting and ending points of the program. A terminator has
flowlines in only one direction, either in (a stop node) or out (a start node).
Data Input or Output. Allows the user to inputdata and results to be displayed.
Processing. Indicates an operation performed by the computer, such as a variable
assignment or mathematical operation.
Decision. The diamond indicates a decision structure. A diamond always has two
flowlines out. One flowlineout is labeled the “yes” branch and the other is labeled the
“no” branch.
Predefined Process. One statement denotes a group of previously defined statements.
For instance, “Calculate m!” indicates that the program executes the necessary commands
to compute m factorial.
Connector. Connectors avoid crossing flowlines, making the flowchart easier to read.
Connectors indicate where flowlines are connected. Connectors come in pairs, one with
a flowline in and the other with a flowline out.
Off-page connector. Even fairly small programs can have flowcharts that extend several
pages. The off-page connector indicates the continuation of the flowchart on another
page. Just like connectors, off-page connectors come in pairs.
Flowline. Flowlines connect the flowchart symbols and show the sequence of
operations during the program execution.
Engineering/Math/Physics 25: Computational Methods
31
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Top-Down Dsgn: Structure Chrt
 As we Have Seen a FlowChart:
• Details exactly HOW a program will do
each task
 In contrast, the next design tool, the
Structure Chart:
• Shows only WHAT tasks your program will
do (not HOW it will complete them)
Engineering/Math/Physics 25: Computational Methods
32
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Structure Chart
 Structure charts are Hierarchical
diagrams → A form of an “Org Chart”
• They diagram the OverAll program
(organization) Structure
• They show the Relationship between all
the Tasks (workers) in the program
• They indicate which Data (Information) is
shared by the tasks (workers)
Engineering/Math/Physics 25: Computational Methods
33
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Creating Structure Charts
 A large program design is
first broken into tasks
Task
 Tasks are repeatedly divided
into even smaller subtasks
SubTask1
• Rectangles are used to represent
tasks/subtasks within the program
• Lines are used to hierarchically
connect the tasks/subtasks
– Subtasks are diagrammed below
the task that they are part of
Engineering/Math/Physics 25: Computational Methods
34
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
SubTask2
Structure Charts – Data Flow
 Passing of data between
tasks is shown by arrows
going up from or down
to the task’s rectangle
Task
Data1
SubTask1
Data1
SubTask2
• An upward arrow indicates that the data value has
been set inside the task and is being passed out
for use by other tasks
• A downward arrow indicates a data value
previously set in some other task is now being
passed into this task
• Data may also be passed both into a task
(downward arrow), modified, and passed
back out again (upward arrow).
Engineering/Math/Physics 25: Computational Methods
35
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Sample Structure Chart
 Given a generic program that reads some
data from the user, runs some calculations
using that data, and displays results to the
user, the structure chart could look like this:
main
Data
Get_Input
Data
Process_Data
Engineering/Math/Physics 25: Computational Methods
36
Result
Result
Display_Results
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Structure Chart: Sequential
Program
 Using our previous sequential program
design example (calculate the two
childrens’ allowances, based upon 75¢ per
year-age), the structure chart might be:
main
Age1,
Age2
Get_Ages
Age1,
Age2
Calculate_Allowances
Engineering/Math/Physics 25: Computational Methods
37
Allow1,
Allow2
Allow1,
Allow2
Display_Allowances
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Summary – Structure Charting
 Put the name of the program in a
rectangle root of an upside-down tree.
 Determine the main subtasks that
must be performed by the program to
solve the problem.
• Put main subtasks in
rectangles below the
root, and draw a
connecting line from
the root to each subtask.
Engineering/Math/Physics 25: Computational Methods
38
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Summary – Structure Charting
 Examine each subtask individually,
and break them down into even
smaller tasks
• Put subtasks in rectangles below the task
that they are part of, and draw a
connecting line from task to subtask.
 Repeat until the BOTTOM TASKS of
the tree are VERY SIMPLE to complete
Engineering/Math/Physics 25: Computational Methods
39
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
All Done for Today
LBL
Org Chart
 In Orgs or SW-Programs →
Form FOLLOWS Function
Engineering/Math/Physics 25: Computational Methods
40
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Engr/Math/Physics 25
Appendix
f x   2 x  7 x  9 x  6
3
2
Bruce Mayer, PE
Licensed Electrical & Mechanical Engineer
BMayer@ChabotCollege.edu
Engineering/Math/Physics 25: Computational Methods
41
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Yet More Org Charts
Engineering/Math/Physics 25: Computational Methods
42
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
CIA Org Chart (not secret)
Engineering/Math/Physics 25: Computational Methods
43
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Engineering/Math/Physics 25: Computational Methods
44
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Engineering/Math/Physics 25: Computational Methods
45
Bruce Mayer, PE
BMayer@ChabotCollege.edu • ENGR-25_Programming-1.ppt
Download