Chapter 6 Procedures and Functions Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI 3131.01.

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 6- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Advertisements

Chapter 6, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 6 Sub Procedures And Functions.
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 6 Procedures and Functions.
Sub and Function Procedures
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: Sub and Function Procedures
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Eight Sub and Function Procedures.
1.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
VBA Modules, Functions, Variables, and Constants
Example 2.
Chapter 7: Sub and Function Procedures
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
VB – Core III Functions Sub-routines Parameter passing Modules Scope Lifetime.
Procedures and Functions
5.05 Apply Looping Structures
Apply Sub Procedures/Methods and User Defined Functions
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Programming with Microsoft Visual Basic th Edition CHAPTER SEVEN SUB AND FUNCTION PROCEDURES.
Programming with Microsoft Visual Basic 2012 Chapter 7: Sub and Function Procedures.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Seven Sub and Function Procedures.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Tutorial 11 Using and Writing Visual Basic for Applications Code
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Variable, Expressions, Statements and Operators By: Engr. Faisal ur Rehman CE-105 Fall 2007.
Why to Create a Procedure
Programming with Microsoft Visual Basic 2008 Fourth Edition
CS0004: Introduction to Programming Subprocedures and Modular Design.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 7 Sub and Function Procedures.
110-G1 Motivation: Within a program, may have to perform the same computation over and over Many programs share the same computation (e.g. sorting) To.
Chapter 6 Sub Procedures
Chapter 9: Writing Procedures Visual Basic.NET Programming: From Problem Analysis to Program Design.
Introduction to VB.NET 2005 Dr. McDaniel IDS4704 Spring 2005.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 10: Chapter 6: Slide 1 Unit 10 Sub Procedures and Functions Chapter 6 Sub.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
Visual Basic Programming I 56:150 Information System Design.
Debugging, Static Variables, ByRef, ByValue Chapt. 6 in Deitel, Deitel and Nieto.
Programming with Microsoft Visual Basic th Edition
Created by Alia Al-Abdulkarim 2008 Visual Basic Vs. Java.
Week Procedures And Functions 7 A procedure is a collection of statements that performs a task.
BACS 287 Programming Fundamentals 5. BACS 287 Programming Fundamentals This lecture introduces the following topics: – Procedures Built-in Functions User-defined.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Tutorial 81 Field, Record, Data File Field - a single item of information about a person, place, or thing Record - a group of related fields that contain.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 6 Sub Procedures And Functions.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
Copyright © 2014 Pearson Education, Inc. Chapter 6 Procedures and Functions.
1 Computer Programming Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Addison Wesley is an imprint of © 2011 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 3 Variables and Calculations.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
Sub Procedures Chapter 6-Part 1. Chapter 6 Part 12 Event Procedures Code that occurs based upon event. Mouse click Got focus Repetitive code that might.
Sub Procedures And Functions
Visual Basic Fundamental Concepts
Chapter 9: Value-Returning Functions
Chapter 7 User-Defined Methods.
Royal University of Phnom Penh
IS 350 Application Structure
Object-Oriented Programming: Classes and Objects
Lesson 16 Sub Procedures Lesson 17 Functions
Functions Chapter 6-Part 2.
Method.
2. Understanding VB Variables
Object-Oriented Programming: Classes and Objects
Visual Basic..
Procedures and Functions
CIS16 Application Development and Programming using Visual Basic.net
Chapter 7: Using Functions, Subs, and Modules
Tonga Institute of Higher Education
STARTING OUT WITH Visual Basic 2008
Presentation transcript:

Chapter 6 Procedures and Functions Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI

Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine

Topics Procedures Passing arguments to Procedures Functions Debugging: Step into, over, and out of procedures and functions

Introduction A procedure is a collection of statements that performs a task – Event handlers are a type of procedure A function is a collection of statements that performs a task and returns a value to the VB statement that executed it – Functions work like intrinsic functions, such as CInt and IsNumeric A method can be either a procedure or a function

Procedures A moderately complex program needs to perform multiple tasks. A procedure is a block of program code that performs a specific task. A program can be considered as the assembly of multiple procedures. Execution of a procedure is commonly referred to as calling a procedure. Most Visual Basic procedures are Sub procedures and Function procedures.

