1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” Herbert G. Mayer, PSU CS Status 8/5/2013 Initial content copied verbatim from.

Slides:



Advertisements
Similar presentations
Subprograms Functions Procedures. Subprograms A subprogram separates the performance of some task from the rest of the program. Benefits: “Divide and.
Advertisements

Sub and Function Procedures
Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)
Spring Semester 2013 Lecture 5
Lecture Set 4 Data Types and Variables Part B – Variables, Constants, Expressions Conversion Rules Options Strict, Option Explicit Scope of Definition.
The Web Warrior Guide to Web Design Technologies
1 CS 106, Winter 2009 Class 10, Section 4 Slides by: Dr. Cynthia A. Brown, Instructor section 4: Dr. Herbert G. Mayer,
1 CS 106, Winter 2009 Class 11, Section 4 Slides by: Dr. Cynthia A. Brown, Instructor section 4: Dr. Herbert G. Mayer,
Writing General Procedures Often you will encounter programming situations in which multiple procedures perform the same operation This condition can occur.
VBA Modules, Functions, Variables, and Constants
Example 2.
PSU CS 106 Computing Fundamentals II VB Subprograms & Functions HM 4/29/2008.
Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one procedure Therefore,
Wed/Fri Week 2 Functions! What are they? What do they look like in JavaScript? What are they good for? How do I use them? Some examples… Mini-Lab 1!!!
VB .NET Programming Fundamentals
Apply Sub Procedures/Methods and User Defined Functions
1 CS 106 Computing Fundamentals II Chapter 16 “Naming In Excel” Herbert G. Mayer, PSU CS Status 7/6/2013 Initial content copied verbatim from CS 106 material.
1 CS 106 Computing Fundamentals II Chapter 17 “Introduction To VBA” Herbert G. Mayer, PSU CS status 6/30/2013 Initial content copied verbatim from CS 106.
Why to Create a Procedure
1 CS 106 Computing Fundamentals II Chapter 25 “Variables, Assignment Statement” Herbert G. Mayer, PSU CS Status 7/4/2013 Initial content copied verbatim.
1 CS 106 Computing Fundamentals II Chapter 7 “Showing Developer Tab” Herbert G. Mayer, PSU CS status 6/17/2013 Initial content copied verbatim from CS.
1 CS 106 Computing Fundamentals II Chapter 4 “Excel Basics for Mac” Herbert G. Mayer, PSU CS status 6/27/2013 Initial content copied verbatim from CS 106.
CS0004: Introduction to Programming Subprocedures and Modular Design.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
1 CS 106 Computing Fundamentals II Chapter 61 “Loops” Herbert G. Mayer, PSU CS Status 7/29/2013 Initial content copied verbatim from CS 106 material developed.
CPS120: Introduction to Computer Science Decision Making in Programs.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
1 CS 106 Computing Fundamentals II Chapter 84 “Array Formulae” Herbert G. Mayer, PSU CS status 6/14/2013 Initial content copied verbatim from CS 106 material.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 CS 106 Computing Fundamentals II Chapter 23 “Controls And Events” Herbert G. Mayer, PSU CS Status 7/5/2013 Initial content copied verbatim from CS 106.
PSU CS 106 Computing Fundamentals II VB Declarations HM 5/4/2008.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
1 CS 106 Computing Fundamentals II Chapter 211 “Coding And Debugging” Herbert G. Mayer, PSU CS status 6/29/2013 Initial content copied verbatim from CS.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 CS 106 Computing Fundamentals II Chapter 210 “Adding Controls to User Forms” Herbert G. Mayer, PSU CS Status 7/4/2013 Initial content copied verbatim.
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
ECE 103 Engineering Programming Chapter 31 C Scopes Herbert G. Mayer, PSU CS Status 8/1/2015 Initial content copied verbatim from ECE 103 material developed.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 CS 106 Computing Fundamentals II Chapter 28 “Scope” Herbert G. Mayer, PSU CS Status 7/14/2013 Initial content copied verbatim from CS 106 material developed.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
CS0004: Introduction to Programming
Programming Right from the Start with Visual Basic .NET 1/e
Subprograms Functions Procedures.
CS 106 Computing Fundamentals II Chapter 5 “Excel Basics for Windows”
COMP 170 – Introduction to Object Oriented Programming
CS 106 Computing Fundamentals II Chapter 35 “Controls For Choices”
Functions Chapter 6-Part 2.
CS 106 Computing Fundamentals II Chapter 77 “Algorithm”
CS 106 Computing Fundamentals II Chapter 33 “Conditional Statements”
6 Chapter Functions.
CS 106 Computing Fundamentals II Chapter 73 “Ranges”
CS 106 Computing Fundamentals II Chapter 66 “Working With Strings”
Introduction to Visual Programming
Herbert G. Mayer, PSU CS Status 8/2/2013
Chapter 9: Value-Returning Functions
CS 106 Computing Fundamentals II Chapter 64 “For Loop Variations”
Methods.
CS 106 Computing Fundamentals II Chapter 69 “Event Loop”
ITM 352 Functions.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” Herbert G. Mayer, PSU CS Status 8/5/2013 Initial content copied verbatim from CS 106 material developed by CS professors: Cynthia Brown & Robert Martin

