10.3 Procedures Function Procedures 07/06/2019.

Slides:



Advertisements
Similar presentations
30/04/ Selection Nested If structures & Complex Multiple Conditions.
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
8.2 Procedures Function Procedures 20/04/2017.
Creating Embedded Formative Assessment Dr. Steve Broskoske Misericordia University EDU 533 Computer-based Education.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
07/10/ Strings ASCII& Processing Strings with the Functions - Locate (Instr), Mid, Length (Len), Char (ChrW) & ASCII (Asc)
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Chapter 4: The Selection Process in Visual Basic.
Programming Examples to Accompany Structure Topic Please use speaker notes for additional information!
Problem Solving with the Sequential Logic Structure Lesson 5 McManusCOP10061.
1 2.2 Selection Logical Operators. 2 Learning Objectives Explain how the logical operator AND Boolean statements works.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
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.
30/10/ Iteration Loops Do While (condition is true) … Loop.
04/11/ Arrays 1D Arrays Defining, Declaring & Processing.
B065: PROGRAMMING Sub Procedures I. Starter  Identify the separate tasks to be performed in the programming task below (break it down into numbered sections).
22/11/ Selection If selection construct.
Practical Programming COMP153-08S Week 5 Lecture 1: Screen Design Subroutines and Functions.
‘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.
Top-down approach / Stepwise Refinement & Procedures & Functions.
Pay Example (PFirst98) Please use speaker notes for additional information!
Debugging, Static Variables, ByRef, ByValue Chapt. 6 in Deitel, Deitel and Nieto.
Programming with Microsoft Visual Basic th Edition
31/01/ Selection If selection construct.
04/02/ Procedures Top-down approach / Stepwise Refinement & Sub Procedures.
02/03/ Strings Left, Right and Trim. 202/03/2016 Learning Objectives Explain what the Left, Right and Trim functions do.
1 4.2 Selection Logical Operators. 2 Learning Objectives Explain how the logical operator AND Boolean statements works. Directly testing if text boxes.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
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.
26/06/ Iteration Loops For … To … Next. 226/06/2016 Learning Objectives Define a program loop. State when a loop will end. State when the For.
A variable is a name for a value stored in memory.
User-Written Functions
COMPUTATIONAL CONSTRUCTS
IGCSE 4 Cambridge Data types and arrays Computer Science Section 2
Data Types Variables are used in programs to store items of data e.g a name, a high score, an exam mark. The data stored in a variable is entered from.
Lesson 16 Sub Procedures Lesson 17 Functions
Spreadsheet-Based Decision Support Systems
The Selection Structure
JavaScript: Functions
Top-down approach / Stepwise Refinement & Sub Procedures
Coding Concepts (Sub- Programs)
If selection construct
Do While (condition is true) … Loop
PROGRAMMING Sub Procedures I.
4.1 Strings ASCII & Processing Strings with the Functions
Introduction to Visual Programming
Sub Procedures and Functions
If selection construct
Do … Loop Until (condition is true)
Text / Serial / Sequential Files
3.1 Iteration Loops For … To … Next 18/01/2019.
Nested Loops & The Step Parameter
Maintaining a Program In today’s lesson we will look at:
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
The structure of programming
Yan Shi CS/SE 2630 Lecture Notes
Programming In Lesson 4.
Review of Previous Lesson
GCSE Computing:: Selection (IF statements)
Algorithms For use in Unit 2 Exam.
Text / Serial / Sequential Files
3.2 Working with Data Scope of variables 29/07/2019.
Introduction to Computer Programming IT-104
10.2 Procedures Passing Parameters 30/08/2019.
Lecture 20 – Practice Exercises 4
Python Creating a calculator.
Presentation transcript:

10.3 Procedures Function Procedures 07/06/2019

Learning Objectives Describe the difference between functions and sub procedures. Explain how to write and call functions. 07/06/2019

