Upload
osborn-benson
View
225
Download
5
Embed Size (px)
Citation preview
1
IPC144Session 4
Flowcharts
2
Objectives:By the end of this session, the student will be able to:List the three elements of the Structure TheoremIdentify the symbols used in flowchartsRecognize the flowchart symbols and their meaningConstruct the elements of the Structure Theorem using Flowcharts
3
Flowcharts
BackgroundThe third phase of the PDC is Develop Solution into an Algorithm. The points that were made are:
Computers cannot devise a plan or decide to actComputers can only do what they are told, exactly the way they are toldComputers do what you tell them to do, not what you want them to doAn algorithm is a set of precise instructions which describe the task to be performed and the order in which they are to be carried out
Flowcharting is a tool that helps develop a solution into an algorithm: A picture is worth a thousand words Uses only a limited number of symbols to define an algorithm of any
complexity
4
Flowcharts
FlowchartsThis is where the program starts to take shape.
The Structure Theorem states that it is possible to write any computer program by using only THREE basic control structures:simple sequenceselectioniteration
5
Flowcharts
Simple sequenceThe Simple Sequence represents the computer's ability to execute instructions in a step-by-step, sequential manner.
SelectionThe Selection represents the computer's ability to make a decision. By evaluating a condition, alternate execution paths are followed.
IterationIteration represents the computer's ability to repeat a series of instructions.
6
Simple Sequence
7
Flowcharting - Simple Sequence
Flow linesShows the direction of logic flow within the flowchart
Unless otherwise stated the symbols of a flowchart have one flow line entering it, and one flow line exiting it.
8
Flowcharting - Simple Sequence, continued
Terminator or Terminal InterruptUsed to show the beginning or end of an algorithmThere must be these two symbols (only one each)
Start
Stop
9
Flowcharting - Simple Sequence, continued
Terminator or Terminal Interrupt, continuedA simple flowchart that does nothing:
Start
Stop
10
Flowcharting - Simple Sequence, continued
Process BoxUsed to show a processing operationThe operation is described inside the box (i.e. a calculation)Does not show a decision, or the input or output of data
Perform aprocess
11
Flowcharting - Simple Sequence, continued
An ExamplePrepare for an exam:
Start
Stop
Reviewtexts
ReviewLectures
ReviewTests
ReviewLabs
12
Flowcharting - Simple Sequence, continued
Off-page / On-page ConnectorWhat happens when you run out of room on the page?A unique identifier is written inside the symbol so that they can be paired up when reading the flowchartLike the terminator, in that there is either one flow line entering it, OR one flow indicator exiting it.
A
Off-page
A
On-page
13
Flowcharting - Simple Sequence, continued
A three page example
Start
U
V
Y
Z
StopA
B
W
X
A
B
14
Flowcharting - Simple Sequence, continued
Input / Output OperationUsed to show the input of data, or the output of dataThe operation is described inside the boxDoes not show a decision, or any processing steps
Read valueA
15
Flowcharting - Simple Sequence, continued
Module Call BoxUsed to call or invoke another flowchart. Any variables in the current program that are required by the module are listed in parenthesis, each separated by a comma.
The new flowchart is executed, and when it completes (hits the Stop Terminator) the current flowchart resumes execution.
This is where the modularity of programming is represented
getData(a, b)
16
Flowcharting - Simple Sequence, continued
Flowcharting the ModuleAll of the rules that are being discussed for flowcharts applies to the modules.
Modules are flowcharts that are composed of Simple Sequence, Decisions and Iteration.
The START and STOP terminal interrupts have new meaning in this case.
The START terminal interrupt shows the name of the of the module and the parameters to be used (some or all may be modified by the module).
The STOP terminal interrupt shows the module is complete and execution control is being returned to the flowchart that invoked the module.
17
Flowcharting - Simple Sequence, continued
ParametersMuch more time will be spent working with parameters when we actually start programming in C.
Parameters are a means to pass values from a flowchart to a module.
The names of the parameter variables in the module need not be the same name, however, they are positionally dependent.
myModule(a, varB, x, name)
myModule(a, b, c, d)
a avarB bx cname d
18
Flowcharting - Simple Sequence, continued
Parameters, continue
myModule(a, b, c, d)
myModule(a, varB, x, name)
Stop
Proce
ssing i
s pas
sed to
this
flowch
art
Control of execution is returned to the originating flowchart
19
Flowcharting - Simple Sequence, continued
ExampleDevelop a program to accept three numbers, add them together, then print their total and average. Write the flowchart
Input Process Output
val1 Read val1, val2, val3 total
val2 Calculate total average
val3 Calculate average
Display total
Display average
20
Flowcharting - Simple Sequence, continued
ExampleDevelop a program to accept three numbers, add them together, then print their total and average. Write the flowchart
Start
DISPLAY“Enter 1st Value”
total=val1 + val2 + val3
A
C
average=total / 3
PRINT total,average
Stop
GET val1
DISPLAY“Enter 1st Value”
A
DISPLAY“Enter 1st Value”
B
GET val2
DISPLAY“Enter 2nd Value”
B
DISPLAY“Enter 1st Value”
C
GET val3
DISPLAY“Enter 3rd Value”
21
Selection
22
Flowcharting - Selection
Selection
There will be references for the remainder of flowcharting to "conditions"
A condition is a logical expression that is either TRUE or it is FALSE
The condition is expressed as some form of a mathematical expression
Expressions:A > BSIN(theta) = COS(theta)recordValue = "end of records"
23
Flowcharting - Selection, continued
Simple selection boxUsed to show a change in the path of logic in the programThe condition being tested is written inside the diamond in a mathematical form using information available in the flowchart.Has 2 flow indicators exiting itThese flow lines MUST be labelled with the result of the decision (e.g. YES, NO, TRUE, FALSE...)
A > B + 5True
False
24
Flowcharting - Selection, continued
Multiway selection (Case Statement)Used to show a change in the path of logic in the programHas more than 2 flow lines exiting itUsed for EQUALITY decisions (each flow line is labelled with the value)
You may not place a range of values on the flow linesYou may not place conditions on the flow lines
One branch may be labelled 'Default' to represent the path to be taken when none of the conditions are met
varC
1
23
4
DefaultvarC
1 - 6
7 - 910 x > 5
Default
INVALID
25
Flowcharting - Selection, continued
CollectorUsed to collect the flow lines that were created from a decision box, and restore the logic of the program back to a single streamTHE PATHS FROM A DECISION MUST REJOIN IN A COLLECTOR
To be used with simple To be used with a multiwaydecision ONLY decision ONLY
26
Flowcharting - Selection, continued
Example - Simple Decision B
amount < 0DB =
DB + amount
CR =CR + amount
C
True
False
27
Flowcharting - Selection, continued
Example - Multiway Decision B
userOption
res = x * yres = x - y
C
res = x / yres = x + y
A
S M
D
28
Flowcharting - Selection, continued
ExampleWrite a program to help a local Elementary School's library with the overdue fines on books. The librarians don't wish to always charge students for overdue books, however sometimes the number of books that are overdue is too much. When this happens the librarians enter into the program the student's name, the name of the overdue book they borrowed, and the date it was signed out (the librarian reads these fields from the sign-out card). The colour of the card is also entered, as this indicates what the normal sign-out period is for that book. White cards are due back in 14 days, Blue cards in 7 days, Green cards the next day, and Orange cards in 28 days. The colour code of the card is entered as a single character into the program (W, B, G and O). When this information has been entered, the program determines by how much the book is overdue (based on the date the program is run) and the overdue charge, ($0.05 per day). A list is produced that will show the student's name, the name of the book, the number of days the book is overdue and the fine that is payable.
Create the IPO Chart and Flowchart (a module daysBetween(date, n) exists where the date parameter is the date to be compared to and the n parameter is the number of days between date and today that is calculated. For example if today is February 16th and the date parameter is February 5th, then the value of n would be set to 11 by the function.
If date is invalid or the date is in the future, n will be set to a negative number.
29
Flowcharting - Selection, continued
ExampleWrite a program to help a local Elementary School's library with the overdue fines on books. The librarians don't wish to always charge students for overdue books, however sometimes the number of books that are overdue is too much. When this happens the librarians enter into the program the student's name, the name of the overdue book they borrowed, and the date it was signed out (the librarian reads these fields from the sign-out card). The colour of the card is also entered, as this indicates what the normal sign-out period is for that book. White cards are due back in14 days, Blue cards in 7 days, Green cards the next day, and Orange cards in 28 days. The colour code of the card is entered as a single character into the program (W, B, G and O). When this information has been entered, the program determines by how much the book is overdue (based on the date the program is run) and the overdue charge, ($0.05 per day). A list is produced that will show the student's name, the name of the book, the number of days the book is overdue and the fine that is payable.
Create the IPO Chart and Flowchart (a module daysBetween(date, n) exists)
Input Process Output
studentNameRead studentName, bookName, signoutDate, colourCode studentName
bookName Calculate daysOverdue bookNamesignoutDate Calculate fine daysOverdue
colourCodeDisplay studentName, bookName, daysOverdue, fine fine
Main
getData calcFine showFine
30
Flowcharting - Selection, continued
Example
getData(studentName, bookName,signoutDate, colourCode)
calcFine(signoutDate, colourCode,daysOverdue, fine)
showFine(studentName, bookName,daysOverdue, fine)
Start
Stop
31
Flowcharting - Selection, continued
Example
DISPLAY“Enter student’s
name”
getData(sName, bName, date, cCode)
GET sName
DISPLAY “Enter book name”
GET bName
A
DISPLAY“Enter Sign-out Date”
GET date
DISPLAY “Enter card colour
code”
GET cCode
A
Stop
32
Flowcharting - Selection, continued
ExamplecalcFine(outDate, cCode,
overdue, fine)
daysBetween(outDate, n)
n < 0 DISPLAY “Invalid date entered”
fine = 0
B C
TRUE
FALSE
overdue = -1
Any errors in this module will result in overdue being less than 0 when the module returns
33
Flowcharting - Selection, continued
Example B C
cCode
overdue = n - 1
overdue = n - 7
overdue = n - 14
overdue = n - 28
DISPLAY “Invalid
colour code”
fine = overdue x 0.05
Stop
G BW
O Default
34
Flowcharting - Selection, continued
Example
Stop
showFine(sName, bName,overdue, fine)
overdue > 0
DISPLAY sName, bName, overdue,
fine
TRUE
FALSE
35
Flowcharting - Selection, continued
Alternate Example
You can replace the multiway decisionWith a set of nestedsimple decisions
colourCode='W'
ovrDue = n - 14
ovrDue = n - 7
ovrDue = n -1
ovrDue = n - 28
colourCode='B'
colourCode='G'
T
T
TF
F
F
colourCode=‘O'
T
DISPLAY“Invalid code”
F
36
Iteration
37
Flowcharting - Iteration
IterationIteration is also referred to as "looping"The goal of iteration is to repeat a sequence of steps until a certain condition has been metThe iteration is a special case of the decision structure already discussedThe sequence of steps in the loop may consist of simple sequences, decisions, loopsThere are two types of loops:
Pre-test Loop Post-test Loop
38
Flowcharting - Iteration
Pre-Test LoopThe condition that terminates the loop is tested before the loop is enteredIt is therefore possible to not execute any of the statements within the loop at all
Repeatedstatement(s)
False
True
ConditionalExpression
UpdateStatement
39
Flowcharting - Iteration
Post-Test LoopThe condition that terminates the loop is tested after the loop is enteredIt is therefore necessary to execute the sequence of statements at least once in order to reach the decision that terminates the loop.
Repeatedstatement(s)
TrueConditionalExpression
UpdateStatement
40
Flowcharting, continued
Integrity of a FlowchartIn this course will represent ALL logic necessary to represent a program – every last tedious step. There are no 'magic' shortcuts to writing the algorithm.
A flowchart is not just a collection of symbols and lines.
As a rule of thumb – lines in a flowchart do NOT cross each other
Think of a flowchart as a story in print:
Symbols (rectangles, parallelograms, circles, diamonds, lines...) -> letters of the alphabet. Individually they have no meaning, they are used to make words.
Simple Sequence / Decision / Iteration -> Words of the story. Just as you don’t mix letters arbitrarily into a word, you don’t throw symbols into a flowchart.
The flowchart is the story you are composing from START to STOP.
41
Flowcharting, continued
Nesting StructuresWhen combining structures, they must be nested.
Each structure (Simple Sequence, Simple Decision and Iteration) each have ONE entry point and ONE exit point. This is a rule that cannot be broken:
42
Flowcharting, continued
Nesting Structures, continuedEmbedding a loop within a decision
Loopneeded
Becomes...
43
Flowcharting, continued
Nesting Structures, continuedEmbedding a decision within a loop
Decisionneeded Becomes...
44
Flowcharting, continued
Nesting Structures, continuedThink of the nesting of your program, as a series of self-contained objects. One inside the other. There is no connection / interaction across layers. For example, this is illegal: