8.2 Procedures Function Procedures 20/04/2017.

Slides:



Advertisements
Similar presentations
JAVA Coursework (the same for 2A and 2B). Fundamental Information The coursework is 30 marks in your O’Level = 15% of the exam Must be word processed.
Advertisements

Tutorial 8: Developing an Excel Application
30/04/ Selection Nested If structures & Complex Multiple Conditions.
Chapter 10 Introduction to Arrays
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Chapter 9 Introduction to Arrays
Chapter 1 Program Design
Fundamentals of Python: From First Programs Through Data Structures
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
08/09/ Arrays Defining, Declaring & Processing.
SPELLING GAME PROJECT SAMPLE ASSESSMENT MATERIAL GCSE Computing.
Array Processing Simple Program Design Third Edition A Step-by-Step Approach 7.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
11 Finding Winners Using Arrays Session 8.2. Session Overview  Find out how the C# language makes it easy to create an array that contains multiple values.
© 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 12: How Long Can This Go On?
First tutorial.
1 2.2 Selection Logical Operators. 2 Learning Objectives Explain how the logical operator AND Boolean statements works.
Chapter 10: Structures and Sequential Access Files
By the end of this session you should be able to...
19/10/20151 Data Structures Arrays. 219/10/2015 Learning Objectives Explain initialising arrays and reading data into arrays. Design and write routine/s.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
VB Games: Preparing for Memory Brainstorm controls & events Parallel structures (again), Visibility, LoadPicture, User-defined procedures, Do While/Loop,busy.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 5 Arrays.
27/05/ Iteration Loops Nested Loops & The Step Parameter.
30/10/ Iteration Loops Do While (condition is true) … Loop.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Visual Basic Programming
04/11/ Arrays 1D Arrays Defining, Declaring & Processing.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
22/11/ Selection If selection construct.
The Software Development Process
ITI 1120 Lab #5 Contributors: S. Boyd, R. Plesa, A. Felty, D. Inkpen, A. Williams, D. Amyot.
18/12/ Arrays 2D Arrays Defining, Declaring & Processing.
Top-down approach / Stepwise Refinement & Procedures & Functions.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
04/02/ Procedures Top-down approach / Stepwise Refinement & Sub Procedures.
05/02/ Records. 205/02/2016 Learning Objectives State: The difference between records and arrays. The difference between records and arrays. How.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
1 The Software Development Process ► Systems analysis ► Systems design ► Implementation ► Testing ► Documentation ► Evaluation ► Maintenance.
Programming Problems Intermediate 2 Computing SHOW YOUR TEACHER YOUR WORKING PROGRAM AND WRITING FRAME THEN SAVE IN YOUR PROGRAMMING FOLDER AND UPDATE.
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.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
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.
CIS 115 All Exercises Devry University (Devry) FOR MORE CLASSES VISIT CIS 115 All Exercises Devry University.
3.1 Fundamentals of algorithms
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.
The Selection Structure
Top-down approach / Stepwise Refinement & Sub Procedures
If selection construct
Do While (condition is true) … Loop
4.1 Strings ASCII & Processing Strings with the Functions
If selection construct
Do … Loop Until (condition is true)
1D Arrays Defining, Declaring & Processing
Text / Serial / Sequential Files
3.1 Iteration Loops For … To … Next 18/01/2019.
Random Access Files / Direct Access Files
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
10.3 Procedures Function Procedures 07/06/2019.
Text / Serial / Sequential Files
Introduction to Computer Programming IT-104
10.2 Procedures Passing Parameters 30/08/2019.
Presentation transcript:

8.2 Procedures Function Procedures 20/04/2017

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

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

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.

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

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.

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

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

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

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

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

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

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

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

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. http://sqa.fyicenter.com/FAQ/Manual-Testing/What_is_stub_Explain_in_testing_point_of_view_.html http://en.wikipedia.org/wiki/Test_stub 20/04/2017

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?

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

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

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

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 1 - 50. 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.

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

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

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.

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.

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.

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

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

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

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.

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.

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.

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.

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.

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.

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.

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

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.

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.

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.

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.

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

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

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

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