Structured Programming

advertisement
Structured Programming
Defn: This is an approach to program development that produces programs of
high quality that are easy to test, debug, modify and maintain. This technique
emphasizes the modular approach to program development.
Modular Programming: Using this approach a large complex problem is broken
up into sub-problems, and if necessary these are further divided until the tasks
to be solved are simpler or easier for programming code to be developed. – Top
Down Design
ORIGINAL
PROBLEM
X
MEMBER FILE
ADD A
MEMBER
SEARCH FOR
A
MEMBER
MOVIE FILE
DELETE A
MEMBER
EXIT
Structured Programming
Defn: A structure chart is ideally a map of your program which shows how
variables pass data between modules in a program. It helps the programmer to
produce a top-down design of the program
Steps:
Place the main module as the root of an upside-down tree
Determine the set of tasks necessary for solving the problem.
Place these below the root and connect the root to each task
Break down each task into even smaller tasks if necessary.
Eventually the program is broken down to a point where the “leaves” of the
structure chart “tree” represent simple modules that can be coded with just a few
statements.
Structure Charts
Automatic Teller
Activate Customer
Accounts
Validate
Customer
Get Valid
Card #
Pull customer
record
Get Valid
Code #
Handle transactions
Check Transactions
Handle
Queries
Savings Transactions
Handle
Deposits
Exit
Transactions
Handle
withdrawals
Fig 2. A structure chart,. Each box (node) in the chart represents a block of code called a
module. The root node (box at the top) represents the main section of the program. Each
connecting line represents a call to a module. The connecting lines could be variables (data)
which are passed to and from modules.
Structured Programming
Most of the programs written at the ordinary and advanced level courses are likely
to be short; however, in the IT arena most problems will require thousands, if not
millions of lines of code. (Windows 2000 – over 35 millions lines of code). The
importance of splitting a problem into a series of self-contained modules then
becomes obvious. A module should not exceed 100 lines, and preferably short
enough to fit on a single page or screen.
ADVANTAGES OF MODULAR PROGRAMMING
Allows a problem to be split in stages and for a team of programmers to work on
the problem, also enabling a faster solution.
 Senior programmers can be given the more complex modules to write, and the
junior programmers the simpler ones.
 Program modification is easier since changes can be isolated to specific
modules.
Modules can be tested and debugged independently.
Since a module performs a specific well defined task, it is possible to develop and
place commonly used modules in a user library so that they can be accessed by
different programs. (e.g. Validation, Uppercase, Text color…Pascal)
 If a programmer cannot continue through the entire project, it is easier for
another programmer to continue working on self contained modules.
Structured Programming
In the Pascal programming language the concept of structured programming is
expressed using Procedures and Functions.
 Procedures are portions of code that perform a specific task such as draw a
square on screen, prompt a user to enter values, display results on screen etc.
They can exist as independent statements e.g. textcolor(red), inc(x), clrscr;
 Functions are also portions of code that perform a specific task. However,
they return a value or result, such as an integer, a real number, a string , etc.
Consequently, they can only be used as components of statements e.g.
ch:=upcase (ch); y:= abs(z);
Consider the following simple example.
Program Example1:
Procedure open_screen;
Program header
Procedure header
Begin
writeln(‘ Welcome to Cyber Core….’);
End of Procedure
end;
Begin
open_screen;
End.
Start of main program
Calling the procedure open_screen
End of program
Structured Programming
Examine the Pascal program below which prompts a user for two names and outputs the one that is alphabetically
smaller. The program uses a procedure which creates a border (of 20 asterisks) before and after the output. Note also
that the procedure is called twice from the main program and that procedures and functions are written before the
main program.
Program smaller_name;
Var name1,name2:string;
Program header
Global Variables
Procedure Border;
Local Variable
Var i:integer;
Begin
for i:= 1 to 20 do
write(‘*’);
writeln;
End;
End of Procedure
Begin
Start of main program
writeln(‘ Enter two names ‘):readln(name1,name2);
Border;
Call Procedure
If (name1<name2) then
writeln(name1)
else
writeln(name2);
Border;
End.
Call Procedure again
Structured Programming
Notice that the procedure will only print 20 asterisks, no more and no less. If 10 or even 40 asterisks are required
then the same procedure can be used, though some modification will be required. This can be achieved with the
use of a parameter list with one variable, say Num_asterisks . The procedure now looks as follows:
Procedure Border(Num_asterisks:integer);
Var i:integer;
Parameter List
Begin
for i:= 1 to Num_asterisks do
write(‘*’);
writeln;
End;
On examining the new format the number of asterisks is passed to the procedure through the parameter list in the
procedure header. Consequently, when the procedure needs to be called, the value of the parameter is placed in
brackets. So calls in the main program would look like Border(10); or Border(40) ; for printing 10 or 40 asterisks
respectively.
 Global variables exist throughout the scope of a program. They are declared at the start of the program and
values may be accessed at any time and position during the execution of the program.
 Local Variables are declared within a procedure or function. They are created when the subroutine is started
and only exist when that portion of code is executed. When the procedure or function is exited the memory space
which was reserved for the local variables is released for other use.
N.B to minimize the constraints for the running of a program more local declarations
should be made where possible.
Structured Programming
In the Pascal programming language Functions are very similar to Procedures except that they return a value. The
golden rule is that if a value is not to be returned then a procedure should always be used. When programming the
reserved word Function is used instead of the word Procedure and the data type of the returning value must be
stated.
Format of a Pascal Function
Function Name _of _function (parameter_listing) :datatype
Var any_local_variables;
Begin
statement1;
statement2;
Name_of_Function:= value;
End;
Function is_even (num : integer):boolean;
Begin
if (num mod 2 = 0) then
is_even:=true
else
is_even:= false;
end
Integer, string,
char, boolean
Structured Programming
Consider the Pascal program below and answer the questions that follow.
Program test1;
Var ans, num:integer;
Procedure cubed(num: integer; var ans:integer);
Begin
ans:= num * num * num;
End;
Begin
Writeln(‘Enter number : ‘); readln (num);
cubed(num , ans);
Writeln(‘Number Cubed : ‘,ans);
readln;
End.
• What is the name of the program?
• Write the names of the global and local variables.
• State the parameter list in the procedure.
•For each parameter , identify whether it is a variable or value parameter and why.
•What will be the output if the following numbers are entered (a) 4 (b) 3.2 ?
•Do you think cubed should be written as a Function? If so why?
•Assume you decide to write cube as a Function, rewrite the above portion of code.
Program test1;
Var num:integer;
Function Cubed(num: integer) :integer;
Begin
cubed:=num * num * num;
End;
Begin
writeln (‘Enter number : ‘); readln (num);
writeln(‘Number Cubed : ‘, cubed(num));
readln;
End.
Structured Programming
Consider writing a program where a user is required to enter integer values M and N and to calculate and output M
raised to the power N. In analyzing the problem, three cases need to be considered:
• the case of N being Zero
• the case of N being positive and
• finally the case of N being negative
The modular breakdown of the problem now looks as follows:
Power Raising
M +n
M0
M -n
It is now possible to focus on one module at a time and to develop the internal workings (stepwise refinement).
For the Zero case the body of the module would need only contain the statement setting the answer to 1
(Any number raised to the power of Zero equals 1!)
For the Positive Case the following portion of code could be used
ans:= 1;
for i:= 1 to N do
ans:= ans * M
For the Negative Case it is observed that M – n is equal to that of 1/ M + n. Thus, use could be made of previously
written code for the positive case. (all that is necessary is for the procedure to be appropriately called)
Download