Presentation is loading. Please wait.

Presentation is loading. Please wait.

Top-down approach / Stepwise Refinement & Sub Procedures

Similar presentations


Presentation on theme: "Top-down approach / Stepwise Refinement & Sub Procedures"— Presentation transcript:

1 Top-down approach / Stepwise Refinement & Sub Procedures
24/11/2018

2 Learning Objectives Define a procedure.
Explain why procedures are useful. Explain the difference between event and sub / function procedures. State how to begin and end a procedure. 24/11/2018

3 Top-Down Technique / Stepwise Refinement
A problem solving technique: The problem is divided up into a number of smaller problems called modules. Each one is solved separately. Then each module is combined to form a solution to the whole problem.

4 How do we find the area of a 'house' made up from a rectangle and a triangle?
24/11/2018

5 Prose (language description) / Structured English
Find the area of the triangle by multiplying the base by the height and halving. Find the area of the rectangle by multiplying the width by the breadth. Then add the area of the triangle and rectangle together. Each sentence is a module. 24/11/2018

6 Formulae Each formula is a module. AT = ½ BH AR = W + H + W + H
BT = Base of the triangle HT = Height of the triangle W = Width of rectangle BR = Breadth of rectangle AT = Area of the triangle AR = Area of the rectangle AT = ½ BH AR = W + H + W + H = 2 * (H + W) Area of the house = AT + AR Each formula is a module. 24/11/2018

7 Ordered Steps / Structured English
Find the height and base of the triangle. Find the area of the triangle by multiplying the height of the triangle by the base of the triangle, and halving. Find the width and breadth of the rectangle. Find the area of the rectangle by adding the width of the rectangle to the breadth of the rectangle, and multiplying by 2. Add the areas of the triangle and rectangle together. Each step is a module. 24/11/2018

8 Flowchart Ordered steps using arrows to point from one instruction to the next instead of numbers. Find the height and base of the triangle. Find the area of the triangle by multiplying the height of the triangle by the base of the triangle, and halving. Find the width and breadth of the rectangle. Find the area of the rectangle by adding the width of the rectangle to the breadth of the rectangle, and multiplying by 2. Add the areas of the triangle and rectangle together. 24/11/2018

9 Using procedures is the top-down approach to programming
Procedures are modules in program code: A small subprogram which is given a name / identifier. Does a defined task or combination of related defined tasks. Is identified by having a name and is executed when called by its name / identifier.

10 Main Types of Procedure in VB
Sub procedures (sometimes shortened to just procedures). Function procedures (sometimes shortened to just functions and these will be looked at in detail in presentation 8.2 Procedures). These are not set off directly by running a program, but are called by code within the main procedure (Sub Main) or from within another Sub procedure i.e. one of the above.

11 Variables When a program runs, the results to any calculations it performs are stored in RAM. The results to these calculations will be lost as soon as the computer starts doing something else. A variable is a name made up by a programmer to reserve and identify an address in RAM where data can be stored as long as the program runs. 11

12 How do we find the area of a 'house' made up from a square and a triangle?
24/11/2018 12

13 Structure Chart Area of “house” Area of rectangle Area of triangle
Parameters – see the next few slides for details. HouseArea RectangleArea AreaTriangle RectangleWidth RectangleArea TriangleBase TriangleArea RectangleLength RectangleArea TriangleHeight AreaTriangle HouseArea Area of rectangle Area of triangle Area of rectangle + triangle Note that the variable to be returned e.g. TriangleArea also has to be sent to the sub procedure so its value can be changed by the sub procedure - see Value and Reference parameters – later.

14 Parameters Variables passed between (sent to and / or from) modules.
Necessary if the called procedure needs a local variable from the calling procedure.

15 Parameters Passing = sending to or from Variables (with stored data)
Sent to the called procedure from the calling procedure. Or Sent from the called procedure to the calling procedure after it has finished. Needed only when: The called procedure requires data to perform its task. The calling procedure requires data which the called procedure produces. Passing = sending to or from 24/11/2018 15

16 Actual and Formal Parameters
Actual Parameters Variables that are passed to a procedure when it is called. i.e. Call …(…, …, …) Formal Parameters Variables which must be declared in the procedure which must match in number, position and data type the actual parameters sent to it. i.e. Sub …(…, …, …) 24/11/2018 16

17 Value and Reference Parameters
Formal Parameters can be declared as: Value Parameters (ByVal) Parameters in a called procedure which are not passed back to the calling procedure. Reference Parameters (ByRef) Parameters in a called procedure which are passed back to the calling procedure. i.e. Ones which have been changed by the called procedure and these changes are required by the calling procedure. i.e. Private Sub …(ByVal … As …, ByRef… As …) 24/11/2018 17

18 Formal Parameters You may use the same or different identifiers / names as the actual parameters they match. Exams tend to try to use different ones, so beware! It is optional whether you declare the data types of formal parameters (as they must be the same as the actual parameters they match so are inherited from them). However, your code is clearer if you do. My programs will follow this suggestion. 24/11/2018 18

19 (See the next slide for the answers!)
Can you work out which of the parameters below should be passed by Value and which should be passed by Reference? (See the next slide for the answers!) Structure Chart Area of “house” RectangleArea HouseArea AreaTriangle RectangleWidth RectangleArea TriangleBase TriangleArea RectangleLength RectangleArea TriangleHeight AreaTriangle HouseArea Area of rectangle Area of triangle Area of rectangle + triangle

20 Structure Chart Area of “house” Area of rectangle Area of triangle
Key: ….. Reference parameter Value parameter Data Flag Structure Chart Area of “house” RectangleArea HouseArea AreaTriangle RectangleWidth RectangleArea TriangleBase TriangleArea RectangleLength RectangleArea TriangleHeight AreaTriangle HouseArea Area of rectangle Area of triangle Area of rectangle + triangle

21 ByVal by default If you omit ByVal or ByRef then VB will choose ByVal by default. Meaning that by default no variables are passed back to the calling procedure. 24/11/2018 21

22 Sub procedures May return one or more items of data or no data at all to the calling procedure. No data should be returned if a procedure is required to do something that does not involve any calculations or data manipulation. 24/11/2018 22

23 Top-Down Approach / Stepwise Refinement - Advantages
Avoids repeating code as modules can be stored in and used in other programs from a software library. Makes the code more readable. By splitting a problem / code into smaller parts the solution is easier to follow. Helps in debugging a program. Fewer errors are likely to be made. Any errors that are made will be easier to correct. Many people can be involved in the solution. Individual skills can be used. The last 2 bold advantages should only be used if an exam question scenario involves more than one person.

24 Writing and calling procedures
Sub and function procedures should be written outside the main procedure but inside Module … End Module lines. i.e. Click below the line: Module Module1 Press enter to make a blank line if necessary. As with naming identifiers/variables, no spaces are allowed. We will use the same convention as for naming variables: i.e. Each word starts with a capital Also remember to always use meaningful names. 24/11/2018

25 Beginning procedures Procedure Name To begin a procedure use:
Sub …(ByVal/ByRef …. As …, …., etc ….) Procedure Name Variables needed by the procedure. Variables needed by the procedure.

26 Ending procedures To end a procedure use: End Sub 24/11/2018

27 Calling procedures To call a procedure use: Procedure Name
Call … (…., …., etc….) Variables needed by the procedure. Procedure Name You don’t actually have to use Call. You can just the procedure’s name. However, your code is more readable if you do and it makes it easier to differentiate between a procedure and a variable identifier / name. 24/11/2018

28 Scope of a variable Location declared Level Description
Within a procedure. Local scope Available only within the module in which it is declared Outside a procedure. Global scope Available to all modules. As it is available to all procedures then it is does not need to be passed. 28

29 Narrow scope You may be thinking: “To avoid this issue why don’t we declare all variables globally?” However, it is good programming practice and efficient to declare variables with as narrow a scope as possible. Certain errors/problems can occur if you don’t: Name Conflict Avoidance Several different procedures can use the same variable name/identifier. As long as each instance is declared as a (local) procedure variable, each procedure recognizes only its own version of the variable. Debugging Problems: Difficult to debug as difficult to find where variable value was changed as different procedures can modify the value.

30 Global Vs Local Variables
Due to the issues on the proceeding slide global variables are not used unless all procedures require the variable (or at least most of them).

31 Top-Down Approach / Stepwise Refinement - Disadvantages
Individual modules may work as required but they may be linked incorrectly, so the links must be thoroughly tested. Documentation of modules must be thorough. Variables may clash across modules. Parameters may be of the wrong type.

32 Program 8.1a Procedures & Parameters
Specification: Illustrate the use of procedures & parameters. 24/11/2018 32

33 Program 8.1a Value & Reference Parameters
Open the “Program 5.1a Number Array” – 5.1 Arrays. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Procedure Version). 24/11/2018 33

34 Structure Chart Symbols
Selection Iteration A selection in a Structure Chart is determined by the diamond symbol. This means a condition will be checked and depending on the result, different modules will be executed. Using the semi circular arrow we can represent iteration in Structure Charts. The arrow encompasses a link to a module, implying that module is executed multiple times. 

35 Program 8.1a Procedures & Parameters
Key: ….. Reference parameter Value parameter Iteration Data Flag “Number” array Numbers array Numbers array “Bubble Sort” the “Numbers” array. Range Numbers array Numbers array NumberFound Index Lowest Index Numbers array Highest SearchNumber Range Number entered Numbers array Numbers array Total Index Lowest Numbers array Numbers array Index Index Reset and clear the “Numbers” array. Highest Index Display the “Numbers” array. Total Calculate the Total, Highest, lowest & Range of the numbers in the “Numbers” array Search for a number in the “Numbers” array & display results. Store numbers in the “Numbers” array.

36 Program 8.1a Procedures & Parameters
Main Program Store numbers in the “Numbers” array. ByVal: Number entered, Index ByRef: Numbers array “Bubble Sort” the “Numbers” array. Display the “Numbers” array. ByVal: Numbers array, Index Calculate the Total, Highest, lowest & Range of the numbers in the “Numbers” array. ByRef: Total ByRef: Highest ByRef: Lowest ByRef: Range Search for a number in the “Numbers” array & display results. ByVal: Numbers array, Index, NumberFound, SearchNumber Reset and clear the “Numbers” array. ByRef: Numbers array, Index

37 Program 8.1a Procedures & Parameters
As the “Numbers” array is used by stages/procedures we will declare it globally. This means it will be accessible by all procedures and does not need to be passed. The variable “Index” is also used by all stages/procedures but as it is used separately by each stage we will move the declaration of and any reference to it, locally for each procedure (as its previous value is not needed, just its purpose). As it will be difficult to separate the Number entered from the rest of this “Storing” stage, we will deal with input and the variable “Number” locally inside the first “EnterNumbers” procedure. Therefore see next slide for changes.

38 Program 8.1a Procedures & Parameters
Key: ….. Reference parameter Value parameter Iteration Data Flag “Number” array “Bubble Sort” the “Numbers” array. NumberFound Range SearchNumber Range Lowest Lowest Highest Reset and clear the “Numbers” array. Highest Total Display the “Numbers” array. Total Calculate the Total, Highest, lowest & Range of the numbers in the “Numbers” array Search for a number in the “Numbers” array & display results. Store numbers in the “Numbers” array.

39 Program 8.1a Procedures & Parameters
Global Variable Declaration: Select the Declaration statement of the “Numbers” Array & its comment. 'Declare an array for 5 numbers. Dim Numbers(5) As Integer

