Programming 2 (Structured Programming) : Worktext in ITC 106
Programming 2 (Structured Programming) : Worktext in ITC 106
Programming 2 (Structured Programming) : Worktext in ITC 106
PROGRAMMING 2
(STRUCTURED PROGRAMMING)
LLOYD MARK RAZALAN
ANGELO NATHANIEL LOMIBAO
DARWIN G. RARALIO
INSTRUCTOR
Week 5-8
0
Lesson II
Sub Procedures and Function Procedures
Objectives:
After this lesson the students should be able to:
1. To understand how to construct programs modularly from procedures and functions.
2. To be able to create new procedures and functions.
3. To understand mechanisms used to pass information between procedures and functions.
Introduction
Most computer programs that solve real-world problems are much larger than those
presented in the fist few lessons. Experience has shown that the best way to develop and
maintain a large program is to construct it from smaller pieces each of which is more
manageable than the original program. This technique is called divide and conquer. This lesson
describes many key features that facilitate the design, implementation, operation and
maintenance of large program.
Form Modules
A project is made up of modules-such as form modules. Form modules consist of smaller
pieces called procedures. Four types of procedures exist: Event procedure, Visual Basic
procedures, sub Procedures and Function procedures.
Event Procedures – respond to events (i.e. pressing buttons,etc.)
Visual Basic Procedures – (i.e. format$, IIf, Load-Picture, etc. ) are provided by Microsoft to
perform common tasks. Because VB allows programmers to create their own procedures
(called Sub procedures and Function Procedures) to meet the unique requirements of the
problems they solve. Throughout this lesson we simply use the term procedure to refer to both
Sub procedures and Function procedures unless otherwise indicated.
A procedure is invoked(i.e. made to perform its designated task) by a procedure call.
The call specifies the procedure name and provides information (as arguments) that the callee
needs to do its job.
Sub Procedures
sub procedures are created with the Add Procedure dialog (displayed when Add Procedure is
selected from the Tools menu). The Add Procedure menu items is grayed unless the code
window is visible.
The Procedure name is entered in Textbox Name and can be any valid identifier. Frame type
contains radio buttons for selecting the procedure type (sub or function)
1
Frame Scope
Contains radio buttons for selecting keyword Public or keyword Private that will predcede the
procedure name. Public is selected by defaulst. For now as a good practice, we will use
keyword Private, which also preceded our event procedures.
Checking Checkbox All Local variables as Static adds keyword Static to the
procedure creaed with AddProcedure. For now, we will not use this feature.
Once a valid name has been typed into TextBox Name and Ok has been pressed,
the procedure appears in the Code window.
Sub procedures can also be created by typing the sub procedure directly into the code window.
Once a line such as
Private Sub AnotherProcedure()
Is typed and the enter key pressed, Visual Basic automatically creates the End Sub line.
The line Private Sub AnotherProcedure() is the sub procedure header. The header contains
keyword Private, keyword Sub procedure is called (or invoked) the body is immediately
executed. AnotherProcedure is invoked with the line.
2
Another Procedure
Execution of the sub procedure terminates when End Sub is reached. Program execution
then continue with the statement immediately following the call to AnotherProcedure.
all sub procedure definitions contains parenthesis which may be empty or may contain
a list of variable declarations (called parameter list) Consider the following Sub Procedure.
Private Sub PrintPay(hours As Single, wage As Currency)
Print hour * wage
End sub
Which declares two parameter variables, hours and wage, in the parameter list. Parameter
variables are declared using the As keyword or a type-declaration character (if one exists).
Parameter variables are not explicitly given a type default to Variant. Parameter variables
receive their values from the procedure call and are used in the procedure body.
3
The call to PrintPay could also have be written as
Call PrintPay(40, 10.00)
Which uses keyword call and encloses the arguments passed in a set of parenthesis. The
arguments passed can be variable names as well. For example, the call
Call PrintPay(x, y)
Would pass x and y to PrintPay.
Example:
A programmer-defined sub procedure Minimum to determine the smallest of three integers.
The smallest value is displayed in a Label
‘pogram finds the minimum of three numbers input
Option Explicit ‘General declaration
Private Sub cmdSmallest_Click()
Dim value1 As Long, value2 As Long, value3 As Long
value1 = txtOne.text
value2 = txtTwo.text
value3 = txtThree.text
4
The statement
Call Minimum(value1, value2, value3)
Calls Minimum passing value1, value2 and value 3 as arguments. Variables min, y and z are
declared in Minimum to store the values of value1, value2 and value3 respectively. Two if/then
statements ensure that min contains the smallest value. Variable min’s contents are displayed
in Label.
The Visual Basic IDE provides many features for creating programs rapidly. Auto list
members is one such feature that automatically displays an object’s properties and methos.
When the period, l, is typed after an object name, a window appears that lists the properties
and methods for that object. Auto list members allows the programmer to quickly find a
property or method. A property or method is selected by double clicking with the mouse or by
pressing the Tab key or the Enter Key.
Another Useful IDE feature is auto quick info for displaying procedure information for
both Visual Basic procedures and programmer-defined procedures. It shows auto quick info
for programmer-definced procedure Minimum. Auto quick info is displayed automatically
when the opening parenthsis that follows a procedure name is typed.
Both autos list memebtes and auto quick info can be disabled by unchecking Auto List
Members and Auto Quick Info in the Options dialog (Displayed when the Tools menu
Options.. command is selected.)
5
Function Procedure
Function Procedure and sub Procedure share the same characteristics, with one
important difference – Function procedures return a value to the caller, whereas sub procedure
do not. Most procedures 0provided by VB are function procedures. For example, Format$
returns a formatted string.
6
IsVolunteer88 returns either True of False to the caller. A function procedure’s return value is
specified in the body by assigning a value to the Function procedure name, as in
IsVolunteer88 = IIF(mIdNumber, True, False)
Which returns either true or false. Control then returns(along with the value returned) to the
calling statement
returnValue = IsVolunteer88()
and the return value, true or false, is assigned to variable returnValue. Program execution then
continues with the next statement after the call to IsVolunteer88.
All function procedure definitions contain parenthesis. The parenthesis may be empty or may
contain one or parameter variable declarations. Consider the following Function procedure:
An argument can be passed call by value either by using keyword ByVal or by enclosing that
arguments in parentheses, (). To pass an argument call by value, precede the corresponding
parameter variable in the procedure definition with keyword ByVal. Otherwise, call by
reference is implied. The following header declares two variables:
Function Foo(ByVal x As Long, y As Boolean) As Double
Foo receives x by value and y be reference. Visual Basic also provides keyword ByRef, so
Foo could be rewritten as
8
Function Foo(ByVal x as Long, ByRef y as Boolean) As Double which also indicates that x is
received call by value and y is receive by call by reference ByRef is the default, so
programmers rarely use it. The call
doubleValue = Foo(passACopy, passOriginal)
does not use keyword ByVal or ByRef. Arguments passed ByVal can be enclosed in an
optional set of parentheses, as in
doubleValue = Foo(passACopy), passOriginal)
which passes passACopy by value and passOriginal by reference.
When passing arguments call by value, use the optional parentheses around the arguments
being passed and the ByVal keyword in the procedure header. This makes it absolutely clear
that arguments are being passed call by value.
Assuming the ByVal keyword applies to more than one parameter is a logic error. For example,
ByVal in the header of Function Foo(ByVal x As Long, y As Boolean) applies to x and not to
y.
Using the ByVal or ByRef keywords outside a procedure header is a syntax error.
Example:
9
When the if/then/else statement determines that number is less than 0, exit sub is
executed and control is transferred to line.
Next x
Where execution resumes.
Statement exit function causes immediate exit from a function procedure. Control is
returned to the caller and the next statement in sequence after the call is executed.
Example:
10
Exercise 5:
End _____
9. Dim x ___ integer
10. ___________ can weaken security because the called procedure can modify the caller’s
data at will, possibly changing that data.
11
Exercise 6:
2. Analyze the code. Try to find the errors and correct. Display the output
Public 1 As Integer ‘general declaration
Public Sub (product)
Dim a, b, x As Integer
a=B*x
End Sub
12
Lesson 3:
Arrays
Objectives
After this lesson the student should be able to:
1. Introduce the array data structure.
2. Understand the use of arrays to store, sort and search lists and tables of values
3. To understand how to declare an array, initialize an array, and refer to individual
elements of an array.
Arrays
An array is a consecutive group of memory locations that all have the same name and
the same type. To refer to a particular location or element in the array, we specify the array
name and the array element position number. Arrays are name like any other variable
13
To divide the value of element 3 (where element indexes begin at 0) of numbers by 2 and
assign the result to the variable x, we would write
x = numbers(3) /2
Declaring Arrays
Arrays occupy space in memory, the programmer specifies the array type and the
number of elements required by the array so that the compiler may reserve the appropriate
amount of memory. Arrays may be declared as Public(in code module), module or local.
Module arrays are declared in the general declarations using keyword Dim or Private. Local
arrays are declared in a procedure sing Dim or Static. Arrays must be declared explicitly with
keyword As
The declaration
Dim numbers(5) As Integer
Tells the compiler to reserve six elements for Integer array numbers. The value 5 defines the
upper bound of numbers. The lower bound is specified in the declaration, a fixed-sized array
is created.
Memory may be reserved for several arrays with a single declaration. The declaration reserves
100 elements for integer array b, 27 elements for Long array x, 15 elements for string array s
and four elements are initialized to zero by default. The programmer can explicitly initialize
the array with assignment statements.
For example, the lines would initialize numbers to the
values shown in the picture. Repetition statements can also
be used to initialize arrays. For example
For x = 0 to 30 Step 3
h(i) = x
i=i+1
Next x
Initializes the elements of h to the values 0, 3, 6, 9, ……. 30.
14
Examples using arrays
This program use a for to print the contents of ten element integer array dar. By default, each
element of dar is initialized to zero. The program introduces functions LBound and UBound.
Function LBound returns the lower bound(the lowest numbered index value) and function
UBound returns the upper bound(highest numbered index value).
Example 2:
Our next example uses arrays to summarize the results of data collected in a survey.
Consider the problem statement:
Forty students were asked to rate the quality of the food in the student cafeteria on a scale of
1 to 10 (1 means awful and 10 means excellent). Place the 40 responses in an integer array and
summarize the result of the poll.
This is a typical array application. We wish to summarize the number of responses of
each type (1 through 10). The array responses is a 40 element array of the student’s response.
We randomly generate the poll data. Ten element array frequency counts the number of
occurrences of each response.
Up to this point, we have used the default lower bound of 0. We could ignore the first
element, frequency(0), because it is more logical to have the first response increment element.
A more convenient solution is to use the option base statement. Option base sets the lower
bound to 0 or 1 and is placed in the general declaration. This allows us to use ach response
directly as the inde3s in the frequency array.
15
The program introduces the event procedure Form_Load, which is called by Visual Basic
when the form is created at run time. During the from lifetime, form_Load is called only once
by Visual Basic. In Form_Load, we randomly generate the data that represent the student poll
responses and place them into mresponses.
Procedure cmdPrint_Click calculate and prints the frequency of each response. The first
for loop takes each responses from mresponses and increments one of the ten frequency
counters (frequency(1) to frequency(10) with the statement.
Frequency(mresposes(x)) = frequency(mresponses(x)) + 1
This statement increments the appropriate frequency counter depending on the value of
mresponses(x). for example, when the counter x is 1, mresponses(x) is 1, so
frequency(mresponses(x)) is actually interpreted as
Frequency(1) = frequency(1) + 1
Which increments array index one, when x is 1, mresponses(x) is 2, so
frequency(mresponses(x)) is interpreted as
Frequency(2) = frequency(2) + 1
Which increments array index six, and so on. Note that regardless of the number of responses
processed in the survey, only a ten element array is required to summarize the results. If the
data contained invalid values such as 13, the program would attempt to add 1 to frequency(13).
This would be outside the bounds of the array, which is a runtime error. Thus, an executing
program can walk off either end of an array without warning.
16
Passing Arrays to Procedure
To pass an array argument of a procedure, specify the name of the array followed byt a pair of
empty parenthesis. For example, if array hourlyTemparatures is declared as
Dim hourlyTemperature(24) As Integer
The call
Call ModifyArray(hourlyTemparatures())
Passess array hourlyTemparatures to procedure ModifyArray. Arrays are automatically passed
call by reference the calle can modity the element values in the callers original array.
Individual array elements are also passed call by reference. To pass an element of an array to
a procedure, use the array element as ang argument in the call. For example, the call
Call PassOneElement(hourlyTemparature(5))
Would pass the array element corresponding to index 5 to PassOneElement.
For a procedure to receive an array through a call, the parameter list must specify that an array
will be received. For example, the procedure header for ModifyArray migh be written as
Private Sub ModifyArray(a()) As Integer
Indicating that ModifyArray expects to receive an Integer array in parameter a. the size of the
array is not specified between the array parentheses. Because arrays are passed call by
reference, when the callee uses the array name a, it will in fact be referring to the actual array
in the caller (array hourlyTemparatures in the preceding call).
For a procedure to receive an array element from a call, the procedure declares a variable
of the type passed. For example, the procedure header for PassOneElement might be written
as
Private Sub PassOneElement(k as Integer)
Variable k refers to hourlyTemparatures(5)
There may be situations in which a procedure should not be allowed to modify array elements.
Because arrays are always passed call by reference, modification of array values is difficult to
control. One solution is to pass each element individually call by value but rememeber that
this can caus performance problems.
Array elements are passed call by value with keyword ByVal or parentheses. For
example, to pass the eight index of hourlyTemperatures call by value to procedure
TempGauge, we write
Call TempGauge((hourlyTemperatures(8))
Or we write
Private Sub TempGauge(ByVal hourlyTemp as Integer)
Which uses keyword ByVal. The parenthesis in the call and keyword ByVal in the declaration
can be used together or separately.
17
Example:
The program demonstrates passing an array and passing array elements to a procedure.
18
19
Sorting Arrays
Sorting data(placing the data into some particular order such as ascending or
descending) is one of the most important computing applications. A bank sorts all checks by
account number so that it can prepare individual bank statements at the end of each month.
Telephone companies sort their lists of accounts in telephone books by last name and with in
that, by first name to make it easy to find phone numbers. Virtually every organization must
sort some data and in many cases, massive amounts of data. Sorting data is an intriguing
problem that has attracted intense research efforts in the field of computer science.
The program below sorts the values of the ten element array mArray into ascending
order. The technique we use is called the bubble sort or the sinking sort because smaller values
gradually “bubble” their way to the top of the array like air bubbles rising in water and larger
values “sink” to the bottom of the array. The technique is to make several passes through the
array. On each pass, successive pairs of elements are compared. If a pair is increasing order
(or the values are identical), we leave the values as they are. If a pair is in decreasing order,
we swap the values in the array. Sub procedure BubbleSort performs the sort. For resusability,
we place BubbleSort in a code module.
Example:
20
Exercise 7
21
Exercise 8
1. Create a program where you declare an array with 9 elements and get its average.
22
Reference:
Visual Basic 6: How to Program
Deitel & Deitel
T.R. Nietto
23