Subs and Functions Ch 6. Introduction VB.NET Procedures Sub Procedures Function Procedures Outline.

Slides:



Advertisements
Similar presentations
Sub and Function Procedures
Advertisements

JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Example 2.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
Apply Sub Procedures/Methods and User Defined Functions
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Tutorial 11 Using and Writing Visual Basic for Applications Code
CHAPTER SIX Reducing Program Complexity General Sub Procedures and Developer-defined Functions.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
CSCI 3327 Visual Basic Chapter 6: Methods: A Deeper Look UTPA – Fall 2011.
JavaScript: Functions © by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
6.1 Introduction Divide and Conquer –The best way to develop and maintain a large program is to construct it from small, manageable pieces. BZUPAGES.COM.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhancing the Wage Calculator Application Introducing Function Procedures and.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Fund Raiser Application Introducing Scope, Pass-by-Reference and Option Strict.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Functions.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
 2002 Prentice Hall. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using.
Chapter 9: Writing Procedures Visual Basic.NET Programming: From Problem Analysis to Program Design.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Applications Development
Chapter 4 - Visual Basic Schneider1 Chapter 4 General Procedures.
6c – Function Procedures Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
Introduction to Visual Basic Programming. Introduction Simple Program: Printing a Line of Text Another Simple Program: Adding Integers Memory Concepts.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
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.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
PSU CS 106 Computing Fundamentals II VB Declarations HM 5/4/2008.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Visual Basic CDA College Limassol Campus COM123 Visual Programming 1 Semester B Lecture:Pelekanou Olga Week 5: Useful Functions and Procedures.
 2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Procedures Outline 6.1Introduction 6.2 Modules, Classes and Procedures 6.3 Sub Procedures 6.4.
Week Procedures And Functions 7 A procedure is a collection of statements that performs a task.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Chapter 6- Procedures. 6.1Introduction 6.2 Modules, Classes and Procedures 6.3 Sub Procedures 6.4 Function Procedures 6.5 Methods 6.6 Argument Promotion.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Chapter 3: Introducing the Microsoft.NET Framework and Visual Basic.NET Visual Basic.NET Programming: From Problem Analysis to Program Design.
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
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,
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
Arrays 1.
7.1 Introduction Arrays Arrays are data structures consisting of data items of the same type “Static” entities They remain the same size once they are.
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
Visual Basic Fundamental Concepts
Royal University of Phnom Penh
Chapter 7 - Arrays Outline 7.1 Introduction 7.2   Arrays 7.3   Declaring and Allocating Arrays 7.4   Examples Using Arrays   Allocating an Array.
13 Enhancing the Wage Calculator App
Subs, Functions and Events
Method.
Chapter 5 – Control Structures: Part 2
Chapter 5 - Functions Outline 5.1 Introduction
Visual Basic..
CSCI 3327 Visual Basic Chapter 6: Methods: A Deeper Look
Methods.
Presentation transcript:

Subs and Functions Ch 6

Introduction VB.NET Procedures Sub Procedures Function Procedures Outline

VB.NET Procedures Framework Class Library – Provides a rich collection of “prepackaged” classes and methods for performing many operations Mathematical calculations String manipulations Character manipulations Input/output operations

Programmer-defined procedures – FCL cannot provide every conceivable feature that a programmer could want – Three types of procedures Sub procedures Function procedures Event procedures – A procedure is invoked by a procedure call VB.NET Procedures

Payment.vb Program Output 1 ' Fig. 6.2: Payment.vb 2 ' Sub procedure that prints payment information. 3 4 Module modPayment 5 6 Sub Main() 7 8 ' call Sub procedure PrintPay 4 times 9 PrintPay(40, 10.5) 10 PrintPay(38, 21.75) 11 PrintPay(20, 13) 12 PrintPay(50, 14) Console.ReadLine() ' prevent window from closing 15 End Sub ' Main ' print amount of money earned in command window 18 Sub PrintPay(ByVal hours As Double, ByVal wage As Decimal) ' pay = hours * wage 21 Console.WriteLine("The payment is {0:C}", hours * wage) 22 End Sub ' PrintPay End Module ' modPayment The payment is $ The payment is $ The payment is $ The payment is $ PrintPay receives the values of each argument and stores them in the parameters variables hours and wage Notice that PrintPay appears within modPayment. All procedures must be defined inside a module or a class Console application uses a Sub procedure (invoked from the application’s Main procedure) to print a worker’s payment information.

The program contains two procedure definitions: The program contains two procedure definitions: 1.Sub procedure Main, which executes when the console application is loaded. 2.Sub procedure PrintPay, which executes when it is invoked, or called, from another procedure, in this case Main. Sub Procedures

