Presentation is loading. Please wait.

Presentation is loading. Please wait.

8.2 Procedures Function Procedures 20/04/2017.

Similar presentations


Presentation on theme: "8.2 Procedures Function Procedures 20/04/2017."— Presentation transcript:

1 8.2 Procedures Function Procedures 20/04/2017

2 Learning Objectives Describe the difference between functions and sub procedures. Explain how to write and call functions. 20/04/2017

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

4 Built-in & User-defined Functions
Built-in Functions Supplied by VB, some of which you have used previously e.g. Round, Mid, Random, Instr, Div, CharW, Asc, Len, … User-defined Functions Written by the programmer. You will learn to write these here. 20/04/2017

5 Structure Chart Area of “house” Area of rectangle Area of triangle
RectangleWidth TriangleBase TriangleArea RectangleLength TriangleHeight HouseArea RectangleArea AreaTriangle Area of rectangle Area of triangle Area of rectangle + triangle Function: Function: Function: Note that the variable to be returned no longer has to be sent to Function procedures (as they do to Sub Procedures – see 8.1 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.

6 AreaTriangle = ½ * TriangleHeight * TriangleBase
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

7 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) 20/04/2017 Continued on the next slide.

8 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) 20/04/2017

9 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 20/04/2017

10 Program 8.2a 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. 20/04/2017

