Upload
tobit
View
63
Download
0
Embed Size (px)
DESCRIPTION
IPC144 Session 6 Problem Analysis and Program Design Continued. 1. Objectives To write pseudo code To convert Flowcharts into Pseudo code To perform walkthroughs on pseudo code To represent data files in flowcharts and pseudo code To represent arrays in flowcharts and pseudo code. 2. - PowerPoint PPT Presentation
Citation preview
1
IPC144Session 6
Problem Analysis and Program DesignContinued
2
Objectives
To write pseudo codeTo convert Flowcharts into Pseudo codeTo perform walkthroughs on pseudo codeTo represent data files in flowcharts and pseudo codeTo represent arrays in flowcharts and pseudo code
3
Pseudo code
Pseudo codePseudo code (pseudo = fake, code = computer language), a fake computer language (3GL)
Throughout these discussions we have been using the PDC to move from a high level, general analysis of a problem to a more specific solution
The IPO Chart gave us a brief description of the inputs, the outputs and a list of processes for transforming the inputs into the outputs
The Flowchart gave us, diagrammatically, the sequence or order in which processes and decisions are made to solve the problem
Some people are more comfortable with pseudo code, and may choose to design their algorithm directly in pseudo code.
In this course you are expected to be able to read and write both flowcharts and pseudo code.
4
Pseudo code, continued
Pseudo code, continuedPseudo code is a hybrid between the structured computer languages (C, Pascal, BASIC...) and English
The control structures we defined in Flowcharting are represented hereBecause pseudo code is not a real computer language and it has loose rules for implementation, it can be used to develop an algorithm for any structured computer language
From the pseudo code (after testing the algorithm) the program can be coded by translating the statements in pseudo code to statements in the programming language (C in our case).
5
Pseudo code, continued
Pseudo code, continuedThere is no real standard for pseudo code, however it must have the following characteristics:
Statements are written in simple EnglishEach instruction is written on a separate lineKeywords are used to consistently name the parts of control structuresIndentation is used to make parts of a control structure conspicuousEach set of instructions is written from top to bottom, with only one entry point and one exit point
6
Pseudo code, continued
Pseudo code, continuedAgain the three basic structures are represented:
simple sequencesimple decisioniteration
7
Pseudo code, continued
Simple sequence - Assigning Variables
This is where variables are manipulated within your algorithmThe New Webster's Computer Terms dictionary definition:A variable is a symbolic name representing a value that changes during the program's execution
Back to Secondary School algebra, remember these?
5 = 5x + 4y0 = 5(x + y) - 3x + 5
Solve for x and y.
x and y are the variables.
8
Pseudo code, continued
Simple sequence - Assigning Variables, continued
When creating a name for a variable, make it meaningfulDon't make it too long (you will end up with writer's ramp now and carpal tunnel syndrome later)
custName may be not as meaningful ascustomers_first_and_last_name but it is easier to write and probably conveys enough information about how the variable is being used. The other extreme cn is obviously meaningless.
Use your judgement. Ask yourself: If I had to re-read this in another year, would the variable name be meaningful?
9
Pseudo code, continued
Simple sequence - Assigning Variables, continued
There are two types of variable assignments:When you are initializing a variableAs a result of some processing
It will be considered BAD FORM not to initialize a variable before using it
Verbs used: INITIALIZESET
INITIALIZE counter to zeroSET recordSize to 500
10
Pseudo code, continued
Simple sequence - Assigning Variables, continued
As a result of processing:
Expect to use the symbol "="
totalPrice = basePrice + salesTax
You can use this form for initializing variables as well
counterA = 0counterB = 0recordSize = 500
The value on the right side of the “=“ is calculated (if necessary) and then placed into the variable that is on the left side of the “=“. You can have only one variable on the left of the “=“.
11
Pseudo code, continued
Simple sequence - Assigning Variables, continued
Pseudo code Flowchart
counterA = 0
SET recordSize to 500
counterA = 0
SET recordSizeto 500
12
Pseudo code, continued
Simple sequence - Input of Data
Verbs used: READGET
READ usually refers to data being read from a file
GET usually refers to data being entered by the user at a keyboard
READ address FROM customerFileGET newAddress
13
Pseudo code, continued
Simple sequence - Input of Data, continued
Flowchart Pseudo code
READ address FROM customerFile
GET newAddress
Read addressFROM
customerFile
Get newAddress
14
Pseudo code, continued
Simple sequence - Output of DataVerbs used: PRINT
WRITEOUTPUTDISPLAY
PRINT usually refers to data being sent to a printer
WRITE usually refers to data being sent to a file
OUTPUT and DISPLAY usually refer to data being sent to a monitor.
In pseudo code The output is not necessarily formatted (made to look pretty), so it is common to simply list each piece of information separated by commas.
E.g.DISPLAY count, average
15
Pseudo code, continued
Simple sequence - Output of Data, continuedExample:
PRINT "Program Completed"WRITE newAddress TO customerFileOUTPUT name, address, postalCodeDISPLAY "End of Data Reached"
Note that any phrase that is to be output EXACTLY as written is enclosed in quotes
This helps to differentiate between a literal string and a variable name.
E.g.
average = sum / countDISPLAY The average is average over a range of count values
Should be written as:DISPLAY “The average is”, average, “over a range of ” , count, “values”
16
Pseudo code, continued
Simple sequence - Output of Data, continued
Flowchart Pseudo code
WRITE address TO customerFile
DISPLAY newAddress
Write addressTO
customerFile
Display newAddress
17
Pseudo code, continued
Simple sequence - Computation
Some verbs used: ADDCOMPUTECALCULATEMULTIPLYDIVIDESUBTRACT
ADD 1 TO counterCOMPUTE tax = price x 0.15degreesC = (degreesF - 32) x (5/9)
18
Pseudo code, continued
Simple sequence - Computation, continued
Flowchart Pseudo code
ADD 1 TO counter
degreesC = (degreesF - 32) × (5/9)
Add 1 to counter
degreesC =(degreesF - 32)
x (5/9)
19
Pseudo code, continued
Simple sequence - Module Call
Verbs Used: CALL
CALL myModule
CALL yourModule(myvar)
CALL theirModule(yourVar, myVar, someVar)
20
Pseudo code, continued
Simple sequence - Module Call
Flowchart Pseudo code
CALL dspMenu
CALL func(a, b, c)
dspMenu
func(a, b, c)
21
Pseudo code, continued
Selection - Simple DecisionThe basic form looks like:
IF condition THENstatement(s)
ELSEstatement(s)
ENDIF
If the condition is TRUE, then the statements immediately following the THEN keyword are executed, until the ELSE clause. At which point the program resumes after the ENDIF keyword
If the condition is FALSE, then the statements immediately following the ELSE keyword are executed
Note the indentation that is being usedMakes it easier to see the components of the selectionProvides for readability
22
Pseudo code, continued
Selection - Simple Decision, continued
Flowchart Pseudo code
IF a > b THENc = e + f
ELSEc = t x q
END IF
a > b c = e + f
c = t x q
TRUE
FALSE
23
Pseudo code, continued
Selection - Simple Decision, continued
Flowchart Pseudo code
IF condition THENStatementAStatementBStatementC
ELSEStatementDStatementE
END IF
If condition StatementAStatementDTRUEFALSE
StatementB
StatementC
StatementE
24
Pseudo code, continued
Selection - Simple Decision, continued
An example of no indentation: with indentation:
IF a = b THEN IF a = b THENDISPLAY "A equals B" DISPLAY "A equals B"c = (23 - d) / 2 c = (23 - d) / 2lifeUniverseEverything = 42 lifeUniverseEverything = 42ELSE ELSEDISPLAY "A does not equal B" DISPLAY "A does not equal B"vogons = 1 vogons = 1earth = 0 earth = 0ENDIF ENDIF
25
Pseudo code, continued
Selection - Simple Decision, continued
What if you don't need an ELSE clause?
IF avg < 50 THENDISPLAY "Low average”
END IF
avg < 50DISPLAY
"Low Average"TRUE
FALSE
26
Pseudo code, continued
Selection - Multiway DecisionThe basic form looks like:
SWITCH (variable)CASE (option)
statement(s)CASE (option)
statement(s). . . CASE (option)
statement(s)DEFAULT
statement(s)ENDSWITCH
variable is what is being testedoption is the possible value that variable takes on, and represents the new path of logic.
27
Pseudo code, continued
Selection - Multiway Decision, continued
Flowchart Pseudo code
SWITCH (usrSel)CASE (A)
res = a + bCASE (S)
res = a - bCASE (M)
res = a * bCASE (D)
res = a / bDEFAULT
DISPLAY "Invalid option”ENDSWITCH
usrSel
res = a+ b res = a- b res = a* b res = a/ bDISPLAY"Invalidoption"
A S M D Default
28
Pseudo code, continued
Iteration - Pre-Test Loop
The basic form looks like:
DOWHILE conditionstatement(s)
ENDWHILE
29
Pseudo code, continued
Iteration - Pre-Test Loop, continued
Flowchart Pseudo codeDOWHILE i < 10
b = b x ci = i + 1
ENDWHILE
b = b x c
False
True
i < 10
i = i + 1
30
Pseudo code, continued
Iteration - Post-Test Loop
The basic form looks like:
DOstatement(s)
WHILE condition
31
Pseudo code, continued
Iteration - Post-Test Loop, continued
Flowchart Pseudo codeDO
b = b x ci = i + 1
WHILE i < 10
b = b x c
False
Truei < 10
i = i + 1
32
Pseudo code, continued
Converting Flowcharts to Pseudo codeUse the indentation that has been depicted for each of the structures.
The statements that follow IF, CASE, DO and DOWHILE are indented an additional level.
ELSE is at the same level as it's corresponding IF. The statements after the ELSE are indented to the same level as the statements in the IF side
ENDIF, ENDCASE, ENDWHILE and WHILE end the indentation for their structure, and a re aligned with their corresponding IF, CASE, DOWHILE and DO
33
Pseudo code, continued
Converting Flowcharts to Pseudo codeConvert the following flowchart into pseudo code:
hi = 101 resp ≠ “C”
Start
lo = 1
DISPLAY"Choose a number"
DISPLAY"I Guess", guess,
"is it Hi, Lo or Correct?"
resp = “N”
guess =(hi + lo) / 2
GET resp
resp = “L”
resp = “H”
hi = guess
lo = guess
A
A
B
B
C
C
Stop
DISPLAY"I found your number",
guess
TRUE
TRUE
TRUEFALSE
FALSE
FALSE
34
Pseudo code, continued
Converting Flowcharts to Pseudo code, continued
hi = 101lo = 1resp = “N”DISPLAY "Choose a number"DOWHILE resp ≠ “C” guess = (hi + lo) / 2 DISPLAY "I guess", guess, "is it Hi, Lo or Correct?" GET resp IF resp = “L” THEN hi = guess ELSE IF resp = “H” THEN lo = guess ENDIF ENDIFENDWHILEDISPLAY "I found your number: ", guess
35
Pseudo code Walkthroughs
What is the output of
num = 1var = 0DO
var = num + varDISPLAY varnum = num + 2
WHILE NUM <= 7
Note:
<=
means “less than or equal)
36
Pseudo code Walkthroughs
What is the output of
num = 1var = 0DO
var = num + varDISPLAY varnum = num + 2
WHILE num <= 7
14916
37
Pseudo code Walkthroughs
What is the output of
i = 5DOWHILE i > 0
j = if = 1DOWHILE j > 1
f = f x jj = j – 1
ENDWHILEDISPLAY fi = i – 1
ENDWHILEDISPLAY “Done”
38
Pseudo code Walkthroughs
What is the output of
i = 5DOWHILE i > 0
j = if = 1DOWHILE j > 1
f = f x jj = j – 1
ENDWHILEDISPLAY fi = i – 1
ENDWHILEDISPLAY “Done”
12024621Done
39
Data Files
Data FilesFrom Session1 we talked about Secondary Storage.
Secondary storage stores files in a hierarchy of directories.
There are two general types of data files:text filesbinary files
Binary files are not discussed in this course.
Text files contain data that is generally readable by people (the format might be difficult to understand).
40
Data Files, continued
Data Files, continuedThe contents and format of a data file will be specified by the program requirements.
A file contains recordsRecords contain fieldsField contain characters
The end of the data file is represented by an 'End Of File' marker, typically referred to as EOF.
The end of a record is represented by a 'Carriage Return' character, typically referred to as CR or EOR.
Fields are either fixed size (the same size for the same field for all records) or they are delimited (a special character that will not be found in the input data is chosen for this purpose and separates each field within the record.
41
Data Files, continued
Data Files, continuedRegardless of whether the data file has fixed size fields or delimited fields, all of the fields come in the same order.
For simplicity, this course assumes fixed size fields.
Field1 Field2 Field3 . . . Field n
Record1 2003-09-01 -1.00 refund 1345
Record2 2003-09-06 15.02 Belt 54588
Record3 2003-09-10 163.89 Shirt 45846
. . .
Record n 2003-12-24 -5.62 discount 3548
42
Data Files, continued
Data Files, continuedTypical operations that are performed on a Data File:
Open - tell the O/S that you wish to perform some actions on the data in the fileRead - read some data from the data fileRewind - return to beginning of fileWrite - write some data to the data fileClose - tell the O/S that you are finished with the data file
Open, Close and Rewind are represented as processes
Read and Write use the traditional Input/Output box. The fields that are read or written are in the same order in the I/O Box as in the data file.
A file pointer keeps track of where you are in the file.
43
Data Files, continued
Data Files, continuedFlowchart Pseudo code
OPEN file.datREAD a, b, c FROM file.datDISPLAY "Read", a, b, ca = b + cREWIND file.datWRITE a, b, c TO file.datCLOSE file.dat
open file.dat
close file.dat
DISPLAY"Read", a, b, c
READ a, b, cFROM file.dat
WRITE a,b ,cTO file.dat
a = b + c
REWIND file.dat
44
Data Files, continued
Data Files, continuedWhile reading from a data file, how do you know you have reached the End-of-File?
In your condition, refer to a test for EOF. For example,
not EOF file.dat EOF file.datTRUEFALSE
TRUE FALSE
45
Arrays
ArraysIn programming there are times when we need to work with lists of data such as a list of names or a list of data points from an experiment.
These lists can be stored in an Array.
The simplest explanation is to consider a single column from a spreadsheet:
46
Arrays
Arrays
47
Arrays
ArraysNote that the rows are numbered.
The same technique is used in computers.
The array can have any name, using the same techniques as selecting variable names.
Each element of the array is numbered.
The element number of the array follows the array name, enclosed in square brackets:
myList[0]myList[1]…myList[n]
** In C the first element of the array is number 0: myList[0]
48
Arrays
ArraysAn example that places a calculated value into the first 10 rows of an array:
i = 0
i < 10
Start
a[i] = 2 * i + 1
i = i + 1
Stop
TRUE
FALSE