1 Subroutines and Functions Chapter 6 in Deitel, Deitel and Nieto.

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
Procedural programming in Java
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
1.
VBA Modules, Functions, Variables, and Constants
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Program Design and Development
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Promoting Code Reuse Often in programming, multiple procedures will perform the same operation IN OTHER WORDS – the same piece of code will do the same.
VB – Core III Functions Sub-routines Parameter passing Modules Scope Lifetime.
Apply Sub Procedures/Methods and User Defined Functions
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
CS0004: Introduction to Programming Variables – Numbers.
Ch 10: More on Variables and Subroutines CP212 Winter 2012.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Why to Create a Procedure
Visual Basic Games: Week 3 Global variables, parameters, Select, KeyDown Enable, Visible, Focus State of Game Read chapter 3.
1 Visual Basic Checkboxes Objects and Classes Chapt. 16 in Deitel, Deitel and Nieto.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
CS0004: Introduction to Programming Subprocedures and Modular Design.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
1 Chapter 5 - General Procedures 5.1 Function Procedures 5.2 Sub Procedures, Part I 5.3 Sub Procedures, Part II 5.4 Modular Design.
Sub procedures School of Business Eastern Illinois University © Abdou Illia, Spring 2002 (Week 6, Friday 2/21/03)
VB Games: Preparing for Memory Brainstorm controls & events Parallel structures (again), Visibility, LoadPicture, User-defined procedures, Do While/Loop,busy.
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.
Arrays Code: Arrays Controls: Control Arrays, PictureBox, Timer.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
1 Flow Control II Code: Select-Case and For-Next Controls: Frames and OptionButtons.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
B065: PROGRAMMING Sub Procedures I. Starter  Identify the separate tasks to be performed in the programming task below (break it down into numbered sections).
Procedural programming in Java Methods, parameters and return values.
Practical Programming COMP153-08S Week 5 Lecture 1: Screen Design Subroutines and Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
Chapter 3 w Variables, constants, and calculations DIM statements - declaration temporary memory locations identifier, data type, scope data types - values.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Debugging, Static Variables, ByRef, ByValue Chapt. 6 in Deitel, Deitel and Nieto.
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Introduction to Functions CSIS 1595: Fundamentals of Programming and Problem Solving 1.
BACS 287 Programming Fundamentals 5. BACS 287 Programming Fundamentals This lecture introduces the following topics: – Procedures Built-in Functions User-defined.
Controlling Program Flow with Decision Structures.
More on Variables and Subroutines. Introduction Discussion so far has dealt with self- contained subs. Subs can call other subs or functions. A module.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
Subroutines and Functions Chapter 6. Introduction So far, all of the code you have written has been inside a single procedure. –Fine for small programs,
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Selection Using IF THEN ELSE CASE Introducing Loops.
Sub Procedures and Functions Visual Basic. Sub Procedures Slide 2 of 26 Topic & Structure of the lesson Introduction to Modular Design Concepts Write.
CS0004: Introduction to Programming
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
IE 8580 Module 4: DIY Monte Carlo Simulation
A variable is a name for a value stored in memory.
COMPUTATIONAL CONSTRUCTS
IS 350 Application Structure
About the Presentations
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 4 - Visual Basic Schneider
MSIS 655 Advanced Business Applications Programming
Chapter 6 Methods.
Topics Introduction to Functions Defining and Calling a Void Function
Data Types List Box Combo Box Checkbox Option Box Visual Basic 6.0
Chapter 9: Value-Returning Functions
If, Subroutines and Functions
CIS16 Application Development and Programming using Visual Basic.net
Methods.
Presentation transcript:

1 Subroutines and Functions Chapter 6 in Deitel, Deitel and Nieto

2 Resolution Two definitions of “resolution” A solution … of a problem The act … of separating into constituent or elementary parts (Webster’s New Universal Unabridged Dictionary) One of the primary techniques for solving complex problems is “divide and conquer” Break the problem into manageable pieces Solve the pieces Reassemble the pieces into a complete solution

