bacs 287 programming fundamentals 5. bacs 287 programming fundamentals this lecture introduces the...
DESCRIPTION
BACS 287 Procedures A procedure is a set of instructions that perform a particular service. (It is a module in structured programming terminology.) There are 2 generic categories of procedures: built-in (intrinsic) and user- defined. There are also 3 types of procedures: Functions, Subroutines, and Property procedures.TRANSCRIPT
BACS 287
BACS 287
Programming Fundamentals 5
BACS 287
Programming Fundamentals
This lecture introduces the following topics:– Procedures
Built-in Functions User-defined Procedures
– Functions– Subroutines
Passing data via Arguments
BACS 287
Procedures A procedure is a set of instructions that
perform a particular service. (It is a module in structured programming terminology.)
There are 2 generic categories of procedures: built-in (intrinsic) and user-defined.
There are also 3 types of procedures: Functions, Subroutines, and Property procedures.
BACS 287
Procedures All built-in Visual Basic procedures are of the
function type. User-defined procedures can be either the
function or subroutine type. Functions return a value. Subroutines do not
return a value. Functions and subroutines are capable of
performing the same kind of work. They do it in slightly different ways.
BACS 287
Procedures
BACS 287
Procedures versus Methods
Methods are also a type of procedure They perform work for a specific type of object. All methods are procedures, but not all procedures
are methods. Methods differ from procedures in that a method may
only be called from a specific object while generic procedures can be called from any object.
Ex: Debug.write, intX.ToString, strY.Trim
BACS 287
Built-In Functions
Built-in (intrinsic) functions are used anywhere an expression is valid. For example:datX = Date ’Date’ is an intrinsic function
Some functions require additional information (called arguments).sngX = Sqrt(10)strX = MsgBox(“Prompt”,vbYes,”Error”)sngX = Cos(Rnd)
BACS 287
Built-In Functions
VB provides many built-in functions.Date - returns current dateFormat - date or number converted to a text stringInputBox - text entered into a dialog box by userMsgBox - text displayed to user at run-timeLen - number of characters in a text stringMid - selected portion of a stringRnd - random numberInStr – find character(s) in a stringVal - string converted to a numberand many more.....
BACS 287
Built-In Functions Built-in functions are provided by Visual Basic as a
convenience to the programmer. Most could be written as user-defined functions, but
there is no need to do this since they are already written and tested.
You should be familiar with the built-in functions provided by the language to improve personal productivity.
A number of built-in functions are also available as methods in VB .Net.
BACS 287
Built-In Methods
Objects in VB have methods associated with them.
Methods give VB objects functionality (that is, it allows them to act upon data).
Many VB methods do things that can also be done with functions.
Using methods is preferred because they are compatible with other .NET languages.
BACS 287
Built-In Methods
VB provides many methods.Number.toString – converts the number to a stringString.toInt32 – converts the string to an integer data typeString.toInt16 – converts the string to a short data typeString.length – returns the length of the string variableString.split – places each string component into an array elementMath.Sqrt(Number) – returns the square root of the numberMyArray.count – returns the number of elements in the arrayMyArray.sort – sorts the elements of an arrayMyArray.reverse – reverses the order of elements in an arrayand many more.....
BACS 287
User-Defined Procedures
If a built-in function does not exist to perform needed work, you can build your own as a user-defined procedure.
User-defined procedures can be either the function type or the subroutine type.
They can be defined in form modules and code modules.
BACS 287
User-Defined Functions
Function Syntax:
[Public | Private] [Friend] Function function-name [(args)] [As type][statements][function-name = expression] or [Return expression][Exit Function][statements][function-name = expression]
End Function
BACS 287
User-Defined Function Example 1
Private Function Divide_Num (byVal sngX as single, byVal sngY as single) as singleIf sngY = 0 then
Return 0Exit Function
End IFReturn (sngX / sngY)
End Function You return a value to the calling routine by assigning
the return value to the function name.
BACS 287
User-Defined Function Example 2
Public Function Time_Check()as booleanIf TimeValue(Now) < #08:00:00# then
Return vbFalseElse
Return vbTrueEnd IF
End Function Checks the current system time. If its before 8 AM, it
returns false, otherwise it returns true.
BACS 287
User-Defined Functions
Functions are called by using their name in an expression. The arguments are enclosed in () and are separated by commas.sngX = Divide_Num(15.2, 17.3)
If there are no arguments, you can leave off the ().blnX = System_Status
BACS 287
User-Defined Functions
User-defined functions have data types. This determines the type of the return value. If not specified, the return type is object.
Since functions return values, they can be used to build up larger (more complex) statements.If Check_It(strInput) then ...
BACS 287
User-Defined Sub Procedures
There are 2 types of sub procedures: General procedures and Event procedures.
General procedures are invoked by the programmer specifically calling them in the program.
Event procedures are automatically invoked by the system when a specific event occurs. Event procedures have private scope only.
BACS 287
Sub Procedures
Sub Procedure Syntax:
[Public | Private] [Friend] Sub subroutine-name [(args)] [statements][Exit Sub] or [Return][statements]
End Sub
BACS 287
Sub Procedure Example 1
Private Sub Compute_Area (byVal sngLen_ as single,byVal sngWidth as single)Dim dblArea as DoubleIf sngLen = 0 or sngWidth = 0 then
Exit SubEnd IfdblArea = sngLen * sngWidthSystem.Console.WriteLine dblArea
End Sub
BACS 287
Sub Procedure Example 2
Public Sub Beep_Bell ()Dim intX as integerDim intCnt as integerintX = InputBox(“How Many Beeps?”)For intCnt = 1 to intX
BeepNext intCnt
End Sub
BACS 287
Sub Procedures
General sub procedures are called with the Call statement.Call Compute_Area(11, 21)Call My_SubProcuedure(intX)
Because they do not return a value, subroutines cannot be used to build expressions.
BACS 287
User-Defined Procedures
Many times you can use either a function or a subroutine procedure to accomplish the same task.
Professional programmers generally use functions for most user-defined procedures because you can test the success of the execution and proceed appropriately.
BACS 287
Arguments
There are 2 basic methods of passing data to a user-defined procedure: Increase the variable scope or use arguments.
The preferred method is to pass data to the procedure via arguments.
This allow you to better control the data that is used by the procedure.
BACS 287
Arguments
Passing Arguments to Procedures:– Argument Data Type– Passing Arguments by Value– Passing Arguments by Reference– Optional Arguments– Indefinite Number of Arguments– Named Arguments
BACS 287
Argument Data Type
All arguments have a data type. If you do not declare a specific type, it is object by default.
Function X (byVal strX as string, byVal objY as object) ...
Sub Y (byVal datZ as date, byVal sngR as single) ...
Function Z (byVal intX as integer, byVal objG) as single ...
BACS 287
Passing Arguments by Value
A copy of the variable is passed to the procedure. Any changes affect only the copy, not the original. This is the default.
Sub X (ByVal intY as integer)
Function Y (objX, ByVal strY as_ string)as Integer
BACS 287
Passing Arguments by Reference
The actual variable is passed to the procedure. Any changes to the variable affect the original.
Sub R (byRef intY as integer)
Function Z (byRef objX, byRef blnG as boolean)as Integer
BACS 287
byRef Arguments
When arguments are passed byRef, any changes made to the value of the variable by the procedure are visible to the entire scope of the variable.
This means that a subroutine can return a value to its calling code if variables are passed ‘byRef’.
Also, this would be somewhat more efficient if the things being passed were large (i.e., objects).
Still better to do this with Functions if you have no overriding reason to use byRef.
BACS 287
Using Optional Arguments
You can specify that arguments be optional. All optional arguments must supply a default value.
This value cannot be a variable. Once you define one optional argument, all
subsequent arguments must be optional also.Function A (byVal intX as integer, Optional byVal
intY as integer = 2, Optional byVal strZ as string = “test”) ...
To call this function: Answer = A(4,,”string”)
BACS 287
Using Indefinite Arguments
You can allow an arbitrary number of arguments if the last argument is specified as a ParmArray.
Sub mySum (byRef intSum as integer, _ byVal ParmArray intNums() as integer)
Dim intX as integerFor Each intX in intNums
intSum = intSum + intNums(intX)Next intX
End Sub
BACS 287
Using Indefinite Arguments
There can only be one ParmArray in a procedure and it must be the last thing defined.
It must be passed byVal. The code in the procedure must treat it as a
one-dimension array. All arguments preceding the ParmArray word
must be required (that is, no Optional arguments allowed).
BACS 287
Named Arguments
You can specify named arguments by using the := operator in the procedure call.
Function X (byVal strX as string, byVal intX as integer) as Boolean
...
Return_Value = X(intX := 7, strX := “My Name”)
BACS 287
In-Class Example 1
Write a user-defined function called My_Length to accept a string and return the length of that string to the user.
BACS 287
Answer #1
Private Function My_Length (byVal strInput as string) as IntegerReturn len(strInput)
End Function
BACS 287
In-Class Example #2
Modify the previous example to return “a big string” if the string is more than 10 characters long. Return “a small string” if it is 10 or less.
BACS 287
Answer #2
Private Function My_Length (byVal strInput as string) as StringDim intLen as integerintLen = len(strInput)If intLen > 10 then
Return “a big string”else
Return “a small string”End If
End Function
BACS 287
In-Class Example #3
Write a user-defined sub procedure called My_Clear to clear the computer screen when called. (Note, the ‘cls’ function does this.) Next, write code to call the procedure.
BACS 287
Answer #3
Private Sub My_Clear ()cls
End Sub--------------------------Call My_Clear()