You are on page 1of 24

Worktext in ITC 106

PROGRAMMING 2
(STRUCTURED PROGRAMMING)
LLOYD MARK RAZALAN
ANGELO NATHANIEL LOMIBAO
DARWIN G. RARALIO
INSTRUCTOR
Week 5-8

INFORMATION TECHNOLOGY DEPARTMENT

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.

Procedure PrintPay is called with the line


PrintPay 40, 10.00
Which provides values for parameter hours and parameter wage. The value 40 is stored in
hours and tahe value 10.00 is stored in wage. These values are multiplied together to calculate
the pay, which is then printed.

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

Call Minimum(value1, value2, value3)


End Sub
Private Sub Minumum(min As Long, y As Long, z As Long)
If y < min Then
min = y
End If
If x < min Then
min = x
End If
lblSmallest.Caption = “Smalles value is “ & min
End Sub

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.

Programmer-defined function procedures, can be created with the add procedure. It


could also be created by typing the function procedure directly into the code window.
The line
Private Function IsVolunteer88()
Is the function procedure header. The header contains the keyword function, the function name
and parentheses. The declaratins and statements that the programmer will insert between the
header and End Function form the function procedure body. IsVolunteer88 is invoked with the
line.
returnValue = IsVolunteer88()
When a function procedure name(such as IsVolunteer88) is encountered at run-time, the
function procedure is called, causing its body statements to execute. Consider the complete
definition for IsVolunteer88:
Private Function IsVolunteer88()
‘ mIdNumber is module variable
IsVolunteer88 = IIf(mIdNumber, True, False)\
End Function

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:

Private Function Area (s1 As Single, s2 As Single)


Area = s1* s2 ‘return the area
End Sub
Which declares two parameter variables s1 and s2. Area’s return type is variant area is called
with the statrement.
squareFtNeeded = Area(8.5, 7.34)
which passes 8.5 and 7.34 to area. The value 8.5 is stored in s1 and value 7.34 is stored in s2.
These values are multiplied together to calculate the area, which is returned and assigned to
squareFtNeeded. When one or more arguments are passed to a Function procedure, parenthesis
are required. A function procedure that does not take any arguments need not have parenthesis
in the call.
7
Calling a function procedure without enclosing its arguments in parentheses is a syntax error.
Return types can be explicitly stated in the Function procedure header using either the As
keyword or a type declaration character (if one exist. For example, we could rewrite the
definition of Area to explicitly return a single as follows:
Private Function Area! (s1 as Single, s2 As Single)
Or
Private Function Area (s1 as Single, s2 as Single) As Single
We could also rewrite the definition of IsVolunteer88 as
Private Function IsVolunteer88() As Boolean
In this situation we cannot use a type declaration character because Boolean does not have
one.

Call by Value vs. Call by Reference


Two ways to invoke procedure calls in most programming languages are call by value
and call by reference. With cqall by reference, the caller gives the called procedure the ability
to directly access the caller’s data, and to modify that data if the called procedure so chooses.
When an argument is passed call by value, a copy of the argument’s value is paased. The called
procedure dcan manipulate that coy but canno t manipulate the caller’s data.
Call by reference is good for performance because it can eliminate the overhead of copying
large amount of data.
Call by reference can weaken security because the called procedure can modigy the caller’’s
data at will, possibly changing that data.
When an argument is passed call by value, a copy of that arguments value is made and passed.
Changes to the copy do not affect the original variable’s value in the caller. This prevents
accidental side effects that so greatly hinder the development of correct and reliable software
systems.
Call by value is potentially bad for performance if the data being passed is large, because
making a copy of that data takes time and consumes memory.

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:

Exit Sub and Exit Function


Statements Exit Sub and Exit Function alter the flow of control. Executing Exit Sub in a Sub
procedure causes an immediate exit from the procedure. Control is returned to the caller and
the next statement in sequence after the call is executed.

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:

Direction: Fill in the blanks


1. A procedure is invoked with ______.
2. Statements Exit Sub and Exit Function ______the flow of control.
3. __________ is good for performance because it can eliminate the overhead of copying
large amount of data.
4.
5. _____________ can be created with the add procedure. It could also be created by
typing the function procedure directly into the code window.
6. Visual Basic Procedures – (i.e. format$, IIf, Load-Picture, etc. ) are provided by
_________to perform common tasks.
7. ________ function causes immediate exit from a function procedure.
8. Private Sub cmdPrint_Click()

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:

1. Determine the output of the program


Public a, b, x As Integer ‘general declaration
Public Sub (Sum)
b=2
a=b
x =a+b
End Sub

Private Sub CmdPrint_Click()


Call Sum
Print “the sum of” & a & “and “ & b “is” & x
End Sub

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

Private Sub CmdPrint_Click()


Call Sum
Print “the Product of” & x & “and “ & b “is” & a
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

The picture shows a six element integer array


named numbers. Any one of these elements may
be referred to by giving the array name followed
by the element position number in parenthesis,
the first array element is at position number zero.
Thus, the fist element of numbers is referred to
as numbers(0), the second element of numbers is
referred to as numbers(1) and so on.
The position number contained within
parenthesis is more formally called an index. An
index must be a Long or a Long expression in the
range -2,147,483,648 to 2,147,483,648( any
floating-point number is rounded to the nearest
whole number).
If a program uses an expression as a index, then the expression is evaluated to determine the
value of index. For example, if we assume that a is 1 and b is 2, then the statement adds 2 to
numbers (3).
Let us examine array numbers in the picture above more closely. The array name is
numbers. Its six elements are referred to as numbers(0), numbers(1),
numbers(2)….numbers(5). The value of numbers(0) is 77, the value of numbers(1) is 68, the
value of numbers(2) is 55…. The value of numbers(5) is 89.
To print the sum of the values contained in the first three elements of numbers, we write
Print numbers(0) + numbers(1) +numbers(2)

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

Direction: provide your correct answer before each number


1. Numbers(10) has how many elements?
2. What is the array name of the question in number 1?
3. Provide the code on how to get the product of first 3 elements of the array in number1
4. An index of an element starts with?
5. What is an array?
6. The range of array index in Long expression?
7. What do you mean by sorting data?
8. Dim n(10) As Integer has 10 elements. True or false?
9. In declaring an Array, you can start with a number. True or False?
10. How to declare an Array?

21
Exercise 8

1. Create a program where you declare an array with 9 elements and get its average.

2. Create a program where you sort a values of ten element array

22
Reference:
Visual Basic 6: How to Program
Deitel & Deitel
T.R. Nietto

23

You might also like