boss worker2worker3worker1 worker4worker5 How Procedure Works A (called) procedure is invoked by another procedure (caller). The called procedure does the job and return the result to the caller or simply transfer control to the caller without returning anything. An analogy of procedure calls:

Sub Procedures vs. Function Procedures A Sub procedure does not return a value after performing its assigned task. A Function procedure returns a value after performing its assigned task. A Function procedure can only return one value.

Sub Procedures Two types of Sub procedures: 1.Event procedures - Associated with a specific object and event 2.General Purpose Sub procedures - Independent of any object and event; can be called (or invoked) from one or more places in an application.

Sample Procedure, Tutorial 6-1 Sub DisplayMessage() 'A Sub procedure that displays a message. lstOutput.Items.Add("") lstOutput.Items.Add("Hello from DisplayMessage procedure.") lstOutput.Items.Add("") End Sub Private Sub btnGo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnGo.Click ' This procedure calls the DisplayMessage procedure. lstOutput.Items.Add("Hello from btnGo_Click procedure.") lstOutput.Items.Add("Now I am calling the " & _ "DisplayMessage procedure.""procedure.") DisplayMessage() lstOutput.Items.Add("Now I am back " _ & "in the btnGo_Click procedure.") End Sub Calls DisplayMessage procedure Returns to btnGo_Click

Declaring a Procedure AccessSpecifier is optional and establishes accessibility to the program Sub and End are keywords ProcedureName used to refer to procedure –Use Pascal casing, capitalize 1 st character of the name and each new word in the name ParameterList is a list of variables or values being passed to the sub procedure. It is optional. [AccessSpecifier] Sub ProcedureName ([ParameterList]) [Statements] End Sub

More on the Access Specifier Private allows use only from that form Public allows use from other forms If not specified, default is Public There are other access specifiers such as: – Protected – Friend – Protected Friend – These will be discussed in later chapters

Placing Sub Procedure in File General Purpose Sub procedures can be placed anywhere in the Form's code module. Likewise, the event procedures can also be placed anywhere in the Form's code module.

Sample Procedure Private Sub DisplayGrade() ' Display the intAverage score. lblAverage.Text = intAverage.ToString() ' Determine and display the letter grade. Select Case intAverage Case 90 To 100 lblLetterGrade.Text = "A" Case 80 To 90 lblLetterGrade.Text = "B" Case 70 To 79 lblLetterGrade.Text = "C" Case 60 To 69 lblLetterGrade.Text = "D" Case Else lblLetterGrade.Text = "E" End Select End Sub

Procedures and Static Variables Variables needed only in a procedure, should be declared within that procedure – Creates a local variable with scope only within the procedure where declared – Local variable values are not saved from one procedure call to the next To save value between procedure calls, use Static keyword to create a static local variable – Static VariableName As DataType – Scope is still only within the procedure – But variable exists for lifetime of application

Arguments Argument – a value passed to a procedure We’ve already done this with functions – Value = CInt(txtInput.Text) – Calls the CInt function and passes txtInput.Text as an argument A procedure must be declared with a parameter list in order to accept an argument

Passing Multiple Arguments Multiple arguments separated by commas Value of first argument is copied to first Second to second, etc. ShowSum(intValue1, intValue2) ' calls ShowSum procedure Sub ShowSum(ByVal intNum1 As Integer, _ ByVal intNum2 As Integer) ' This procedure accepts two arguments, and prints ' their sum on the form. Dim intSum As Integer intSum = intNum1 + intNum2 MessageBox.Show("The sum is " & intSum.ToString) End Sub

Passing Variables A variable has both a value and a unique address in the computer's memory. Either the value or the address can be passed to a Sub procedure. Two ways of passing parameters: (1)Pass by value. The value of the variable is passed to the called procedure; (2)Pass by reference: The address of the variable is passed to the called procedure.

Two analogies Telling someone the balance of your banking account passes the information about your banking account. This is equivalent to "pass by value". Giving someone the information on the account number, PIN, etc. authorizes the person to deposit or withdraw from the account, as well as to query the balance. This equivalent to "pass by reference".