Sub Procedures Sub Procedures Format of a procedure definition Sub procedure-name(parameter-list) declarations and statements End Sub Procedure header: – ByVal: specifies that the calling program should pass a copy of the value of the argument in the procedure call to the parameter, which can be used in the Sub procedure body. Procedure-name – Directly follows the Sub keyword – Can be any valid identifier Procedure body – The declarations and statements in the procedure definition form the procedure body

Common Errors Declaring a variable in the procedure’s body with the same name as a parameter variable in the procedure header is a syntax error. Declaring a variable in the procedure’s body with the same name as a parameter variable in the procedure header is a syntax error. Defining a procedure inside another procedure is a syntax error—procedures cannot be nested. Defining a procedure inside another procedure is a syntax error—procedures cannot be nested. The procedure header and procedure calls all must agree with regard to the number, type and order of parameters. The procedure header and procedure calls all must agree with regard to the number, type and order of parameters.

Function Procedures Function Procedures Similar to Sub procedures One important difference: – Function procedures return a value to the caller, whereas Sub procedures do not.

1 ' Fig. 6.3: SquareInteger.vb 2 ' Function procedure to square a number. 3 4 Module modSquareInteger 5 6 Sub Main() 7 Dim i As Integer ' counter 8 9 Console.WriteLine("Number" & vbTab & "Square" & vbCrLf) ' square numbers from 1 to For i = 1 To Console.WriteLine(i & vbTab & Square(i)) 14 Next End Sub ' Main ' Function Square is executed 19 ' only when the function is explicitly called. 20 Function Square(ByVal y As Integer) As Integer 21 Return y ^ 2 22 End Function ' Square End Module ' modSquareInteger The For structure displays the results of squaring the Integer s from 1-10 Square is invoked with the expression Square(i) The Return statement terminates execution of the procedure and returns the result of y ^ 2 Console application uses Function procedure Square to calculate the squares of the Integers from 1–10.

Program Output Number Square

Function Procedures Function Procedures Format of a Function procedure definition Function procedure-name(parameter-list) As return-type declarations and statements End Function Return-type: Indicates the data type of the result returned from the Function to its caller Return expression – Can occur anywhere in a Function – It returns exactly one value – Control returns immediately to the point at which that procedure was invoked

Common Errors If the expression in a Return statement cannot be converted to the Function procedure’s return-type, a runtime error is generated. Failure to return a value from a Function procedure (e.g., by forgetting to provide a Return statement) causes the procedure to return the default value for the return-type, often producing incorrect output.

1 ' Fig. 6.4: Maximum.vb 2 ' Program finds the maximum of three numbers input. 3 4 Public Class FrmMaximum 5 6 ' obtain values in each text box, call procedure Maximum 7 Private Sub btnMaximum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaximum.Click 8 Dim value1, value2, value3 As Double 9 10 value1 = txtFirst.Text 11 value2 = txtSecond.Text 12 value3 = txtThird.Text lblMaximum.Text = Maximum(value1, value2, value3) 15 End Sub ' cmdMaximum_Click ' find maximum of three parameter values 18 Function Maximum(ByVal valueOne As Double, ByVal valueTwo As Double, ByVal valueThree As Double) As Double Return Math.Max(Math.Max(valueOne, valueTwo), valueThree) 21 End Function ' Maximum End Class ' FrmMaximum Event handler btnMaximum_Click Handles the event in which Button btnMaximum is clicked EX1- Maximum Number

EX2- Sorting Array Bubble Sort (a.k.a. sinking sort) Bubble Sort (a.k.a. sinking sort) – Smaller values “bubble” their way to the top of the array, (i.e. toward the first element) – Larger values “sink” to the bottom of the array, (i.e. toward the end) – The bubble sort is easy to program, but runs slowly Becomes apparent when sorting large arrays Becomes apparent when sorting large arrays

1 Public Class FrmBubbleSort 2 Dim array As Integer() = New Integer(9) { } 3 ' sort array using bubble sort algorithm 4 Sub BubbleSort(ByVal sortArray As Integer()) 5 Dim pass, i As Integer 6 7 For pass = 1 To sortArray.GetUpperBound(0) 8 9 For i = 0 To sortArray.GetUpperBound(0) If sortArray(i) > sortArray(i + 1) Then 12 Swap(sortArray, i) 13 End If 14 Next 15 Next 16 End Sub ' BubbleSort Sub Swap(ByVal swapArray As Integer(), ByVal first As Integer) 19 Dim hold As Integer 20 hold = swapArray(first) 21 swapArray(first) = swapArray(first + 1) 22 swapArray(first + 1) = hold 23 End Sub ' Swap 1.Sub BubbleSort 2.Sub Swap 3.Sub cmdCreate_Click 4.Sub cmdSort_Click

