Docsity

Intro to Programming: Visual Basic Sub & Function Procedures, Univ. of Pittsburgh, Summer , Study notes of Computer Science

Partial preview of the text

Download Intro to Programming: Visual Basic Sub & Function Procedures, Univ. of Pittsburgh, Summer and more Study notes Computer Science in PDF only on Docsity!

CS 0004 – Introduction to

Programming

Using Visual Basic

Summer 2009

University of Pittsburgh

Lecture 10

7/8/09 CS4 - Summer 2009 - Lecture 10 1

Chapter 5 - General Procedures

• 5.1 Sub Procedures, Part I

• 5.2 Sub Procedures, Part II

• 5.3 Function Procedures

• 5.4 Modular Design

• 5.5 A Case Study: Weekly Payroll

Devices for Modularity

• Visual Basic has two devices for breaking

problems into smaller pieces:

  • Sub procedures
  • Function procedures

Sub Procedures

• Perform one or more related tasks

• General syntax

Sub ProcedureName() statements End Sub

Naming Sub Procedures

• The rules for naming Sub procedures are the

same as the rules for naming variables.

Sub ExplainPurpose()

Example

lstBox.Items.Clear() ExplainPurpose() lstBox.Items.Add("") lstBox.Items.Add("Program displays a sentence") lstBox.Items.Add("identifying a sum.") End Sub

Arguments and Parameters

• Sum(2, 3)

Sub Sum(ByVal num1 As Double, ByVal num2 As Double) arguments parameters displayed automatically

Several Calling Statements

ExplainPurpose() Sum(2, 3) Sum(4, 6) Sum(7, 8) Output: Program displays a sentence identifying a sum. The sum of 2 and 3 is 5. The sum of 4 and 6 is 10 The sum of 7 and 8 is 15.

Variables and Expressions as Arguments Dim s As String = "CA" Dim p As Double = 19 Demo(s, 2 * p) Sub Demo(ByVal state As String, ByVal pop As Double) txtBox.Text = state & " has population " & pop & _ " million." End Sub

  • Note : The variable names in the arguments need not match the parameter names. For instance, s versus state ..

Calling

A Sub procedure can call another Sub procedure. Private Sub btnAdd_Click(...) Handles btnAdd.Click Sum(2, 3) End Sub Sub Sum(ByVal num1 As Double, ByVal num2 As Double) DisplayPurpose() lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "." End Sub

ByVal and ByRef

• Parameters in Sub procedure headers are

proceeded by ByVal or ByRef

• ByVal stands for By Value

• ByRef stands for By Reference

Passing by Value

• When a variable argument is passed to a

ByVal parameter, just the value of the

argument is passed.

• After the Sub procedure terminates, the

variable has its original value.

Same Example: n num

Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByVal num As Double) num = 3 * num End Sub Output: 4

Passing by Reference

• When a variable argument is passed to a

ByRef parameter, the parameter is given the

same memory location as the argument.

• After the Sub procedure terminates, the

variable has the value of the parameter.