40 Program 8.1a Procedures & Parameters
Global Variable Declaration: Move the Declaration statement of the “Numbers” Array & its comment out of the procedure to the beginning, before (or outside of) any procedures or “modules. Also change its comment to: ‘Declare the Numbers array globally so that it is accessible by all procedures. However, this will make it difficult to debug as difficult to find where variable value was changed as different procedures can modify the value.

41 Program 8.1a Procedures & Parameters
Travel outside any procedure into the Global Declarations area. See last slide. Begin and end a procedure with the following lines leaving a blank line in between. Move the Index, Number and EnterAnotherNumber declarations; and line Index = 1 and the Do … Loop Until …. lines regarding the “entering of numbers into the ‘Numbers’ array into the procedure. Replace the lines moved from the main program with a call of this procedure. Sub Main() Variable Declarations. Do NumberFound = False Call EnterNumbersProc() Sub EnterNumbersProc () Dim Index As Integer ‘Used as an index for the array. Dim Number As Integer Dim EnterAnotherNumber As Boolean Index = 1 Do Console.WriteLine(“Enter a number.”) Number = Console.ReadLine ‘Store the number entered. ‘ ‘Store the number in the next element of the array. Numbers(Index) = Number ‘Increment How Many Numbers to move to the next element of the Numbers array. Index = Index + 1 If Index = 5 Then ‘Is array full? Console.WriteLine(“The array is FULL!”) ‘Inform user array is full! Else Console.WriteLine(“Do you wish enter another number (True/False)?”) EnterAnotherNumber = Console.ReadLine End If Loop Until Index = 5 Or EnterAnotherNumber = False End Sub

42 Program 8.1a Procedures & Parameters
Run the program and test it. It should work as normal and feel exactly the same to the normal “user”. Only a programmer would notice the difference when they examine the code. 24/11/2018 42

43 Program 8.1a Procedures & Parameters
Sub Main() Variable Declarations. Do NumberFound = False Call EnterNumbersProc() Console.WriteLines(“Do you wish to “Bubble” sort the array? (True/False)”) If BubbleSort = True Then Call BubbleSortProc() End If Sub BubbleSortProcProc () Bubble Sort Lines – shown below as pseudocode as you were asked to write these lines yourself: Do NoSwaps = True For Index ← 1 To NumberOfItems - 1 If List[Index] > List[Index + 1] Then Temp ← List[Index] List[Index] ← List[Index + 1] List[Index + 1] ← Temp NoSwaps = False End If End For NumberOfItems = NumberOfItems - 1 Loop Until NoSwaps = True For End ← NumberOfItems - 1 To 1 Step - 1 For Index ← 1 To End End Sub Or

44 Program 8.1a Procedures & Parameters
Run the program and test it. It should work as normal and feel exactly the same to the normal “user”. Only a programmer would notice the difference when they examine the code. 24/11/2018 44

45 Program 8.1a Procedures & Parameters
Sub Main() Variable Declarations. Do NumberFound = False Call EnterNumbersProc() Console.WriteLines(“Do you wish to “Bubble” sort the array? (True/False)”) If BubbleSort = True Then Call BubbleSortProc() End If Call DisplayNumbersProc Sub DisplayNumbersProc () Dim Index As Integer ‘Used as an index for the array. Console.WriteLine(“The contents of the array:”) For Index = 1 To 5 'Go through and display each element of the array. Console.WriteLine(Numbers(Index)) Next Index End Sub New Line

46 Program 8.1a Procedures & Parameters
Run the program and test it. It should work as normal and feel exactly the same to the normal “user”. Only a programmer would notice the difference when they examine the code. 24/11/2018 46