3 Modules Modules are one of the “constituent parts” into which a programmer breaks Visual Basic code Another “unit” of programming is the object

4 Divide and Conquer Example

5 Option Explicit Dim EmployeeName As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double Private Sub cmdCalculate_Click() GetInfo CalculateWeeklySalary PrintResult End Sub Problem broken into three modules They’re getting rid of the currency type so use double These are “calls”

6 The GetInfo Module Private Sub GetInfo() EmployeeName = txtFirstName.Text & _ " " & txtLastName.Text GetHours GetWage End Sub This module is further broken down into more modules

7 GetHours Module Private Sub GetHours() If IsNumeric(txtHours.Text) Then Hours = CInt(txtHours.Text) Else MsgBox ("Please enter a number (e.g. 34)” _ & “for the Hours.") txtHours.Text = "" txtHours.SetFocus End If End Sub

8 GetWage Module Private Sub GetWage() If IsNumeric(txtWage.Text) Then Wage = CDbl(txtWage.Text) Else MsgBox ("Please enter a number “ _ & “ (e.g. 7.95) for the Wage.") txtWage.Text = "" txtWage.SetFocus End If End Sub

9 CalculateWeeklySalary Module Private Sub CalculateWeeklySalary() If Hours > 40 Then Salary = (Hours - 40) * 1.5 * Wage + _ 40 * Wage Else Salary = Hours * Wage End If End Sub

10 PrintResult Module Private Sub PrintResult() lblSalary.Caption = EmployeeName & _ " earned " lblSalary.Caption = lblSalary.Caption & _ Format$(Salary, "currency") lblSalary.Caption = lblSalary.Caption & _ " the week of " & Date & "." End Sub

11 Code maintenance Modularization makes the code easier to maintain If the way the data is obtained changes, we need only change the GetInfo module If we alter the overtime rules, we need only change the CalculateWeeklySalary module If we decide to cut an actual check, we need only change the PrintResult module

12 Reduce Repeated Code Another possible benefit of modules is the reduction of repeated code A given module can be called more than once from more than one location in the code

13 Select a Color Revisited Recall we must change the form’s backcolor property as well as the backcolor property of all the optionbuttons, and we must do that in click method of each of the optionbuttons To prevent a lot of repetition, we will use a subroutine

14

15 Add Procedure Does not return anything so sub Used only by this form so private

16 Add Procedure Result Or just type this; actually VB supplies the End Sub automatically

17 Calling Subroutines Private Sub optBlue_Click() Color = vbBlue Call ColorForm End Sub Private Sub optGreen_Click() Color = vbGreen ColorForm End Sub Call ColorForm subroutine using keyword Call Call ColorForm subroutine without keyword Call

18 Subroutine ColorForm Private Sub ColorForm() frmSelectColor.BackColor = Color optRed.BackColor = Color optBlue.BackColor = Color optGreen.BackColor = Color optYellow.BackColor = Color optCyan.BackColor = Color optMagenta.BackColor = Color End Sub Open parenthesis; close parenthesis

19 Scope If a variable is declared at the top of the module, it is referred to as global and is available to all of the modules belonging to the form If a variable is declared within a module, it is referred to as local and is available only within that module

20 What’s the difference? Global variables should be fundamental to the problem and needed by several modules Local variables are those that are needed in one or two modules only

21 An Example For example the i in For i=1 To n is only needed within the for loop within one module, so it should be declared locally This way i cannot be confused with other counters in the problem (even if they are also called i) Duplicate variable names can be a big problem in longer programs, proper use of scope limits the difficulty

22 Passing a Parameter To get local information from one module to another, one “passes” the information The information that is passed is placed in the parentheses

23 Passing a Parameter Option Explicit Private Sub Form_Load() Call optRed_Click End Sub Private Sub optBlue_Click() Call ColorForm(vbBlue) End Sub Look Ma, no global variables Passing a parameter

