HNDIT Rapid Application Development

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.
Sub and Function Procedures
Chapter 3: Using Variables and Constants Programming with Microsoft Visual Basic 2005, Third Edition.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
1.
Input Dialog Box An input dialog box can be used to obtain a single item of input from the user Presents a window (dialog box) requesting input Syntax:
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Chapter 4 - Visual Basic Schneider
Chapter 7: Sub and Function Procedures
Chapter Three Using Variables and Constants Programming with Microsoft Visual Basic th Edition.
Apply Sub Procedures/Methods and User Defined Functions
Programming with Microsoft Visual Basic 2012 Chapter 7: Sub and Function Procedures.
Dani Vainstein1 VBScript Session 9. Dani Vainstein2 What we learn last session? VBScript coding conventions. Code convention usage for constants, variables,
Variables and Constants
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
Intrinsic Functions Pre-coded Functions Used to improve developer productivity Broad Range of Activities Math calculations Time/Date functions String.
Chapter 6 Procedures and Functions Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI
Why to Create a Procedure
CSCI 3327 Visual Basic Chapter 6: Methods: A Deeper Look UTPA – Fall 2011.
1 Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
3 - Variables Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
Computer Programming TCP1224 Chapter 4 Variables, Constants, and Arithmetic Operators.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Chapter 6 Sub Procedures
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
Chapter 8 - Visual Basic Schneider
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 10: Chapter 6: Slide 1 Unit 10 Sub Procedures and Functions Chapter 6 Sub.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
‘Tirgul’ # 2 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #2.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Three Using Variables and Constants.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
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.
Programming with Microsoft Visual Basic th Edition
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
Week Procedures And Functions 7 A procedure is a collection of statements that performs a task.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
BACS 287 Programming Fundamentals 5. BACS 287 Programming Fundamentals This lecture introduces the following topics: – Procedures Built-in Functions User-defined.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 6 Sub Procedures And Functions.
Copyright © 2014 Pearson Education, Inc. Chapter 6 Procedures and Functions.
1 VB-06-String Manipulation Mar 03, 2002 String Function VISUAL BASIC.
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,
CSC 162 Visual Basic I Programming. String Functions LTrim( string ) –Removes leading spaces from the left side of string RTrim( string ) –Removes trailing.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Chapter 3 - Visual Basic Schneider. Private Sub cmdEvaluate_Click() Dim n As Single, root As Single n = 6.76 root = Sqr(n) picResults.Print root; Int(n);
Data Types. Visual Basic provides data type Single for storing single-precision floating-point numbers. Data type Double requires more memory to store.
Sub Procedures And Functions
A variable is a name for a value stored in memory.
An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use.
Visual Basic Variables
Chapter 3: Using Variables and Constants
Procedures and Functions
Sub Procedures and Functions
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
STARTING OUT WITH Visual Basic 2008
Presentation transcript:

HNDIT23073- Rapid Application Development Week 4- 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 Used for Repeated or Shared Tasks - Container for code to be called multiple times Makes the code easier to understand

Procedure (cont.) 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

Procedure Types in Visual Basic (Event) Sub Procedure Performs a logical action Does not return a value Executes when event occurs - not “Called” from code (Gen Purpose) Sub Procedure Must be “Called” from other code Function Performs Calculation Does return a Value

Sub Procedure An abbreviation of the older term subroutine Sub procedures are written to perform specific tasks General 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

Sub Procedure Syntax Public Sub SubName (parameterName As DataType) ‘*procedure code*’ End Sub Public (optional) - the AccessSpecifier - establishes accessibility to the program Sub and End - keywords SubName - 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

Procedure Call Used to invoke (cause to execute) a procedure Syntax: Call ProcedureName (Arguments) Call (optional) - keyword ProcedureName - name of Sub (or Function) to invoke Arguments (if any, included in parenthesis) - Data passed to the procedure Example: Call Power (5, 2) OR Power (5, 2)

Arguments Values, Variables or Expressions placed in parentheses in a Call statement Contain data needed by the procedure The 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

Parameters 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 procedure Syntax: (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

Passing Arguments to Parameters 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.

Sub Procedure Example Private Sub btnResult_Click() ‘* event procedure Dim lng As Single, wid As Single lng = 5 wid = 10 Call ComputeArea(lng, wid) ‘* call to sub End Sub Sub ComputeArea(Length As Single, Width As Single) Dim Area As Single Area = Length * Width MsgBox(“Area = “ & Area)

Pass by Value or Pass by Reference 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

ByVal/ByRef Example At declaration intX  5 intY  5 At termination 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) ChangeValue(intX = 5) Result: intY = intX = 10 At termination intX  5 intY  10 At declaration intX  5  intY At termination intX  10  intY

Sub Procedure Example 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 input Call Sub

Functions Procedures that return a Value Same 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 Char Object 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

Function Syntax Public (optional) - the AccessSpecifier Public Function FunctionName (parameterName As DataType) As returnType ‘* function code Return Value ‘* OR FunctionName = Value End Function Public (optional) - the AccessSpecifier Function and End – keywords FunctionName - 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 function Return Value – required statement to return data to caller

Using Functions Functions ALWAYS return a value When 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

Function Example Private Sub btnResult_Click() ‘* event procedure Dim 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 A

Function Example 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 Input Call the function, Display results in a message box.

Intrinsic Functions Pre-coded Functions provided by VB Used to improve developer productivity – less time spent coding Broad 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

Numeric 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

Formatting 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%

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

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

Invalid Conversions Conversion functions can fail String “xyz” can’t be converted to a number Dim dblSalary as Double = CDbl(“xyz”) There’s no day 35 in the month of May Dim datHired as Date = CDate(“05/35/2005”) These failed conversions cause a runtime error called an invalid cast exception

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

String 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

Input Box InputBox Syntax: Example: 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”)

Message Box MsgBox Syntax Example Displays a message in a dialog box MsgBox (prompt, [title]) Example MsgBox (“Hello World”, “Chapter 7_1”) MsgBox (“The Result is “ & Result)

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

TOE Chart TASK OBJECT EVENT Input Price Text Box, Label None Display Receipt List Box Display Subtotal Label, Label Display Sales Tax Display Total Add Item to Receipt Button Click Exit

Interface

Code Variables Subtotal Tax Total What Data Types? Where to Declare?

Add to Receipt Button Event Read in Data from Text Box Convert to Number CDbl Val Add to ListBox Formatted as Currency Update Subtotal, Tax, and Total Variables Update Output Displays

Convert to Number Format to Currency Format to Currency

Example 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.

Reference http://www.cis.usouthal.edu,2014/03/11