47 Program 8.1a Procedures & Parameters
Sub Main() Variable Declarations. Do NumberFound = False Call EnterNumbersProc() Console.WriteLine(“Do you wish to “Bubble” sort the array? (True/False)”) If BubbleSort = True Then Call BubbleSortProc() End If Call DisplayNumbersProc Call SumHighLowRange Proc (Total, Lowest, Highest, Range) Console.WriteLine(“The Total is: “ & Total) Console.WriteLine(“The Highest number is: “ & Highest) Console.WriteLine(“The Lowest number is: “ & Lowest) Console.WriteLine(“The Range number is: “ & Range) Sub SumHighLowRangeProc (ByRef Total As Integer, ByRef Lowest As Integer, ByRef Highest As Integer, ByRef Range As Integer) Dim Index As Integer ‘Used as an index for the array. For Index = 1 To 5 'Go through each element of the array. Total = Total + Numbers(Index) ‘Running total of each number. If Index = 1 Then ‘The 1st number is both the lowest and highest. Lowest = Numbers(Index) Highest = Numbers(Index) ‘Compare each number to the lowest and highest so far and change accordingly. ElseIf Numbers(Index) < Lowest Then Lowest = Numbers(Index) ‘Set new lowest number. ElseIf Numbers(Index) > Highest Then Highest = Numbers(Index) ’Set new highest number. End If Next Index Range = Highest – Lowest End Sub New Line

48 Program 8.1a Procedures & Parameters
Run the program and test it. It should work as normal and feel exactly the same to the normal “user”. Only a programmer would notice the difference when they examine the code. 24/11/2018 48

49 Program 8.1a Procedures & Parameters
Sub Main() Variable Declarations. Do …… Console.WriteLine(“Enter a number to search for.”) SearchNumber = Console.ReadLine Call SearchArrayProc(SearchNumber, NumberFound) Console.WriteLine(“Do you wish to ‘Search’ again, ‘Reset’ or ‘Exit’?”) Request = Console.ReadLine Loop Until Request <> “Search” ‘Search again or continue. Sub SearchArrayProc(ByVal SearchNumber As Integer, ByVal NumberFound As Boolean) Dim Index As Integer ‘Used as an index for the array. 'Go through each element in the array to search for the number required. For Index = 1 To 5 ‘Has the number been found? If Numbers(Index) = SearchNumber Then Console.WriteLine(“The number “ & SearchNumber & “ is in element " & Index & " of the ‘Numbers’ array.“) NumberFound = True End If ‘Keep looking until all 5 elements have been searched. Next Index ‘If the number was not found display a suitable message. If NumberFound = False Then Console.WriteLine(“The number " & SearchNumber & " has not been found in the ‘Numbers’ array. End Sub New Line

50 Program 8.1a Procedures & Parameters
Run the program and test it. It should work as normal and feel exactly the same to the normal “user”. Only a programmer would notice the difference when they examine the code. 24/11/2018 50

51 Program 8.1a Procedures & Parameters
Sub Main() Variable Declarations. Do …… If Request = “Reset” Then ‘Reset? Call ResetArrayProc() End If Loop Until Continue = “Exit” ’Exit? Sub ResetArrayProc() Dim Index As Integer ‘Used as an index for the array. ‘Arrays may contain values from previous processing. If they do then programs will use this data and give incorrect results. Loop through each array element from element 1 to the last element. For Index = 1 To 5 Numbers(Index) = 0 ‘Place a zero in all array elements. Next Index End Sub New Line

52 Program 8.1a Procedures & Parameters
Run the program and test it. It should work as normal and feel exactly the same to the normal “user”. Only a programmer would notice the difference when they examine the code. 24/11/2018 52

53 Collapsing / Expanding “Procedures” / “Code Blocks”
Note that “procedures” or “code blocks” can be collapsed and expanded as needed. 24/11/2018

54 Note that “Global” variables do not appear to be on your syllabus.
Therefore you may be asked to read and write code that involves passing variables that could have been avoided by declaring them globally. Also note that passing arrays is slightly “quirky”: Procedure Declaration: Sub EnterANumberProc(ByRef Numbers() As Integer) Note that brackets are used but no size is given inside them. .... End Sub Main Program: Dim Numbers(5) As Integer ..... Call EnterANumberProc(Numbers) Note that no brackets or size are used. 24/11/2018