Function Procedures Known as just functions for short (sub procedures are known as just procedures for short). Always returns one item of data to the calling procedure. Remember that: Sub procedures: May return one or more items of data or no data at all to the calling procedure. If only one value is to be returned then a Function is more suitable, if two or more values (or no values) need to be returned then a procedure is more suitable.

Built-in & User-defined Functions Built-in Functions Supplied by VB, some of which you have used previously e.g. Format, Mid, Today User-defined Functions Written by the programmer. You will learn to write these here. 07/06/2019

AreaTriangle = ½ * TriangleHeight * TriangleBase Functions: CalcTriangleArea Main Program TriangleHeight AreaTriangle = ½ * TriangleHeight * TriangleBase Input TriangleHeight Input TriangleBase Input RectangleWidth Input RectangleLength CalcTriangleArea CalcRectangleArea CalcHouseArea Output HouseArea TriangleBase TriangleArea CalcAreaRectangle RectangleLength AreaRectangle = RectangleWidth * RectangleBreadth RectangleWidth RectangleArea AreaRectangle CalcHouseArea AreaTriangle HouseArea = AreaTriangle + AreaRectangle Parameters HouseArea Note that the variable to be returned no longer has to be sent to Function procedures (as they do to Sub Procedures – see 10.2 Procedures), so all formal parameters are value parameters. A function just returns one answer and it is left up to the main program to “know” what that answer means.

Writing a Function Similar to Sub procedures. Differences: Its job is to return only one item of data. So all formal parameters are value parameters (see the last slide). i.e. Declared with ByVal Starts with Private Function instead of Sub. The first line of the function (after the Private Function…) has to declare the variable which will be returned: Dim (Variable Name to be returned) As (Data Type) 07/06/2019 Continued on the next slide.

Writing a Function The last line of the function (before the End Function) will return the one item of data to the calling procedure: Return (Variable name to be returned) When the function is called you treat it as a value (i.e. the value it returns). Store it in a variable: VariableName = FunctionName(Variables to be passed) Display it directly: Control.Text = FunctionName(Variables to be passed) 07/06/2019

Writing a Function i.e. Private Function …(ByVal … As …, By Val… As …) Dim (Variable name to be returned) As (Data Type) … Return (Variable name to be returned) End Function 07/06/2019

Program 10.3 Calculating Interest Specification: Write a function to calculate the amount of interest earned on an investment. The amount invested, the interest rate and the number of years the investment lasts, are to be entered by the user. 07/06/2019

Program 10.3 Calculating Interest If you invested €1000 over 2 years at an interest rate of 10% per year then the interest paid after one year would be €100. i.e. 10% of €1000 In year 2 you would get 10% of (€1000 + €100 = €1100) i.e. €110 So the total interest paid would be €210 after 2 years. This program will calculate the interest paid for a given number of years. 07/06/2019

Program 10.3 Calculating Interest Create a new project named ‘Calculating Interest’. txtAmount txtInterestRate txtYears lblInterest butCalcInterest

Program 10.3 Calculating Interest butCalcInterest code: Dim Interest As Decimal Dim Amount As Decimal Dim InterestRate As Single Dim Years As Integer Amount = txtAmount.Text InterestRate = txtInterestRate.Text Years = txtYears.Text ‘Call the CalcInterest function by passing it the relevant ‘parameters and assigning it to the variable Interest. Interest = CalcInterest(Amount, InterestRate, Years) lblInterest.Text = “€” & Interest 07/06/2019

Program 10.3 Calculating Interest Create a function: Private Function CalcInterest(ByVal Amount _ As Decimal, ByVal InterestRate As Single, _ ByVal Years As Integer) Dim Interest As Decimal ‘Variable to be returned. ‘For the loop to calculate year on year up to the number of ‘years the user entered. Dim Year As Integer For Year = 1 To Years Interest = Interest + ((Amount + Interest) * _ InterestRate / 100) Next Year Return Interest ‘Return the variable Interest. End Function

Program 10.3 Calculating Interest Run the program and test it. 07/06/2019

