37
CIS 115 Lecture 6

Procedures and Functions

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: Procedures and Functions

CIS 115 Lecture 6

Page 2: Procedures and Functions

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 applicationsModular Programming - Break large

problems down into smaller onesUsed for Repeated or Shared Tasks -

Container for code to be called multiple times

Makes the code easier to understand

Page 3: Procedures and Functions

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

Page 4: Procedures and Functions

(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

Page 5: Procedures and Functions

An abbreviation of the older term subroutineSub procedures are written to perform

specific tasksGeneral 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

Page 6: Procedures and Functions

Public Sub SubName (parameterName As DataType)

‘*procedure code*’End SubPublic (optional) - the AccessSpecifier - establishes

accessibility to the programSub and End - keywordsSubName - 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

Page 7: Procedures and Functions

Used to invoke (cause to execute) a procedureSyntax: Call ProcedureName (Arguments)

Call (optional) - keyword ProcedureName - name of Sub (or Function) to invoke Arguments (if any, included in parenthesis) - Data

passed to the procedureExample:

Call Power (5, 2) OR

Power (5, 2)

Page 8: Procedures and Functions

8

Values, Variables or Expressions placed in parentheses in a Call statement

Contain data needed by the procedureThe 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

Page 9: Procedures and Functions

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 procedureSyntax: (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

Page 10: Procedures and Functions

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.

10

Page 11: Procedures and Functions

Private Sub btnResult_Click() ‘* event procedureDim lng As Single, wid As Single

lng = 5 wid = 10 Call ComputeArea(lng, wid) ‘* call to subEnd Sub

Sub ComputeArea(Length As Single, Width As Single) Dim Area As Single Area = Length * Width MsgBox(“Area = “ & Area)End Sub

Page 12: Procedures and Functions

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

Page 13: Procedures and Functions

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 declarationintX 5 intY 5

At declarationintX 5 intY

At terminationintX 10 intY

At terminationintX 5 intY 10

Page 14: Procedures and Functions

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 inputCall Sub

Page 15: Procedures and Functions

Procedures that return a ValueSame 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 CharObject 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

Page 16: Procedures and Functions

Public Function FunctionName (parameterName As DataType)

As returnType‘* function code Return Value ‘* OR FunctionName = Value

End FunctionPublic (optional) - the AccessSpecifierFunction and End – keywordsFunctionName - 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

functionReturn Value – required statement to return data to caller

Page 17: Procedures and Functions

Functions ALWAYS return a valueWhen 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

Page 18: Procedures and Functions

Private Sub btnResult_Click() ‘* event procedureDim 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 AEnd Sub

Page 19: Procedures and Functions

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 InputCall the function, Display results in a message box.

Page 20: Procedures and Functions

Pre-coded Functions provided by VBUsed to improve developer productivity – less

time spent codingBroad 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

Page 21: Procedures and 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

Page 22: Procedures and 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%

Page 23: Procedures and Functions

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 )

Page 24: Procedures and 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”)

Page 25: Procedures and Functions

Conversion functions can fail String “xyz” can’t be converted to a

numberDim dblSalary as Double = CDbl(“xyz”)

There’s no day 35 in the month of MayDim datHired as Date = CDate(“05/35/2005”)

These failed conversions cause a runtime error called an invalid cast exception

Page 26: Procedures and 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”

Page 27: Procedures and 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

Page 28: Procedures and Functions

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”)

Page 29: Procedures and Functions

MsgBox Displays a message in a dialog box

Syntax MsgBox (prompt, [title])

Example MsgBox (“Hello World”, “Chapter 7_1”) MsgBox (“The Result is “ & Result)

Page 30: Procedures and Functions

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)

Page 31: Procedures and Functions

TASK OBJECT EVENT

Input Price Text Box, Label None

Display Receipt List Box None

Display Subtotal Label, Label None

Display Sales Tax Label, Label None

Display Total Label, Label None

Add Item to Receipt Button Click

Exit Button Click

Page 32: Procedures and Functions
Page 33: Procedures and Functions

Variables Subtotal Tax Total

What Data Types?Where to Declare?

Page 34: Procedures and Functions

Read in Data from Text BoxConvert to Number

CDbl Val

Add to ListBox Formatted as Currency

Update Subtotal, Tax, and Total Variables

Update Output Displays

Page 35: Procedures and Functions

Convert to Number

Format to Currency

Format to Currency

Page 36: Procedures and Functions

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.

Page 37: Procedures and Functions

Homework 4 Visual Basic – Procedures and Functions See handout for details and due date Questions?