Pass Variables by Value Passing variables by value is specified in the parameter list. Use the keyword ByVal in the variable declaration. When the procedure is invoked, only the value of the variable is passed to the procedure. Example: Private Sub DisplayMessage(ByVal pet As String, ByVal years As String) messageLabel.Text = "Your pet " & pet & " is " _ & years & " years old." End Sub

Pass Variables by Value (Cont'd) In the calling procedure, you may have code like this: Private Sub getInfoButton_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles getInfoButton.Click Dim petName As String Dim petAge As String petName = InputBox("Pet's name:", "Name Entry") petAge = InputBox("Pet's age (years):", "Age Entry") DisplayMessage(petName, petAge) End Sub

Passing Variables by Reference Passing variables by reference gives the receiving procedure access to the variable being passed. In most cases, you pass variables by reference when you want the receiving procedure to change the contents of the variables. Use the ByRef keyword in the parameter list.

Passing Variables by Reference (Cont'd) Example Private Sub calcButton_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles calcButton.Click Dim hoursWkd As Decimal Dim rateOfPay As Decimal Dim grossPay As Decimal hoursWkd = Convert.ToDecimal(hoursListBox.SelectedItem) rateOfPay = Convert.ToDecimal(rateListBox.SelectedItem) CalcGrossPay(hoursWkd, rateOfPay, grossPay) grossLabel.Text = grossPay.ToString("C2") End Sub

Look into Memory of variables The variables used in exchange information between the calcButton's click event procedure and the CalcGrossPay procedures are allocated as follows: In the calling procedure: hoursWkd rateOfPay In the called procedure: hoursWkd rateOfPay In both procedures:GrossPay Variable Value Address

Passing Variables by Reference (Cont'd) Example Private Sub CalcGrossPay(ByVal hours As Decimal, _ ByVal rate As Decimal, _ ByRef gross As Decimal) ' calculates gross pay If hours <= 40D Then gross = hours * rate Else gross = hours * rate + (hours - 40D) * rate / 2D End If End Sub

Additional ByVal or ByRef Example Tutorial 6-4 demonstrates the difference between parameters passed ByVal & ByRef – Passed ByVal – Calling procedure does not “see” changes made to the value of an argument – Passed ByRef – Calling procedure “sees” changes made to the value of an argument

Function Procedures Similar to a Sub procedure, a function procedure is a block of code that performs a specific task. Different from a Sub procedure, a function procedure returns a value upon completion of the task. The concepts of passing by value and passing by reference apply to both Sub procedures and Function procedures.

Declaring a Function New keyword Function Also new is As DataType which states the data type of the value to be returned Return value is specified in a Return expression [AccessSpecifier] Function FunctionName ([ParameterList]) _ As DataType [Statements] End Function

Function Call Example sngTotal = Sum(sngValue1, sngValue2) Function Sum(ByVal sngNum1 As Single, _ ByVal sngNum2 As Single) As Single Dim sngResult As Single sngResult = sngNum1 + sngNum2 Return sngResult End Function sngValue1 & sngValue2 must be data type Single – Data types must agree with parameter list sngTotal must be Single, agrees with return value Tutorial 6-5 demonstrates function use

Returning Nonnumeric Values Function IsValid(intNum As Integer) As Boolean Dim blnStatus As Boolean If intNum >= 0 And intNum <= 100 Then blnStatus = True Else blnStatus = False End If Return blnStatus End Function Function FullName(ByVal strFirst As String, _ ByVal strLast As String) As String Dim strName As String strName = strLast & ", " & strFirst Return strName End Function

Visual Basic 2010 addition Nullable types were added to Visual Basic In Visual Basic 2010 you can use them as parameters. Here are two examples: ' Assign Nothing as the default value for nullable optional parameter. Sub Calculate (ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Integer? = Nothing)... End Sub ' Assign an integer value to a nullable optional paramter of type Double. Sub Process(ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Double? = 10)... End Sub

Debugging Involving Procedures Step Into - continue to debug by single-stepping through a procedure Step Over - run procedure without single-stepping, continue single-step after the call Step Out - end single-stepping in procedure, continue single-step after the call Tutorial 6-6 provides examples