Upload
irene-weaver
View
215
Download
1
Embed Size (px)
Citation preview
COIT29222-Structured Programming
Lecture Week 09 Reading: Textbook (4th Ed.), Chapters 2 & 3
Textbook (6th Ed.), Chapters 5 & 6 Study Guide Book 3, Module 1
This week, we will cover the following topics:Designing Well-structured Programs
Structured programTop-down designStructured designStructure chartFunction parameters
Pass by valuePass by reference
What is a well-structured program?
One whose meaning is easily understood
i.e. one that clearly reflects what the program does
i.e. provides a clear description of the steps involved in performing its task
For large and/or complex programs this sort of clarity requires organisation/structure
Organising the process of writing programs
Structured ProgrammingAn attempt to formalise the logic used in
developing a solution to a computer problem
A discipline the programmer imposes on him/herself independently of the programming language used to code the design
Apply a Structured Approach to
Producing a precise problem specification
Designing a solution to the problemIncludes testing
Against the specificationFor logical correctness
Coding the design in a programming languageIncludes documentation and code layout
Problem Analysis & Specification
Requirements of the specification – organised in terms of input-process-output model of data processing:
data input to the programprocessing required by the program information output from the
program With consideration for generalisation
Solve not only the specific problem at hand, but any reasonably closely related problem
Problem Analysis & Specification - Example
Formalise the specification:Jo is employed by Ted's TV Repairs. Jo is
charged out to customers at a flat charge of $32 to determine if a TV is repairable and a further $45 an hour to fix repairable TVs. In the month of June, Jo dealt with 57 TVs and booked 136 hours work. How much revenue did Jo generate for the company during the month of June?
Problem Analysis & Specification - Example
InputNumber of TVs looked at Number of hours worked
ProcessingCalculate Revenue generated as: (Number of TVs looked at * 32) +
(Number of hours worked * 45) Output
Revenue generated
Problem Analysis & Specification - Example
Generalisation rates at which Jo charged to customers will change over time:
charge to look at a TVhourly rate
become inputs to the system rather than fixed values within the system
Problem Analysis & Specification - Example
Generalisation revised input:Number of TVs looked at Number of hours workedCharge to look at a TVHourly rate
Generalisation not straightforwardweigh increased costs against probability
of occurrence of more general cases
Designing Problem Solutions
The technology of structured programming design is aimed at managing complexity.
Our approach to structured design is based on the production of an algorithm to solve the problem.An algorithm is a set of steps required to
solve a problem/perform a taskAlgorithms are independent of any
programming language
Top-down Design with Step-wise Refinement
Algorithm representing a problem solution is produced by:Describe problem solution as a set of
high-level sub-tasksProduce algorithms for high-level sub-
tasks in terms of simpler sub-tasks
Continue decomposing sub-tasks into simpler sub-tasks simple enough to be implemented in the statements of a programming language
Top-down Design with Step-wise Refinement
This process is known as top-down design since one proceeds from the top, abstract or “big picture” view down to the detail of the problem solution.
The solution is a hierarchical set of sub-tasks with each step down the hierarchy involving a greater refinement of detail.
Hierarchical systems are good at reducing complexity.
Top-down Design – Ted’s TV Repairs - Example
Problem solution as a set of high-level sub-tasks:
get the required input (INPUT)
calculate the generated revenue (PROCESS)
display the generated revenue (OUTPUT)
Ted’s TV Repairs – Algorithms for Sub-tasks
get the required input
prompt for and get the number of TVs looked at
prompt for and get the number of hours worked
prompt for and get the charge rate to look at a TV
prompt for and get the hourly rate for looking at a TV
Ted’s TV Repairs – Algorithms for Sub-tasks
calculate the generated revenue set GeneratedRevenue to
(TVsLookedAt * ChargeToLook) + (HoursWorked *HourlyRate)
display the generated revenuewrite "Generated revenue ==> "write GeneratedRevenuewrite NewLine
Ted’s TV Repairs – Algorithms for Sub-tasks
get the required inputwrite "Number of TVs looked at ==> "read TVsLookedAtwrite "Number of hours worked ==> "read HoursWorkedwrite "Charge rate to look at a TV ==> "read ChargeToLookwrite "Hourly rate for looking at a TV"read HourlyRate
Ted’s TV Repairs – main Algorithm
main algorithm get the required input ( INPUT )set GeneratedRevenue to ( PROCESS ) (TVsLookedAt * ChargeToLook) + (HoursWorked *HourlyRate)
write "Generated revenue ==> “ ( OUTPUT )write GeneratedRevenuewrite NewLine
Structured Designs
Devising a structured design to a computing problem involves:
Algorithm designin conjunction with
Data design For clarity of exposition we’ll discuss
algorithm design, then data design
Algorithm Design
2 concepts underpin our structured approach to algorithm design:Top-down design with step-wise
refinementSimple flow of control
Flow of control is governed by control structures
Control structures determine the order in which steps in an algorithm are executed
The 3 fundamental Control Structures
Sequence– Steps of an algorithm executed in
sequence - default caseSelection
– Selection of one of a number of execution paths based on a condition (if, if-else, switch)
Repetition– Repeated execution of one or more
steps while some condition holds true (while, do-while, for)
The 3 Fundamental Control Structures
These 3 control structures have 1 entry point and 1 exit point flow-of-control simplicity
Arbitrarily complex algorithms built by connecting control structures:
Control-structure stacking
Control-structure nesting
Sequence Control StructureBy default the flow of control in an
algorithm is sequential.The main algorithm of Ted’s TV Repairs is
built by stacking 5 sequence control structuresWith the exit point of each control
structure (statement) connected to the entry point of the next control structure (statement)
Data Design
2 aspects to data designData structure
The way in which data is organisedWhen the design coded into a
programming language the way data represented in memory
Data flowThe flow of data between the
various sub-tasks in a structured design
Data Flow
The sub-tasks in a program design communicate via dataData is said to flow between sub-tasks
Top-down, step-wise-refined approach to program design solution as a hierarchy of sub-tasksThe structure chart shows:
Hierarchical structure of the design
Data flow among subtasks
Structure Chart – Ted’s TV Repairs Example
main
get the required input
TVsLookedAt ChargeToLook HoursWorked HourlyRate
Sub-task InterfaceThe set of data items through which a sub-
task communicates with other sub-tasks in the design is called its interfaceIn a structure chart, the data items
labelling the arrow above a sub-task comprise its interface
Sub-task interfaces are the only means of communication between sub-tasks in a structured designThis restriction prohibits sub-task
communication via global data items
Data Item in an InterfaceInput data item
Data flows into the sub-task via this data itemLabels downward-pointing arrow in a structure
chartOutput data item
Data flows from the sub-task via this data item Labels upward-pointing arrow in a structure
chartInput/output data item
Data flows both into and from the sub-task via this data item Labels both upward- & downward-pointing
arrows in a structure chart
Algorithms with Interfaces - Ted’s TV Repairs-Example
get the required inputinput: ( no input data items )
write "Number of TVs looked at ==> "read TVsLookedAtwrite "Number of hours worked ==> "read HoursWorkedwrite "Charge rate to look at a TV ==> "read ChargeToLookwrite "Hourly rate for looking at a TV"read HourlyRate
output: TVsLookedAt, ChargeToLook, HoursWorked, HourlyRate
Data Structure
An integral part of the design of sub-task algorithms is the design of the data on which they operate.
Data design involves:Devising meaningful names
(identifiers) for data entities Associating various properties with
those names
Local Data Items
In this course, for each sub-task in a program design, data-item names and their associated properties will be kept in a local data items table
Local data items are data items which:are used in a sub-taskdo NOT appear in the sub-task
interface
Local Data Items – Ted’s TV Repairs
Main algorithmSince there is no interface, all the
data items used are local data items: GeneratedRevenue, TVsLookedAt, HourlyRate, ChargeToLook, HoursWorked
Get the required input algorithmThere are no local data items since all
the data items used appear in the output list of the sub-task interface
Local Data Items Table – Ted’s TV Repairs - main
Local Data Items Table - Properties
The properties associated with data items are the column names in the local data items table.Name: a meaningful name for the data itemType: the type of data that will be stored in
the data itemWe use type names in the data design that
are independent of any programming language:
integer, real, character, boolean, string and, for array types: array of integer, array of character etc.
Local Data Items Table - Properties
Range of values: specifies the possible range of values for the data itemRanges must be sufficiently large to allow
for extreme values of data itemsThe range for calculated values is
determined by performing the calculation using the appropriate extreme valuesGeneratedRevenue data item calculated
as: 3000.0 * 200.0 + 360.0 * 500.0 = 780000.0
Local Data Items Table - Properties
Initial value: the initial value of the data item, either:Read
Data item initially read from the keyboardCalculated
Data item initially the result of a computation
A value The program logic depends on the data
item having this initial value
Constant Data Items
Those data items whose value does not change after initialisation.
Assign a name to every distinct use of a literal value used in a program design.
We use symbolic names for constant values to:Improve design (thus program) clarityMake designs (thus programs) more
easily maintainable
Structured Programming
Is an organised approach to program design that increases the likelihood of producing clear, correct & efficient programs. This involves:Top-down design with step-wise
refinementProduces a solution to the problem at
hand as a hierarchy of sub-tasks Algorithm design limited to 3 types of
control structure
Structured ProgrammingLimited scope of data structures
Restricting communication between sub-tasks to the data in their interfaces Structured designs do NOT allow sub-
tasks to communicate via global dataMaking sub-tasks as independent as
possibleWhen possible the data structures required
to implement a sub-task’s functionality are hidden inside the sub-task
Testing Program Designs
An integral part of a structured approach to program design is the testing of those designs.
Revise the Input Validation, Testing and
Maintenance module of the course.
Mapping Designs to C++ ProgramsThere is a natural mapping from the elements
of a structured design to C++ code. In overview:Mapping global constant table entries to
C++ global constant definitionsWriting a C++ function for each of the
sub-tasks in the design:With the function main() corresponding
to the main sub-taskA function’s parameters corresponding
to the sub-task interfaceMapping local constant data items table
entries to C++ local constant definitions
Mapping Designs to C++ Programs
Mapping local data items table entries to local variable definitions
Mapping the pseudocode constructs of algorithms to C++ constructs
The generated code must be readable and maintainable, which involves:Generation of explanatory documentationAppropriate use of white space, including
the use of indentation to emphasise the scope of control structures
C++ Global Constant Definitions
In C++, global constants must appear in the code prior to their first use:
By convention they are placed before any function prototypes (and after any #include directives)// any #include directives // any using statements
// global constant definitionsconst double PI = 3.1415;
// any function prototypes
Mapping sub-tasks to C++ functions
Sub-tasks in the program design are mapped to C++ functions.The main sub-task is mapped to the C+
+ function main() which takes the general form:
void main(void){
// local constant definitions// declarations of local variables
// C++ code to implement the main// sub-task of the program design
}
Example: Mapping local data items table – Ted’s TV Repairs
int
TVsLookedAt;
double
ChargeToLook,
HoursWorked,
HourlyRate,
GeneratedRevenue;
Mapping calls to sub-tasks to C++ function calls
The sub-task call:
get the required input
maps to the C++ function call:
GetRequiredInput(TVsLookedAt, ChargeToLook, HoursWorked, HourlyRate);C++ function calls generally take a list of
arguments which correspond to the interface data items of the called sub-task
Function ArgumentsIn a called function, an argument
corresponding to:An input data item may be a constant, a
variable or an expressionSince data only flows into the function
via this argumentAn output or input/output data item
must be a variableSince data may flow from the called function to the calling function via this argument, a variable must be used to store the value passed back from the function
Mapping pseudocode constructs to C++ constructs
To map the Ted’s TV Repairs main algorithm to C++ code:The set statement maps to the C++
assignment statementThe write statements map to generating
output on the pre-defined standard output stream object, coutAccess to cout is achieved by including
the iostream library Names in std namespace are made
known with using statements
Ted’s TV Repairs – function main()
#include <iostream> // for cout, endlusing std::cout;using std::endl; void main(void){int
TVsLookedAt;double
ChargeToLook,HoursWorked,HourlyRate,GeneratedRevenue; …/cont’d
Ted’s TV Repairs – function main()
// INPUT: get inputs from the userGetRequiredInput(TVsLookedAt, ChargeToLook,
HoursWorked, HourlyRate); // PROCESS: calculate the generated revenue GeneratedRevenue = TVsLookedAt * ChargeToLook +
HoursWorked * HourlyRate; // OUTPUT: display calc’d generated revenue cout << "Generated revenue ==> " << GeneratedRevenue << endl;
}
Mapping Sub-tasks to C++ Functions
A sub-task of a program design, other than the main sub-task, maps to:A C++ function prototype and a C++ function implementation
In C++, all names – including function names - must be declared before use:Thus the function, GetRequiredInput(),
must be declared before its use in function main()
Mapping Sub-tasks to C++ Functions
By convention, all function prototypes are placed before all possible invocations i.e. prior to the function main()(which precedes all function implementations)
In C++, a function can have a return value.The return-value type must be specified
in the function prototype. Functions which do not return a value are
specified with a return type of void
Mapping Sub-tasks to C++ Functions
A sub-task interface maps to the parameters of the corresponding C++ function.The program design provides the
following information about parameter declarations:Parameter typesWhether a parameter is an input, output or input/output parameter
Mapping Sub-task Interfaces to C++ Function Parameters
Parameter types can be determined from the data items.For the get the required input sub-task the
types are determined from the main sub-task data items.
Thus the parameters of GetRequiredInput() will have the following types:
int TVsLookedAtdouble ChargeToLookdouble HoursWorkeddouble HourlyRate
Mapping Sub-task Interfaces to C++ Function Parameters
Input, Output or Input/Output interface data items must be mapped into the C++ parameter-passing mechanisms, which are:Pass-by-value
The value of an argument passed to a function cannot be changed by the function call
Input data items are mapped to pass-by-value parameters – Example:
void FunctionId(int ParamId);
Mapping Sub-task Interfaces to C++ Function Parameters
Pass-by-referenceValue of an argument passed to a function
can be changed by the function callOutput and Input/Output data items are
mapped to call-by-reference parametersTo designate that a parameter is pass-by-
reference, precede the parameter name with an & character - Example:void GetRequiredInput(
int &TVsLookedAt, double &ChargeToLook, double &HoursWorked, double &HourlyRate);
C++ Arrays as ParametersAn array variable (in C++) represents the
address of the 1st element (0th index) of the array. For example:const int MAX_STUDENTS = 300;int StudentResults[MAX_STUDENTS];The name of the array, StudentResults,
is the address of the first element, StudentResults[0]
Individual array elements are accessed with the use of the [] operator – Example:StudentResults[2] = 95;
C++ Arrays as Pass-by-value Parameters - Example
const int MAX_STUDENTS = 300;AFunction(int StudentResults[], int Index);...void main (void){
int Index = 2;int StudentResults[MAX_STUDENTS]; ...StudentResults[Index] = 95;...AFunction(StudentResults, Index); //
(1)...
}
C++ Arrays as Pass-by-value Parameters - Example
C++ Arrays as Pass-by-value Parameters - Example
Thus, the elements of the array can be accessed in the body of Afunction() via the address in the local copy. Example:
StudentResults[2] = 22; would modify the 3rd element of the array passed as argument to the functionThe array is passed by value, but the
effect is simulated or pseudo call-by-reference.
Output & Input/Output array data items of a sub-task interface are mapped to call-by-value parameters in C++
Mapping input data items to C++ function parameters
An input array data item should map to a construct which disallows modification of the array elements within the body of the function. Can be achieved with the C++ type
qualifier, const. Example:AFunction(const int
StudentResults[], int Index);Thus, input array data items of a sub-
task interface map to const array parameters in a C++ function
C++ Function ImplementationA function implementation corresponds to a
whole sub-task, interface + algorithm of a program design.
A function implementation is a definition of how the function accomplishes its task.
Mapping a sub-task to a function implementation involves:Mapping the sub-task interface to function
parametersMapping local constant & data items to local
constant and variable definitionsMapping the sub-task algorithm to C++
constructs
C++ Function Implementation – General Format
void FunctionName(<parameter list>){
// definitions of local constants &// variables
// C++ code to implement the sub-task// of the program design
}
Function Implementation – Ted’s TV Repairs
void GetRequiredInput(int &TVsLookedAt, double &ChargeToLook,
double &HoursWorked, double &HourlyRate) {
// prompt for/get the no. of TVs looked at// per monthcout << "Number of TVs looked at ==> ";ReadInteger(TVsLookedAt); // validate as int
…/cont’d
Function Implementation – Ted’s TV Repairs
// prompt for/get no. of hours worked per monthcout << "Number of hours worked ==> ";ReadDouble(HoursWorked); // validate double
// prompt for/get charge rate to look at a TVcout << "Charge rate to look at a TV ==> ";ReadDouble(ChargeToLook); // validates double
// prompt for/get hrly rate for work on a TVcout << "Hourly rate for looking at a TV ==> ";ReadDouble(HourlyRate); // validates double
}
Summary Structured programs are easily understood Structured programming is an organised
approach to program design that increases the likelihood of producing clear, correct & efficient programs
Algorithms are independent of any programming language
Structure charts/Flow charts/Pseudocode help programmers in designing and developing algorithms
Function parameters can be passed by value or reference
The name of the array is the address of the first element