2 Syllabus Procedures In VBA Procedures In VBA Two Aspects of Procedures Two Aspects of Procedures Definition vs. Call Definition vs. Call Sub Procedure Definition Sub Procedure Definition Procedure Name Procedure Name Parameters Parameters Procedure Body Procedure Body Functions Functions

3 Procedures in VBA Main idea: encapsulate code in its own procedureMain idea: encapsulate code in its own procedure Two kinds: Sub Procedures and FunctionsTwo kinds: Sub Procedures and Functions We’ve already seen event procedures, which are sub procedures, and we’ve seen Excel user functionsWe’ve already seen event procedures, which are sub procedures, and we’ve seen Excel user functions Why create more procedures?Why create more procedures? If we are repeatedly doing the same task, we can write the code in one place, give that “place” a name, and then call the the name code –i.e. the procedure or function-- repeatedly If a program is long and complex, we can break it into understandable parts, AKA logical modules 3

4 Analogous to Problem-Solving Master a particular task that comes up repeatedly so you don’t have to think about how it works each time it occursMaster a particular task that comes up repeatedly so you don’t have to think about how it works each time it occurs Break a large, complex problem into smaller, more manageable partsBreak a large, complex problem into smaller, more manageable parts 4

5 Two Aspects of Procedures The Definition: a separate piece of code where the procedure is defined, as we do with event proceduresThe Definition: a separate piece of code where the procedure is defined, as we do with event procedures The Procedure Call: A piece of code that invokes a procedure from another place, e.g. a function, procedure, or event procedureThe Procedure Call: A piece of code that invokes a procedure from another place, e.g. a function, procedure, or event procedure Event procedures, like Form_Initialize or btnProcess_Click, are invoked when the event happens, like loading the form or clickingEvent procedures, like Form_Initialize or btnProcess_Click, are invoked when the event happens, like loading the form or clicking The explicit call is another method of invoking --or activating-- the sub or functionThe explicit call is another method of invoking --or activating-- the sub or function 5

6 Definition vs. Call The procedure definition is the source code that specifies to the computer (compiler, interpreter) the name, the parameters, the return value for functions, and the actions to perform when calledThe procedure definition is the source code that specifies to the computer (compiler, interpreter) the name, the parameters, the return value for functions, and the actions to perform when called The procedure call makes the procedure actually happenThe procedure call makes the procedure actually happen When done, the calleé returns to the place after the callWhen done, the calleé returns to the place after the call 6

7 Sub Procedure Definition A sub procedure has a name, possibly some formal parameters, and a body; always requires a pair of parentheses ( ) for the formal parameter list: Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Dim answer As Double Dim answer As Double answer = param1 + param2 answer = param1 + param2 lstResults.AddItem( "param1 = " & CStr( param1 ) & “param2 = ” & CStr( param2 ) ) lstResults.AddItem( "param1 = " & CStr( param1 ) & “param2 = ” & CStr( param2 ) ) lstResults.AddItem( "answer = " & CStr( answer ) ) lstResults.AddItem( "answer = " & CStr( answer ) ) End Sub 7

8 Procedure Name Consider the header:Consider the header: Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double )Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) PrintAnswer() is the name of the procedure. A good convention is to start procedure names with capital letters, variable names with lower-case lettersPrintAnswer() is the name of the procedure. A good convention is to start procedure names with capital letters, variable names with lower-case letters A good convention is to use a verb in the procedure name; one that reflects what the procedure doesA good convention is to use a verb in the procedure name; one that reflects what the procedure does 8

9 Parameters Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) The formal parameters are param1 and param2The formal parameters are param1 and param2 A ByVal parameter is similar to a local variableA ByVal parameter is similar to a local variable Assignments to the formal do NOT change the actual!Assignments to the formal do NOT change the actual! Its type is declared in the header -these are of type DoubleIts type is declared in the header -these are of type Double A formal parameter’s initial value is set in the procedure call; we say the formal parameter is bound to the actual parameter at the place of callA formal parameter’s initial value is set in the procedure call; we say the formal parameter is bound to the actual parameter at the place of call Changes to ByVal parameters only affect the formal parameter during the call and only inside the sub scopeChanges to ByVal parameters only affect the formal parameter during the call and only inside the sub scope 9

10 More on Formal Parameters Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Recall that variable names are used in two waysRecall that variable names are used in two ways On the right side of an assignment statement, a variable name represents a value On the left side, it represents a location where a value can be stored Instead of passing a value to a parameter, we could pass a location, essentially hooking up the formal parameter to a variable elsewhere in the program; this would be a reference parameterInstead of passing a value to a parameter, we could pass a location, essentially hooking up the formal parameter to a variable elsewhere in the program; this would be a reference parameter If you don’t specify ByVal, VBA will use pass by reference as a defaultIf you don’t specify ByVal, VBA will use pass by reference as a default Reference parameters are used when we want the procedure to change a value elsewhere in the program, e.g. the actualReference parameters are used when we want the procedure to change a value elsewhere in the program, e.g. the actual 10