11 Program 8.2a 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 (€ €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. 20/04/2017

12 Program 8.2a Calculating Interest
Create a new project named ‘Calculating Interest’.

13 Program 8.2a Calculating Interest
Dim Interest As Decimal Dim Amount As Decimal Dim InterestRate As Single Dim Years As Integer Console.WriteLine(“Please enter the amount of money to be deposited.) Amount = Console.ReadLine Console.WriteLine(“Please enter the interest rate.) InterestRate = Console.ReadLine Console.WriteLine(“Please enter the number of years the money will be deposited.) Years = Console.ReadLine ‘Call the CalcInterest function by passing it the relevant ‘parameters and assigning it to the variable Interest. Interest = CalcInterest(Amount, InterestRate, Years) Console.WriteLine(“€” & Interest) 20/04/2017

14 Program 8.2a 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

15 Program 8.2a Calculating Interest
Run the program and test it. 20/04/2017

16 Stub Testing A stub is a “dummy” procedure/function which is used because the actual real procedure/function is not ready. e.g. If the main program in “8.2a Calculating Interest” for accepting input and displaying the interest has been written but the function for actually calculating the interest has not, we could write a “dummy function” which returns a “pretend” interest value to see if the main program appears to function. Obviously the actual interest would not yet have any connection to the inputs so it cannot be fully tested, but it would give us a sense of testing. 20/04/2017

17 Commenting on Functions
For presentations 8.1 & 8.2 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?

18 Given Pseudocode will use the following structure for function definitions:
FUNCTION <identifier> RETURNS <data type> function has no parameters <statement(s)> ENDFUNCTION FUNCTION <identifier> (<identifier>: <data type>) RETURNS <data type> function has one or more parameters Functions used in an expression, for example: x ← SQRT(n) WHILE NOT EOF(<fi lename>) 20/04/2017

19 Extension “Number Array” Program 8.2b
Open the “Program 5.1a Number Array” – 5.1 Arrays. Separate the “SumHighLowRangeProc” procedure into 4 functions. Sum Highest Lowest Range The basic loop will have to be repeated each time. 20/04/2017

20 Extension Programs Open any of the programs you have written previously and move appropriate lines into appropriate functions. Particularly look at extension programs written in from 5.1 Arrays on. 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. 20/04/2017

21 Extension “Lottery Game”
A lottery game draws six numbers between 1 and 50, which are all different. A computer program is to be developed to simulate the drawing of the six numbers. Write a procedure to initialise an array holding the Numbers drawn. Write a function to generate a random number from Use a Boolean array with upper bound 50 to identify duplicates. For example, the array cell with subscript 37 indicates whether or not the number 37 has been drawn. Write a procedure to initialise the array above. Write a “main program” to generate six different numbers using the procedures/functions above. Start with the initialisation procedures and make sure the user can reset and start again, without quitting the program. 20/04/2017 Continued on the next slide.

22 Extension “Hockey Club Winners” Program
A hockey club has 347 members and each week all members pay $1 into a prize draw fund. Each week there is one winner and the winning number is to be generated by a computer program. Write program code to generate a number between 1 and 347. The number of members will change as members leave the club and new members join. Amend the program code so that: the user inputs the current number of members (X) the random number generator is coded as a function which: has a single parameter X returns the winning number. 22

23 Extension “User IDs and Passwords” Program
Extend the “Password Entry” program written in presentations 3.3/3.4: Use a function PasswordCheck with the stored password as a parameter. If the user enters the correct password the function returns the value TRUE. Each time the password is entered incorrectly, the message “Wrong password” is output. If the user enters an incorrect password 3 times, the user is told that access is denied, and the function returns the value FALSE. Use a sequential file of records to store the user IDs and encrypted passwords. When a user types in their User ID, the program calls a function, FindPassword, with parameter ThisUserID. The function searches each record in the file for ThisUserID and returns the encrypted password. If ThisUserID is not stored in the file, the function returns an error code. I suggest creating the file manually first (type in the User IDs and passwords directly into a text file). Program’s folder – folder with name – bin – Debug. See presentation 7.1 Files if you need to remind yourself about how files work etc.. 23

24 Extension “Football Club Members Winners”
A football club is owned by its fans and currently has 3089 members. The data about members is held in a file MEMBERS.DAT. Each member is given a member number. For each of the 23 home games, there is a prize draw with the member drawn gifted $100. Once a member is a winner, they cannot win again. The lucky member number is to be selected each week by a computer program. Hence, for the draw for the first week, it will generate a member number between 1 and 3089. 20/04/2017 Continued on the next slide.

25 Extension “Football Club Members Winners”
The MEMBERS.DAT file is a text file with the following structure. Each member’s data is a single line of text, consisting of: four characters for the member number (fixed length) a <Space> character member name (variable length). 20/04/2017 Continued on the next slide.

26 Extension “Football Club Members Winners”
A second serial file PREVIOUSWINNERS.DAT stores the member numbers of all past winners. The diagram shows the file after five home games. 20/04/2017 Continued on the next slide.

27 Extension “Football Club Members Winners”
Use the identifiers as shown in the table below: 20/04/2017 Continued on the next slide.

28 Extension “Football Club Members Winners”
Complete the structure chart. Write the program discussed as shown below. Continued on the next slide. 20/04/2017

29 Extension “Football Club Members Winners”
A student is investigating how many items customers purchase when visiting a supermarket. She collects data for 100 customers which shows the following: Write program code to generate the sequence of number of items purchased for the random arrival of 500 customers, based on the given data. Code the number of items generated for each customer as a function NumberOfItems(). Do not attempt to summarise these as a distribution table. 20/04/2017

30 Extension “Sports Tally”
Extend the “Sports Tally” program written in presentation 3.4 Iteration Loops. Use a one-dimensional array, Tally, instead of four variables to store the counts. Modularise the design. The main program should just consist of three procedure calls: InitialiseArrayCounts InputStudentChoices OutputTallyChart outputs the first two columns of the tally chart and then calls OutputTally to output the correct number of bars (\). The output should look like this: Write this program.

31 Extension “Learn Multiplication Tables” Program
A teacher wants to write a program to help young children learn their multiplication tables between 1 and 10. If the child chooses the number 7, the screen displays: The algorithm to produce this output is represented by the flowchart shown: The program needs the following three integer variables: Number i Result Write this ‘main’ program. 20/04/2017 Continued on the next slide.

32 Extension “Learn Multiplication Tables” Program
The teacher then wants the program to: show a visual representation of a multiplication ask the child to key in an answer. For example, the multiplication of 3 × 4 is represented as shown. Add the code for this in the main program but note: I suggest you ask the child if they want to show another times table or start the test first. If the child wants to start the test I suggest you use: Console.Clear() ‘Clear the console. Use a function Random(X) that returns a whole number in the range 1 to X inclusive. Note that the previous slide stated that the teacher wants the children learn the multiplication tables between 1 and 10, so in the main program this function will be used with X as 10. Use a procedure Display(Number1, Number2) to display the question as shown above. Use a procedure ShowMultiplicationGrid(Number1, Number2) to produce the grid of asterisks (*) . Called from Display(Number1, Number2) above. Continued on the next slide.

33 Extension “Learn Multiplication Tables” Program
Write a function CheckAnswerCorrect that gives a child three chances to type in the correct answer. The function returns TRUE if the child typed the correct answer, and FALSE if all three attempts are incorrect. Complete the flowchart opposite, using the given statements. Now write this function and use it appropriately in the main program. I suggest: Do …. Loop Until CheckAnswerCorrect = False 20/04/2017 Continued on the next slide.

34 Extension “Learn Multiplication Tables” Program
The teacher now wants the program to output the number of questions the child answers correctly before the program stops. Now write this as a function TestScoreTotal that returns the number of questions answered correctly and use it appropriately in the main program. Note: Random(X), Display(Number1, Number2) and CheckAnswerCorrect will be used in this TestScoreTotal function now so move their use from the main program into this function. I suggest that in the main program you simply display the result of the TestScoreTotal function. e.g. Console.WriteLine(“The number of questions you answered correctly was: “ & TestScoreTotal ) 20/04/2017 Continued on the next slide.

35 Extension “Learn Multiplication Tables” Program
During the school day, several children in the class will use this program. The teacher wants to store each child’s name and their best test score so far. Assume there will be no more than 30 children in the class. In the main program: Declare a record structure StudentScore to store the data for one child. Declare a one-dimensional array of records to store the data for the whole class. Use the identifier Student. Write a function FindArrayIndex to return the array index of the record in which the child’s name is stored in the Student array or the next available new array index if the child is new. Use this function appropriately in the main program. See the next slide for some hints. 20/04/2017 Continued on the next slide.

36 Extension “Learn Multiplication Tables” Program
e.g. As the TestScoreTotal function is now needed twice, I suggest now storing the value returned. NumberOfCorrectQuestions = TestScoreTotal Console.WriteLine(“The number of questions you answered correctly was: “ & NumberOfCorrectQuestions) If NumberOfCorrectQuestions > Student (Score. FindArrayIndex) Then Make sure that if a student types a mixture of upper and lower case letters (e.g. ALI and Ali), the program allows for this treats them as the same name. Write a procedure to display all students’ names and test scores. Call this procedure in the appropriate location in the main program. 20/04/2017 Continued on the next slide.

37 Extension “Learn Multiplication Tables” Program
The teacher wants to store in a file the name and best score so far for each of the children. Write a procedure, SaveToFile, to save the data stored in the Student array of records. The data must be stored in a file named StudentFile. Note that you will have to write a procedure which is called at the beginning of the main program, to copy the contents of StudentFile into the array Student, every time the program starts. 20/04/2017

38 Extension “Token Game”
A game is played by two players. Player A uses white tokens ( ). Player B uses black tokens ( ). The players take turns dropping tokens into a vertical grid. The tokens fall straight down and occupy the next available space in the chosen column. The aim of the game is to connect four of one’s own colour tokens. This must be done in a vertical, horizontal or diagonal line. Here is one example after Player A has had 2 turns and Player B has had 1 turn: Nathan wants to write a program to allow two users to play the game on the computer. The program will display a simplified version of the above grid which is redrawn after every turn. Continued on the next slide.

39 Extension “Token Game”
Before any tokens have been dropped into the grid, all grid cells are empty. The array Grid is to be used to represent the contents of the game grid. After a player takes their turn, the new state of the grid is to be displayed on the screen. The display will show only the cell contents. Write a main program to initialise the array Grid and implement the algorithm represented by the flowchart. To drop a token into the grid, the player enters the chosen column number. The function ColumnNumberValid has a parameter (x) which is the chosen column number. The function returns: TRUE if x is between 1 and 7 inclusive and there is still space in the column FALSE otherwise Write this function. Continued on the next slide.

40 Extension “Token Game”
The program stores in the variable NextPlayer the character 'A' or 'B' to show whose turn it is next. The chosen column number is validated using the function from part on the last slide ColumnNumberValid . The program then sets the relevant empty grid cell to the player’s token value. Write the code to do this at an appropriate location in the main program code written earlier on the last slide. Continued on the next slide.

41 Extension “Token Game”
Nathan wants a single player to play against the computer. He uses the built-in function RANDOM(n) to simulate the computer’s choice of column. This function returns a whole number in the range 1 to n inclusive. Write a procedure GetColumn to input the next move either from the computer or Player ‘B’. This procedure has two parameters which are passed either by reference or by value. Call this procedure at the appropriate place in the main program code written earlier on the last slide. The exam question did not ask for this but obviously there is no function to see if a player has won. If you wish to try this please feel free.

42 Extension “Factorial Iterative Function” Program
Change the “Factorial” Program 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). 20/04/2017

43 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. 20/04/2017

44 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 20/04/2017

45 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) 20/04/2017


Download ppt "8.2 Procedures Function Procedures 20/04/2017."

Similar presentations


Ads by Google