55 Commenting on Procedures
For presentations 8.1 & 8.2 I will only ask for comments to procedures. Your comments MUST explain: What is the procedure for? Why and when (after and before what) are you calling it? What parameters are being sent to it and why? What parameters are being returned and why?

56 Given Pseudocode will use the following structure for procedure definitions
PROCEDURE <identifier> <statement(s)> ENDPROCEDURE PROCEDURE <identifier> (BYVALUE <identifier>: <datatype>) PROCEDURE <identifier> (BYREF <identifier>: <datatype>) CALL <identifier> ()

57 Extension Program 8.1b Create procedures for the program “5.1b Marks Array”. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Procedure Version). 24/11/2018 57

58 Extension Programs Open any of the programs you have written previously and move appropriate lines into appropriate procedures. Particularly look at extension programs written in from 5.1 Arrays on. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Procedure Version). Do this for as many programs as you need to until you are confident in creating procedures. 24/11/2018 58

59 Extension Program: “Computing Terms”
Using a text editor, create a sample text file containing a set of computing terms, each followed by a one line description. The typical file contents will be as shown below with each term and description on alternate lines. 24/11/2018

60 Extension Program: “Computing Terms”
Write code to produce a menu for the user as shown. 24/11/2018

61 Extension Program: “Computing Terms”
Code option 1 on the menu as a procedure SearchByTerm which: prompts the user for the search term searches a file (make your own with copy and paste from internet research) for the term and reports either: FOUND ... followed by its description, or TERM NOT FOUND Typical output using the sample file would be: 24/11/2018

62 Extension Program: “Computing Terms”
Code option 2 on the menu as a procedure SearchDescriptionsForKeyword which: prompts the user for the keyword searches all the descriptions in the file for the presence of that keyword and reports either: one or more terms whose description contained the keyword, or NO DESCRIPTIONS FOUND containing this keyword. Typical output using the sample file would be: 24/11/2018

63 Plenary What is a procedure? Why are procedures useful?
A separate section of code which performs one or more specific tasks and is identified by having a name. Why are procedures useful? Avoid repeating code. Make the code more readable. Help in debugging a program. Use the same procedure in other programs. Pass parameters. 24/11/2018

64 Plenary What is the difference between event and sub / function procedures? Event Procedures Executed in response to events e.g. click, change, … Sub / Function procedures These are not set off directly by events, but are called by called by code within an event procedure or from within another non-event procedure i.e. one of the above. 24/11/2018

65 Plenary How do we begin and end a procedure? 24/11/2018

66 Beginning procedures To begin a procedure use: Procedure Name
Private Sub …() Procedure Name Private means that the procedure can only be used on the form it is declared on (all the programs I will show you, use only one form anyway).

67 Ending procedures To end a procedure use: End Sub 24/11/2018

68 Plenary What are parameters?
Variables (with stored data) Sent to the called procedure from the calling procedure. Or Sent from the called procedure to the calling procedure after it has finished. What does passing mean in relation to parameters? Passing = sending to or from 24/11/2018 68 68

69 Plenary What are actual, formal, value and reference parameters?
How do we declare value and reference parameters? 24/11/2018 69 69

70 Actual and Formal Parameters
Actual Parameters Variables that are passed to a procedure when it is called. i.e. Call …(…, …, …) Formal Parameters Variables which must be declared in the procedure which must match in number, position and data type the actual parameters sent to it. i.e. Private Sub …(…, …, …) 24/11/2018 70

71 Value and Reference Parameters
Formal Parameters can be declared as: Value Parameters (ByVal) Parameters in a called procedure which are not passed back to the calling procedure. Reference Parameters (ByRef) Parameters in a called procedure which are passed back to the calling procedure. i.e. Public Sub …(ByVal … As …, ByRef… As …) 24/11/2018 71


Download ppt "Top-down approach / Stepwise Refinement & Sub Procedures"

Similar presentations


Ads by Google