11 Procedure Body Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Dim answer As Double Dim answer As Double answer = param1 + param2 answer = param1 + param2 lstResults.AddItem( "answer = " & CStr( answer ) ) End Sub Note the local variable answer The result of calling this procedure is to make some text appear in list box lstResults 11

12 Sub Procedure Call A sub procedure is called from elsewhere in the program, for example from within an event procedureA sub procedure is called from elsewhere in the program, for example from within an event procedure The call uses the procedure name and arguments --AKA actual parametersThe call uses the procedure name and arguments --AKA actual parameters A sub procedure call is a statementA sub procedure call is a statement Here’s what it might look like:Here’s what it might look like: Dim varA, varB As Double Dim varA, varB As Double varA = CDbl( txtArg1.Text ) varA = CDbl( txtArg1.Text ) varB = CDbl( txtArg2.Text ) varB = CDbl( txtArg2.Text )... And then:... And then: Call PrintAnswer( varA, varB – 1 ) Call PrintAnswer( varA, varB – 1 ) 12

13 Actual vs. Formal Parameter Actual parameters are also referred to as: ArgumentsActual parameters are also referred to as: Arguments Arguments are used to feed information to the procedureArguments are used to feed information to the procedure They are connected with the formal parameters by position; referred to as bindingThey are connected with the formal parameters by position; referred to as binding The actual is bound to the formal at the place of callThe actual is bound to the formal at the place of call 13

14 Examples With this procedure code: Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Dim answer As Double Dim answer As Double answer = param1 + param2 answer = param1 + param2 lstResults.AddItem( "answer = " & CStr( answer ) ) lstResults.AddItem( "answer = " & CStr( answer ) ) End Sub The procedure call: Call PrintAnswer( 3, 5 ) sets param1 = 3 and param2 = 5 Call PrintAnswer( x, y ) sets param1 = x and param2 = y, whatever the values of x and y happen to be 14

15 Functions Functions have one extra element: they return a valueFunctions have one extra element: they return a value We’ve seen examples of functions built into VBA: for example, Format, or any user functionWe’ve seen examples of functions built into VBA: for example, Format, or any user function A function can have parametersA function can have parameters A function returns a result that has a particular data typeA function returns a result that has a particular data type A function call is an expression with a data typeA function call is an expression with a data type 15

16 Function Definition A function procedure definition has a name, possible formal parameters, a body of code, and a typeA function procedure definition has a name, possible formal parameters, a body of code, and a type Example function definition:Example function definition: Function ComputeAnswer( ByVal param1 As Double, ByVal param2 As Double) As Double ComputeAnswer = param1 + param2 ComputeAnswer = param1 + param2 End Function 16

17 About the Function Definition To set the value returned by the function, we use an assignment to the name of the function:To set the value returned by the function, we use an assignment to the name of the function: Specifying the type of the function at the end of the header appears to be optional, even with Option Explicit turned on, but it is a good idea to do itSpecifying the type of the function at the end of the header appears to be optional, even with Option Explicit turned on, but it is a good idea to do it Note the function just computes a value and returns at the end of the function bodyNote the function just computes a value and returns at the end of the function body 17

18 Function Call A function is called from elsewhere in the program, for example from within some event procedureA function is called from elsewhere in the program, for example from within some event procedure The call uses the function name and arguments (AKA actual parameters), and returns a valueThe call uses the function name and arguments (AKA actual parameters), and returns a value Here’s what it might look like:Here’s what it might look like: varA = CDbl( txtArg1.Text ) varA = CDbl( txtArg1.Text ) varB = CDbl( txtArg2.Text ) varB = CDbl( txtArg2.Text ) answer = ComputeAnswer( varA, varB ) answer = ComputeAnswer( varA, varB ) 18

19 What Happens in Procedure Call The expressions for the argument values are evaluated, and the formal parameters are set to those valuesThe expressions for the argument values are evaluated, and the formal parameters are set to those values The Dim statements for the procedure are used to create any local variablesThe Dim statements for the procedure are used to create any local variables The code for the procedure is executedThe code for the procedure is executed Control returns to the line after the procedure call (sub procedure), or to the line of the call with the returned value (function)Control returns to the line after the procedure call (sub procedure), or to the line of the call with the returned value (function) 19

20 Control Flow for Procedure Call Some program code Procedure call More program code Procedure code Set parameter values Return value (function)

21 Procedures and Program Structure The main program in the procedure demo is the event procedure for btnResultsThe main program in the procedure demo is the event procedure for btnResults We could have simply put all the code in this procedureWe could have simply put all the code in this procedure To make our program better structured and more readable, though, break major step into their own procedures or functionsTo make our program better structured and more readable, though, break major step into their own procedures or functions 21