Program 10.3 Calculating Interest Write a “Boolean” function to test if the data entered in the text boxes is numeric. Private Function NumericFN Dim Numeric As Boolean = True If IsNumeric (txtAmount.Text) = False Or IsNumeric (txtInterestRate.Text) = False Or IsNumeric (txtYears.Text) = False Then Numeric = False End If Return Numeric End Function 07/06/2019

Program 10.3 Calculating Interest Test this function before the Dim lines in the butCalcInterest code: If NumericFN = False Then MsgBox (“Please only enter numbers!”) Exit Sub End If 07/06/2019

Commenting on Functions In presentations 10.1 – 10.3 I will only ask for comments to procedures/functions. Your comments MUST explain: What is the procedure/function for? Why and when (after and before what) are you calling it? What parameters are being sent to it and why? What parameter/s is/are being returned and why?

Extension “Average” Program 1 Open Program 3.4 Average you used last lesson. Make the sub-procedure CalcMean into a function. This is appropriate because CalcMean returns only one variable i.e. Mean. Write a Boolean function to test for numeric data. 07/06/2019

Extension “Factorial Iterative Function” Program 1 Change the “Factorial” Program - 5.1 Loops so that it uses a function. This is called an iterative function. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Iterative Function Version). 07/06/2019

Extension Programs 2 Open any of the programs you have written previously and move appropriate lines into appropriate functions. Particularly look at the original programs written in 3.1 Working with Data. e.g. “Discount” Program “Selling Price” Program “Interest” Program etc.... Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Function Version). Do this for as many programs as you need to until you are confident in creating functions. 07/06/2019

Extension “Factorial Recursive Function” Program 3 Change the “Factorial” Program (Iterative Version) in presentation 5.1 Loops so that it uses a recursive function. Hint: FUNCTION calc(n) IF n = 1 THEN calc ← 1 ELSE calc ← n * calc(n-1) ENDIF RETURN calc Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Recursive Function Version). 07/06/2019

Extension “Adding Numbers from 1 to a chosen number” Program 4 Change the “Adding Numbers from 1 to a chosen number” Program (Iterative Version) in presentation 5.1 Loops so that it uses a recursive function. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Recursive Function Version).

Extension “Adding Numbers between two chosen numbers” Program 5 Change the “Adding Numbers between two chosen numbers” Program (Iterative Version) in presentation 5.1 Loops so that it uses a recursive function. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Recursive Function Version).

Extension “Adding Numbers from one chosen number to 6 then add 1” Program 6 Change the “Adding Numbers from one chosen number to 6 then add 1” Program (Iterative Version) in presentation 5.1 Loops so that it uses a recursive function. Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the same name but add (Recursive Function Version).

When to Use Recursion? Neat, cleaner and more elegant answer compared to the iterative version. Writing recursive functions can give you greater confidence that you are coding correctly. Often, writing code that ought to be recursive without recursion (i.e., as loops) produces messy code. Recursion often produces solutions that are very compact (requires few lines of typed code). So easier to debug than code with many lines. Recursive solutions can be VERY inefficient though. In general, recursion should be used when you know the number of recursive calls isn't excessive which depends on how much memory you have. Maximum: ~ 1000 recursive calls. A large number of function calls could cause stack overflow. Iteration can be simpler to understand and easier to write so less chance of error though. http://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html 07/06/2019

Plenary What is the difference between functions and sub procedures? Function Procedures Always returns one item of data to the calling procedure. Sub procedures: May return one or more items of data or no data at all to the calling procedure. 07/06/2019

Plenary How do we write functions? Private Function …(ByVal … As …, ByVal… As …) Dim (Variable name to be returned) As (Data Type) … Return (Variable name to be returned) End Function 07/06/2019

Plenary How do we call functions? Assign a function’s return value to a variable. (Variable name) = (Function Name)(Parameters) Display a function’s return value e.g. to the text property of a control. (Control Name).Text = (Function Name)(Parameters) 07/06/2019