24 Local ColorForm Private Sub ColorForm(Color As Long) frmSelectColor.BackColor = Color optRed.BackColor = Color optBlue.BackColor = Color optGreen.BackColor = Color optYellow.BackColor = Color optCyan.BackColor = Color optMagenta.BackColor = Color End Sub Passed variable and its type

25 What has been gained? First, the variable color is now local to ColorForm meaning that the variable color can be used elsewhwere in the program without problem Second, the variable color (which corresponds to a memory location) exits only for the duration of ColorForm, so memory is freed up

26 Information Hiding “The process of hiding details of an object or function. Information hiding is a powerful programming technique because it reduces complexity. …. The programmer can then focus on the new object without worrying about the hidden details.” “Information hiding is also used to prevent programmers from changing --- intentionally or unintentionally -- parts of a program.” (

27 Multiple programmers Most code is written by teams of coders One should be able to use a module without detailed knowledge of how it works (its implementation) If a module uses global variables, then someone using module must declare these variables And if two modules use the same global variables, there can be conflicts

28 To and Fro We have seen how to get local information to a module, now we must consider how to get it back VB distinguishes between subroutines and functions; the difference is that function return a value (send back some information) to whatever modules called it

29 Weekly Salary Revisited

30 New cmdCalculate_Click Option Explicit Private Sub cmdCalculate_Click() Dim EmployeeName As String Dim Hours As Integer Dim Wage As Double Dim Salary As Double All variables local now

31 New cmdCalculate_Click (Cont.) EmployeeName = GetName() Hours = GetHours() Debug.Print Hours Wage = GetWage() Salary = CalculateWeeklySalary(Hours, Wage) Call PrintResult(EmployeeName, Salary) End Sub Three functions return name, hours and wage respectively, note they are part of assignment statement CalculateWeeklySalary now a function

32 GetName Function Private Function GetName() As String GetName = txtFirstName.Text & " " _ & txtLastName.Text End Function Type of thing that gets returned Whatever you want returned assign to the function’s name

33 GetHours Function Private Function GetHours() As Integer If IsNumeric(txtHours.Text) Then GetHours = CInt(txtHours.Text) Else MsgBox ("There was an error in the hours.") txtHours.Text = "" txtHours.SetFocus GetHours = 0 End If End Function Need to return something even if there was a mistake, better to test on validate method

34 GetWage Function Private Function GetWage() As Double If IsNumeric(txtWage.Text) Then GetWage = CDbl(txtWage.Text) Else MsgBox ("There was an error in the Wage.") txtWage.Text = "" txtWage.SetFocus GetWage = 0 End If End Function

35 CalculateWeeklySalary Function Private Function CalculateWeeklySalary(Hours As Integer, _ Wage As Double) As Double If Hours > 40 Then CalculateWeeklySalary = (Hours - 40) * _ 1.5 * Wage + 40 * Wage Else CalculateWeeklySalary = Hours * Wage End If End Function

36 PrintResult Subroutine Private Sub PrintResult(EmployeeName As _ String, Salary As Double) lblSalary.Caption = EmployeeName & _ " earned " lblSalary.Caption = lblSalary.Caption & _ Format$(Salary, "currency") lblSalary.Caption = lblSalary.Caption & _ " the week of " & Date & "." End Sub

37 VB Functions VB has some built in functions such an Abs(x) - return the absolute value of x Exp(x) - return the exponential of x Int(x) - return the integer part of x Sgn(x) - return the sign of the number x Rnd() - return a “pseudo-random” number between 0 and 1

38 Random Numbers

39 Random Numbers Option Explicit Private Sub cmdRandom_Click() txtRandomSingle.Text = Rnd() End Sub Private Sub cmdRandomInteger_Click() txtRandomInteger.Text = Int(Rnd() * ) End Sub

40 Random numbers Private Sub Command1_Click() txtRandomAB.Text = Int(Rnd() * (txtB.Text - txtA.Text + 1) + txtA.Text) End Sub