370 likes | 450 Views
CIS 115 Lecture 6. Procedures and Functions. Procedure. A set or block of code statements that is given a name so that it can be invoked by another part of the program Building blocks of applications Modular Programming - Break large problems down into smaller ones
E N D
CIS 115 Lecture 6 Procedures and Functions
Procedure • A set or block of code statements that is given a name so that it can be invoked by another part of the program • Building blocks of applications • Modular Programming - Break large problems down into smaller ones • Used for Repeated or Shared Tasks - Container for code to be called multiple times • Makes the code easier to understand
Procedure (cont.) • General Form: Declaration statement (Procedure Header) Code statements End statement (Procedure Close) • Other names used by different programming languages to refer to procedures • Method • Subroutine • Function
Procedure Types in Visual Basic • (Event) Sub Procedure • Performs a logical action • Does not return a value • Executes when event occurs - not “Called” from code • (Gen Purpose) Sub Procedure • Performs a logical action • Does not return a value • Must be “Called” from other code • Function • Performs Calculation • Does return a Value • Must be “Called” from other code
Sub Procedure • An abbreviation of the older term subroutine • Sub procedures are written to perform specific tasks • General purpose Sub procedures are not triggered by events but called from statements in some other location • Event procedures are special Sub procedures that are not called from statements, but rather are executed when a corresponding event occurs
Sub Procedure Syntax Public Sub SubName (parameterName As DataType) ‘*procedure code*’ End Sub • Public (optional) - the AccessSpecifier - establishes accessibility to the program • Sub and End - keywords • SubName - name used to refer to Sub - rules for naming Sub Procedures are the same as for variables, except Sub procedure names begin with uppercase letters. • ParameterList - a list of variables or values being passed to the sub procedure
Procedure Call • Used to invoke (cause to execute) a procedure • Syntax: Call ProcedureName (Arguments) • Call (optional) - keyword • ProcedureName - name of Sub (or Function) to invoke • Arguments (if any, included in parenthesis) - Data passed to the procedure • Example: • Call Power (5, 2) OR • Power (5, 2)
Arguments • Values, Variables or Expressions placed in parentheses in a Call statement • Contain data needed by the procedure • The data is passed to the procedure when it is called • We’ve already done this with the Val functions • intNumber = Val(txtInput.Text) • Calls Val function and passes txtInput.Text
Parameters • Declared in procedure header (in parentheses after ProcedureName) (can have 0 or more) • Must be declared (similar to a variable) in the procedure header in order to accept an argument • Created as a local variable for the procedure • Syntax: (parameterName As DataType) • parameterName - name used to refer to parameter in procedure code (same naming rules as variables) • As - keyword • Data Type - type of value the parameter will contain
Passing Arguments to Parameters • When the procedure is called, the values of the arguments (in the call statement) are passed into (copied to) the corresponding parameters (in the procedure header). • Data needed by the Sub (or Function) and sent by the Call statement • The number of arguments and parameters must match. • The data type of each argument must match its corresponding parameter.
Sub Procedure Example Private Sub btnResult_Click() ‘* event procedure Dim lng As Single, wid As Single lng = 5 wid = 10 Call ComputeArea(lng, wid) ‘* call to sub End Sub Sub ComputeArea(Length As Single, Width As Single) Dim Area As Single Area = Length * Width MsgBox(“Area = “ & Area) End Sub
Pass by Value or Pass by Reference • Arguments are usually passed ByVal • A copy of the value of the argument is stored in the parameter l0cation • Any changes in that value made by the called procedure are made only to the parameter location – original argument from calling procedure will not change • Arguments (variables) can also be passed ByRef • The reference (memory location) of the variable used as the argument is stored in the Parameter l0cation • Parameter references (points to) the original variable’s (argument’s) memory location • Any changes made by the called procedure are made to the original variable (argument) from calling procedure
ByVal/ByRef Example At declaration intX 5 intY 5 Sub ChangeValue(ByVal intY As Integer) intY = 10 End Sub .................. ChangeValue(dim intX as integer = 5) .................. Result: intY = 10 intX = 5 _______________________________________________________ Sub ChangeValue(ByRef intY As Integer) intY = 10 End Sub .................. ChangeValue(intX = 5) .................. Result: intY = intX = 10 At termination intX 5 intY 10 At declaration intX 5 intY At termination intX 10 intY
Sub Procedure Example • Write a Sub Procedure named Power with 2 integer parameters (originally from text boxes). The sub should calculate the first parameter raised to the second parameter and display the results in a message box. • Obtain input • Call Sub
Functions • Procedures that return a Value • Same form as Sub except must return a value • Must have an associated data type to tell program what type of data it will return • One of the numeric types String Boolean Char Object Etc. • Must include a “Return” statement or Assign a value to the name of the function • This statement causes the function to end and return the appropriate value
Function Syntax Public Function FunctionName(parameterName As DataType) As returnType ‘* function code Return Value ‘* OR FunctionName = Value End Function • Public (optional) - the AccessSpecifier • Function and End – keywords • FunctionName - name used to refer to function - Function procedure names begin with uppercase letters. • ParameterList - list of values being passed to the function • returnType - DataType of the value returned by the function • Return Value – required statement to return data to caller
Using Functions • Functions ALWAYS return a value • When calling a function, you MUST do something with the value that is returned • Right hand side of an assignment statement • Part of an Output Statement • Must be suitable to the particular return type • A Function can be used in any statement where a literal or variable of the particular return type could be used
Function Example Private Sub btnResult_Click() ‘* event procedure Dim lng As Single, wid As Single, area As Single lng = 5 wid = 10 area = ComputeArea(lng, wid) ‘* call to Function MsgBox(“Area = “ & area) End Sub Function ComputeArea(L As Single, W As Single) As Single Dim A As Single A = L * W Return A End Sub
Function Example • Write a function named Quotient with 2 Integer parameters (originally from text boxes) and a Double return type. The function should calculate the first parameter divided by the second and return the result. • Obtain Input • Call the function, • Display results in a message box.
Intrinsic Functions • Pre-coded Functions provided by VB • Used to improve developer productivity – less time spent coding • Broad Range of Built-In Functions • Math calculations • Formatting • Time/Date functions • To find a function open the Object Browser • F2 OR • Select View Menu then Object Browser option • String manipulation • Many more
Numeric Functions • Rnd - Returns a number between 0 and 1 (excluding 1) • Int(6 * Rnd) + 1 ‘* Returns a random integer from 1 through 6 • Sqr(n) - Returns the square root of the number n • IsNumeric(s) - Returns true if the item s can be converted to a number, false if not • IsNumeric (“23.5”) ‘* Returns True • IsNumeric(“hello”) ‘* Returns False • Round(n, r) - Returns the number n rounded to r decimal places • Round(6.3819, 3) ‘* Returns 6.382 • Int(n) - Returns the integer part of the number n • Int (123.456) ‘* Returns 123
Formatting Functions • FormatNumber(n, [r]) - returns number n formatted with commas and r decimal places (default is 2 decimal places) • FormatNumber(8765.4537) ‘* Returns 8,765.45 • FormatNumber(8765.4537, 3) ‘* Returns 8,765.454 • FormatCurrency(n, [r]) – returns number n formatted with dollar sign, commas, and r decimal places (default 2) • FormatCurrency(65) ‘* Returns $65.00 • FormatCurrency(65273.815) ‘* Returns $65,273.82 • FormatPercent(n, [r]) - returns number n formatted as percent with r decimal places (default 2) • FormatPercent(.658) ‘* Returns 65.80% • FormatCurrency(8.20) ‘* Returns 820.00%
Val(s) - Returns the numbers contained in the string s (stops at 1st non numeric item) Val(“123abc”) ‘* Returns 123 Str(n) - Converts number n to a String Str(123) ‘* Returns “123” Specific conversion functions for each data type CBool ( expr ) CByte ( expr ) CChar ( expr ) CDate ( expr ) CDbl ( expr ) CDec ( expr ) CInt ( expr ) CLng ( expr ) CObj ( expr ) CShort ( expr ) CSng ( expr ) CStr ( expr ) Conversion Functions
Conversion Functions • Cint(n) - converts number n to an integer • Rounding can be done with the CInt function • CInt(12.4) ‘* Returns 12 • CInt(12.5) ‘* Returns 13 • CStr(n) - converts number n to a string • CStr(26) ‘* Returns “26” • CDec(n) - converts number n to a decimal value • Dim decPay as Decimal = CDec(“$1,500”) • CDate(s) – converts string s to a date • Dim datHired as Date = CDate(“05/10/2005”)
Invalid Conversions • Conversion functions can fail • String “xyz” can’t be converted to a number Dim dblSalary as Double = CDbl(“xyz”) • There’s no day 35 in the month of May Dim datHired as Date = CDate(“05/35/2005”) • These failed conversions cause a runtime error called an invalid cast exception
String Functions • Left(s, n) - Returns the number of characters specified by n, starting at the beginning of the string s • Left(“Penguin”, 4) ‘* Returns “Peng” • Right(s, n) - Returns the number of characters specified by n, starting from the end of the string s • Right(“Penguin”, 5) ‘* Returns “nguin” • Mid(s, n, r) - Returns the substring from string s, starting at the position indicated by n and continuing for the length specified by r • Mid(“Penguin Penguin”, 5, 6 ) ‘* Returns “in Pen”
String Functions • UCase(s) - Converts any lowercase letters in string s to uppercase • UCase(“Yes”) ‘* Returns “YES” • Lcase(s) - Converts any uppercase letters in string s to lowercase • UCase(“Yes”) ‘* Returns “yes” • InStr(s, t) - Searches for the first occurrence of string t in string s and returns the starting position in s at which t is found, -1 if not found • InStr(“John Smith”, “h”) ‘* Returns 2 • Len(s) - Returns the number of characters in string s • Len(“Yes Yes”) ‘* Returns 7
Input Box • InputBox • Prompts the user for keyboard input • Input is returned to the program for processing • Syntax: • Result = InputBox (prompt, [title]) • Example: • strInput = InputBox (“Enter Input”) • strName = InputBox (“What is your name”, “Name”)
Message Box • MsgBox • Displays a message in a dialog box • Syntax • MsgBox (prompt, [title]) • Example • MsgBox (“Hello World”, “Chapter 7_1”) • MsgBox (“The Result is “ & Result)
Example • Create an application that adds items to a sales receipt one at a time using an input text box and a button. Each time the button is pressed, the new item price should be added to a list box control which acts as a receipt. The program should also contain output labels for subtotal, sales tax and total that should be updated when an item is added to the receipt. (Ensure that the prices are numeric and that the output is formatted to currency)
Code • Variables • Subtotal • Tax • Total • What Data Types? • Where to Declare?
Add to Receipt Button Event • Read in Data from Text Box • Convert to Number • CDbl • Val • Add to ListBox • Formatted as Currency • Update Subtotal, Tax, and Total Variables • Update Output Displays
Convert to Number Format to Currency Format to Currency
Example Write a VB application to have the user input a first name, middle name, and last name. Produce an output string stating the full name and the initials (with periods). Be sure that each name and initial is capitalized. Format and display the output in a label. Use 3 separate sub procedures to store input, build output string and display output. Use a function to capitalize a single name and a function to produce the formatted initials from all three names.
Homework • Homework 4 • Visual Basic – Procedures and Functions • See handout for details and due date • Questions?