24 25 ' creates random generated numbers 26 Private Sub cmdCreate_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdCreate.Click Dim output As String 30 Dim randomNumber As Random = New Random() 31 Dim i As Integer 32 txtSorted.Text = " “ 33 ' create 10 random numbers and append to output 34 For i = 0 To array.GetUpperBound(0) 35 array(i) = randomNumber.Next(100) 36 output &= array(i) & vbCrLf 37 Next txtOriginal.Text = output ' display numbers 40 cmdSort.Enabled = True ' enables cmdSort button 41 End Sub ' cmdCreate_Click txtOriginal.Text txtSorted.Text cmdCreate cmdSort

42 ' randomly generated numbers 44 Private Sub cmdSort_Click(ByVal sender As System.Object, _ 44 ByVal e As System.EventArgs) Handles cmdSort.Click Dim output As String 47 Dim i As Integer ' sort array 50 BubbleSort(array) ' creates string with sorted numbers 53 For i = 0 To array.GetUpperBound(0) 54 output &= array(i) & vbCrLf 55 Next txtSorted.Text = output ' display numbers 58 cmdSort.Enabled = False 59 End Sub ' cmdSort_Click End Class ' FrmBubbleSort

EX3- Searching Arrays: Linear Search Searching – The process of locating a particular element value in an array Linear Search – Simple searching technique – Works well for small or unsorted arrays

1 Public Class FrmLinearSearchTest 2 3 Dim array1 As Integer() = New Integer(19) {} 4 ' iterates through array 5 6 Function LinearSearch(ByVal key As Integer, ByVal numbers As Integer()) As Integer 7 8 Dim n As Integer 9 10 ' structure iterates linearly through array 11 For n = 0 To numbers.GetUpperBound(0) If numbers(n) = key Then Return n 16 End If Next Return End Function ' LinearSearch Compares each element of the array with a search key If the search key is not found, the procedure returns –1, a non-valid index number 1.Function LinearSearch 2.Sub cmdCreate_Click 3.Sub cmdSearch_Click

22 ' creates random data 23 Private Sub cmdCreate_Click(ByVal sender As System.Object, _ 24 ByVal e As System.EventArgs) Handles cmdCreate.Click Dim output As String 27 Dim randomNumber As Random = New Random() 28 Dim i As Integer output = "Index" & vbTab & "Value" & vbCrLf 31 ' creates string containing 11 random numbers 32 For i = 0 To array1.GetUpperBound(0) 33 array1(i) = randomNumber.Next(1000) 34 output &= i & vbTab & array1(i) & vbCrLf 35 Next txtData.Text = output ' displays numbers 38 txtInput.Text = "" ' clear search key text box 39 cmdSearch.Enabled = True ' enable search button 40 End Sub ' cmdCreate_Click txtData lblResult cmdSearch cmdCreate txtInput

41 ' searches key of element 42 Private Sub cmdSearch_Click(ByVal sender As System.Object, _ 43 ByVal e As System.EventArgs) Handles cmdSearch.Click ' if search key text box is empty, display 46 ' message and exit procedure 47 If txtInput.Text = "" Then 48 MessageBox.Show("You must enter a search key.") 49 Exit Sub 50 End If Dim searchKey As Integer = Convert.ToInt32(txtInput.Text) 53 Dim element As Integer = LinearSearch(searchKey, array1) If element <> -1 Then 56 lblResult.Text = "Found Value in index " & element 57 Else 58 lblResult.Text = "Value Not Found" 59 End If End Sub ' cmdSearch_Click End Class ' FrmLinearSearch

Conclusion Experience has shown that the best way to develop and maintain a large program is to construct it from small, manageable pieces. This technique is known as divide and conquer. Visual Basic programs consist of many pieces, including modules and classes. Three types of procedures exist: Sub procedures, Function procedures and event procedures.

The characteristics of Function procedures are similar to those of Sub procedures. However, Function procedures return a value to the caller. If a Function procedure body does not specify a Return statement, program control returns to the point at which a procedure was invoked when the End Function keywords are encountered. Conclusion

Option Explicit, which is set to On by default, forces the programmer to declare all variables explicitly before they are used in a program. Forcing explicit declarations eliminates spelling errors and other subtle errors that may occur if Option Explicit is turned Off. Option Strict, which is set to Off by default, increases program clarity and reduces debugging time. When set to On, Option Strict requires the programmer to perform all narrowing conversions explicitly. Conclusion