45
10/06/22 10/06/22 1 8.2 Procedures 8.2 Procedures Function Procedures Function Procedures

30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Embed Size (px)

Citation preview

Page 1: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

21/04/2321/04/23 11

8.2 Procedures8.2 Procedures

Function ProceduresFunction Procedures

Page 2: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

2221/04/2321/04/23

Learning ObjectivesLearning Objectives

Describe the difference between functions Describe the difference between functions and sub procedures.and sub procedures.

Explain how to write and call functions.Explain how to write and call functions.

Page 3: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

33

Function ProceduresFunction ProceduresKnown as just Known as just functionsfunctions for short for short (sub procedures (sub procedures are known as just are known as just proceduresprocedures for short). for short).

Always returns one item of data to the calling Always returns one item of data to the calling procedure.procedure. Remember that:Remember that:

Sub procedures:Sub procedures: May return one or more items of data or no data at all to the calling May return one or more items of data or no data at all to the calling

procedure.procedure.

If only If only one value is to be returned one value is to be returned then athen a Function Function is more is more suitablesuitable, , if if two or more values (or no values) two or more values (or no values) need to be returned then a procedure is more suitableneed to be returned then a procedure is more suitable ..

Page 4: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

4421/04/2321/04/23

Built-in & User-defined FunctionsBuilt-in & User-defined Functions

Built-in FunctionsBuilt-in Functions Supplied by VB, Supplied by VB, some of which you have used previously e.g. some of which you have used previously e.g.

Round, Mid, Random, Instr, Div, CharW, Asc, Round, Mid, Random, Instr, Div, CharW, Asc, Len, …Len, …

User-defined FunctionsUser-defined FunctionsWritten by the programmer.Written by the programmer.

You will learn to write these here.You will learn to write these here.

Page 5: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Structure ChartArea of

“house”

Area of rectangle

Area of triangle

Area of

rectangle + triangle

RectangleWidthRectangleWidth

RectangleLengthRectangleLength

HouseAreaHouseArea

TriangleBaseTriangleBase

TriangleHeightTriangleHeight

TriangleAreaTriangleArea

RectangleAreaRectangleArea

RectangleAre

a

RectangleAre

a

AreaTriangleAreaTriangle

Note that the variable to be returned no longer has to be sent to Function procedures (as they do to Note that the variable to be returned no longer has to be sent to Function procedures (as they do to Sub Procedures – see Sub Procedures – see 8.1 Procedures), so all formal parameters are value parameters. A ), so all formal parameters are value parameters. A functionfunction just returns just returns oneone answer and it is left up to the main program to “know” what that answer means. answer and it is left up to the main program to “know” what that answer means.

FunctionFunction:: FunctionFunction::FunctionFunction::

Page 6: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Input TriangleHeight Input TriangleHeight

Input TriangleBaseInput TriangleBase

Input RectangleWidth Input RectangleWidth

Input RectangleLengthInput RectangleLength

CalcTriangleAreaCalcTriangleArea

CalcRectangleAreaCalcRectangleArea

CalcHouseAreaCalcHouseArea

Output HouseAreaOutput HouseArea

HouseArea = HouseArea = AreaTriangle + AreaTriangle + AreaRectangle AreaRectangle

AreaTriangle = ½ * AreaTriangle = ½ * TriangleHeight TriangleHeight * TriangleBase* TriangleBase

AreaRectangle = AreaRectangle = RectangleWidth * RectangleWidth * RectangleBreadthRectangleBreadth

TriangleHeightTriangleHeightTriangleHeightTriangleHeight

TriangleBaseTriangleBaseTriangleBaseTriangleBase

RectangleWidthRectangleWidthRectangleLengthRectangleLength

CalcTriangleAreaCalcTriangleAreaCalcTriangleAreaCalcTriangleArea

TriangleAreaTriangleAreaTriangleAreaTriangleArea

CalcAreaRectangleCalcAreaRectangleCalcAreaRectangleCalcAreaRectangle

RectangleAreaRectangleArea

CalcHouseAreaCalcHouseAreaCalcHouseAreaCalcHouseAreaAreaTriangleAreaTriangle

AreaRectangleAreaRectangle

HouseAreaHouseArea

Main ProgramMain ProgramMain ProgramMain Program

ParametersParameters

Page 7: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

7721/04/2321/04/23

Writing a FunctionWriting a Function

Similar to Sub procedures.Similar to Sub procedures.Differences:Differences: Its job is to return only one item of data.Its job is to return only one item of data. So all formal parameters are value parameters So all formal parameters are value parameters

(see the last slide)(see the last slide)..i.e. Declared with i.e. Declared with ByValByVal

Starts with Private Starts with Private FunctionFunction instead of instead of SubSub.. The first line of the function (after the Private The first line of the function (after the Private

Function…) has to declare the variable which Function…) has to declare the variable which will be returned:will be returned:

DimDim (Variable Name to be returned) (Variable Name to be returned) As As (Data Type)(Data Type)

Continued on the next slide.Continued on the next slide.

Page 8: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

8821/04/2321/04/23

Writing a FunctionWriting a Function

The last line of the function (before the End The last line of the function (before the End Function) will return the one item of data to the Function) will return the one item of data to the calling procedure:calling procedure:

ReturnReturn (Variable name to be returned) (Variable name to be returned) When the function is called you treat it as a When the function is called you treat it as a

value (i.e. the value it returns).value (i.e. the value it returns).Store it in a variable:Store it in a variable:

VariableNameVariableName = FunctionName( = FunctionName(Variables to be passedVariables to be passed))

Display it directly:Display it directly: ControlControl.Text = FunctionName(.Text = FunctionName(Variables to be passedVariables to be passed))

Page 9: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

9921/04/2321/04/23

Writing a FunctionWriting a Function

i.e.i.e. Private Function …(ByVal … As …, Private Function …(ByVal … As …,

By Val… As …)By Val… As …)DimDim (Variable name to be returned) (Variable name to be returned) As As (Data Type)(Data Type)

……

Return (Variable name to be returned) Return (Variable name to be returned) End FunctionEnd Function

Page 10: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

101021/04/2321/04/23

Program 8.2a Calculating InterestProgram 8.2a Calculating Interest

Specification:Specification: Write a function to calculate the amount of Write a function to calculate the amount of

interest earned on an investment.interest earned on an investment. The amount invested, the interest rate and the The amount invested, the interest rate and the

number of years the investment lasts, are to number of years the investment lasts, are to be entered by the user.be entered by the user.

Page 11: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

111121/04/2321/04/23

Program 8.2a Calculating InterestProgram 8.2a Calculating Interest

If you invested If you invested €1000 over 2 years at an interest €1000 over 2 years at an interest rate of 10% per year then the interest paid after rate of 10% per year then the interest paid after one year would be €100.one year would be €100. i.e. 10% of €1000 i.e. 10% of €1000

In year 2 you would get 10% of (€1000 + €100 = In year 2 you would get 10% of (€1000 + €100 = €1100)€1100) i.e. €110i.e. €110

So the total interest paid would be €210 after 2 So the total interest paid would be €210 after 2 years.years.This program will calculate the interest paid for a This program will calculate the interest paid for a given number of years.given number of years.

Page 12: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Program 8.2a Calculating InterestProgram 8.2a Calculating Interest

Create a new project named ‘Create a new project named ‘Calculating Calculating InterestInterest’.’.

Page 13: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

131321/04/2321/04/23

Program 8.2a Calculating InterestProgram 8.2a Calculating InterestDim Interest As DecimalDim Interest As DecimalDim Amount As DecimalDim Amount As DecimalDim InterestRate As SingleDim InterestRate As SingleDim Years As IntegerDim Years As IntegerConsole.WriteLine(“Please enter the amount of money to be deposited.)Console.WriteLine(“Please enter the amount of money to be deposited.)Amount = Console.ReadLineAmount = Console.ReadLineConsole.WriteLine(“Please enter the interest rate.)Console.WriteLine(“Please enter the interest rate.)InterestRate = Console.ReadLineInterestRate = Console.ReadLineConsole.WriteLine(“Please enter the number of years the money will be Console.WriteLine(“Please enter the number of years the money will be deposited.)deposited.)Years = Console.ReadLineYears = Console.ReadLine‘‘Call the CalcInterest function by passing it the relevant Call the CalcInterest function by passing it the relevant ‘‘parameters and assigning it to the variable Interest.parameters and assigning it to the variable Interest.Interest = CalcInterest(Amount, InterestRate, Years)Interest = CalcInterest(Amount, InterestRate, Years)Console.WriteLine(“Console.WriteLine(“€” & Interest)€” & Interest)

Page 14: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Program 8.2a Calculating InterestProgram 8.2a Calculating Interest

Create a function:Create a function: Private Function CalcInterest(ByVal Amount _Private Function CalcInterest(ByVal Amount _ As Decimal, ByVal InterestRate As Single, _As Decimal, ByVal InterestRate As Single, _ ByVal Years As Integer)ByVal Years As Integer)

Dim Interest As Decimal Dim Interest As Decimal ‘Variable to be returned.‘Variable to be returned.‘‘For the loop to calculate year on year up to the number ofFor the loop to calculate year on year up to the number of‘‘years the user entered.years the user entered.Dim Year As Integer Dim Year As Integer For Year = 1 To YearsFor Year = 1 To Years

Interest = Interest + ((Amount + Interest) * _Interest = Interest + ((Amount + Interest) * _ InterestRate / 100)InterestRate / 100)

Next YearNext YearReturn Interest Return Interest ‘Return the variable Interest.‘Return the variable Interest.

End FunctionEnd Function

Page 15: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

151521/04/2321/04/23

Program 8.2a Calculating InterestProgram 8.2a Calculating Interest

Run the program and test it.Run the program and test it.

Page 16: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

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

161621/04/2321/04/23

http://sqa.fyicenter.com/FAQ/Manual-Testing/What_is_stub_Explain_in_testing_point_of_view_.html

http://en.wikipedia.org/wiki/Test_stub

Page 17: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

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?

Page 18: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Given Pseudocode will use the following Given Pseudocode will use the following structure for function definitions:structure for function definitions:

FUNCTION <identifier> RETURNS <data type>FUNCTION <identifier> RETURNS <data type>function has no parametersfunction has no parameters

<statement(s)><statement(s)>

ENDFUNCTIONENDFUNCTION

FUNCTION <identifier> (<identifier>: <data type>) FUNCTION <identifier> (<identifier>: <data type>) RETURNS <data type>RETURNS <data type>function has one or more parametersfunction has one or more parameters

<statement(s)><statement(s)>

ENDFUNCTIONENDFUNCTION

Functions used in an expression, for example:Functions used in an expression, for example: x ← SQRT(n)x ← SQRT(n) WHILE NOT EOF(<fi lename>)WHILE NOT EOF(<fi lename>)

181821/04/2321/04/23

Page 19: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

191921/04/2321/04/23

Extension Extension “Number Array“Number Array”” Program Program 8.2b8.2b

Open the “Open the “Program 5.1a Number Array” – ” – 5.1 Arrays..

Separate the “Separate the “SumHighLowRangeProc” ” procedure into 4 functions.procedure into 4 functions.1.1. SumSum

2.2. HighestHighest

3.3. LowestLowest

4.4. RangeRange• The basic loop will have to be repeated each time.The basic loop will have to be repeated each time.

Page 20: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

202021/04/2321/04/23

Extension ProgramsExtension Programs

Open any of the programs you have written previously Open any of the programs you have written previously and move appropriate lines into appropriate functions.and move appropriate lines into appropriate functions.

Particularly look at extension programs written in from Particularly look at extension programs written in from 5.1 Arrays 5.1 Arrays on.on.

Make a copy of the previous program’s whole folder to keep the 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 original program but rename this folder with the same name but add ((Function Version)Function Version)..

Do this for as many programs as you need to until you Do this for as many programs as you need to until you are confident in creating functions.are confident in creating functions.

Page 21: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Lottery Game”Extension “Lottery Game”A lottery game draws six numbers between 1 and 50, which A lottery game draws six numbers between 1 and 50, which are all different.are all different.

A computer program is to be developed to simulate the A computer program is to be developed to simulate the drawing of the six numbers.drawing of the six numbers.

Write a procedure to initialise an array holding the Numbers drawn.Write a procedure to initialise an array holding the Numbers drawn. Write a function to generate a random number from 1 - 50.Write a function to generate a random number from 1 - 50. Use a Boolean array with upper bound 50 to identify duplicates. Use a Boolean array with upper bound 50 to identify duplicates.

For example, the array cell with subscript 37 indicates whether or not the For example, the array cell with subscript 37 indicates whether or not the number 37 has been drawn.number 37 has been drawn.

Write a procedure to initialise the array above.Write a procedure to initialise the array above. Write a “main program” to generate six different numbers using Write a “main program” to generate six different numbers using

the procedures/functions above.the procedures/functions above.Start with the initialisation procedures and make sure the user can reset Start with the initialisation procedures and make sure the user can reset and start again, without quitting the program.and start again, without quitting the program.

212121/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 22: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

2222

Extension “Hockey Club Winners” ProgramExtension “Hockey Club Winners” Program

A hockey club has 347 members and each week A hockey club has 347 members and each week all members pay $1 into a prize draw fund. Each all members pay $1 into a prize draw fund. Each week there is one winner and the winning number week there is one winner and the winning number is to be generated by a computer program.is to be generated by a computer program.1.1. Write program code to generate a number between 1 Write program code to generate a number between 1

and 347.and 347.

2.2. The number of members will change as members The number of members will change as members leave the club and new members join. Amend the leave the club and new members join. Amend the program code so that:program code so that:

the user inputs the current number of members (X)the user inputs the current number of members (X)

the random number generator is coded as a function which:the random number generator is coded as a function which: has a single parameter Xhas a single parameter X returns the winning number.returns the winning number.

Page 23: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

2323

Extension “User IDs and Passwords” ProgramExtension “User IDs and Passwords” Program

Extend the “Password Entry” program written in presentations 3.3/3.4:Extend the “Password Entry” program written in presentations 3.3/3.4: Use a function PasswordCheck with the stored password as a parameter.Use a function PasswordCheck with the stored password as a parameter.

If the user enters the correct password the function returns the value TRUE.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 Each time the password is entered incorrectly, the message “Wrong password” is output.output.

If the user enters an incorrect password 3 times, the user is told that access is If the user enters an incorrect password 3 times, the user is told that access is denied, and the function returns the value FALSE.denied, and the function returns the value FALSE.

Use a sequential file of records to store the user IDs and encrypted Use a sequential file of records to store the user IDs and encrypted passwords.passwords.

When a user types in their User ID, the program calls a function, FindPassword, When a user types in their User ID, the program calls a function, FindPassword, with parameter ThisUserID.with parameter ThisUserID.

The function searches each record in the file for ThisUserID and returns the The function searches each record in the file for ThisUserID and returns the encrypted password.encrypted password.

If ThisUserID is not stored in the file, the function returns an error code.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 I suggest creating the file manually first (type in the User IDs and passwords directly

into a text file).into a text file).

Program’s folder – folder with name – bin – Debug.Program’s folder – folder with name – bin – Debug.See presentation 7.1 Files if you need to remind yourself about how files work etc..See presentation 7.1 Files if you need to remind yourself about how files work etc..

Page 24: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Football Club Members Winners”Extension “Football Club Members Winners”

A football club is owned by its fans and currently has A football club is owned by its fans and currently has 3089 members. The data about members is held in a file 3089 members. The data about members is held in a file MEMBERS.DATMEMBERS.DAT. Each member is given a member . Each member is given a member number.number.

For each of the 23 home games, there is a prize draw For each of the 23 home games, there is a prize draw with the member drawn gifted $100.with the member drawn gifted $100.

Once a member is a winner, they cannot win again.Once a member is a winner, they cannot win again.

The lucky member number is to be selected each week The lucky member number is to be selected each week by a computer program. Hence, for the draw for the first by a computer program. Hence, for the draw for the first week, it will generate a member number between 1 and week, it will generate a member number between 1 and 3089.3089.

242421/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 25: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Football Club Members Winners”Extension “Football Club Members Winners”

The MEMBERS.DAT file is a text file with the following The MEMBERS.DAT file is a text file with the following structure.structure.

Each member’s data is a single line of text, consisting of:Each member’s data is a single line of text, consisting of: four characters for the member number (fixed length)four characters for the member number (fixed length) a <Space> charactera <Space> character member name (variable length).member name (variable length).

252521/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 26: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Football Club Members Winners”Extension “Football Club Members Winners”

A second serial file PREVIOUSWINNERS.DAT stores A second serial file PREVIOUSWINNERS.DAT stores the member numbers of all past winners.the member numbers of all past winners.

The diagram shows the file after five home games.The diagram shows the file after five home games.

262621/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 27: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Football Club Members Winners”Extension “Football Club Members Winners”

Use the identifiers as shown in the table below:Use the identifiers as shown in the table below:

272721/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 28: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Football Club Members Winners”Extension “Football Club Members Winners”

Complete the structure chart. Complete the structure chart.

Write the program discussed as shown below.Write the program discussed as shown below.

282821/04/2321/04/23

Continued Continued on the next on the next

slide.slide.

Page 29: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Football Club Members Winners”Extension “Football Club Members Winners”

A student is investigating how many items customers A student is investigating how many items customers purchase when visiting a supermarket.purchase when visiting a supermarket.

She collects data for 100 customers which shows the She collects data for 100 customers which shows the following:following:

Write program code to generate Write program code to generate the sequence of number of items the sequence of number of items purchased for the random arrival purchased for the random arrival of 500 customers, based on the of 500 customers, based on the given data.given data.

Code the number of items Code the number of items generated for each customer as generated for each customer as a function NumberOfItems().a function NumberOfItems().

Do notDo not attempt to summarise attempt to summarise these as a distribution table.these as a distribution table.

292921/04/2321/04/23

Page 30: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Sports Tally”Extension “Sports Tally”

Extend the “Sports Tally” program written in presentation Extend the “Sports Tally” program written in presentation 3.4 Iteration Loops.3.4 Iteration Loops. Use a one-dimensional array, Tally, instead of four Use a one-dimensional array, Tally, instead of four

variables to store the counts.variables to store the counts. Modularise the design.Modularise the design. The main program should just consist of three procedure The main program should just consist of three procedure

calls:calls:InitialiseArrayCountsInitialiseArrayCounts

InputStudentChoicesInputStudentChoices

OutputTallyChartOutputTallyChart outputs the first two columns of the tally chart and thenoutputs the first two columns of the tally chart and then calls calls

OutputTally OutputTally to output the correct number of bars (\).to output the correct number of bars (\).

The output should look like this:The output should look like this:

Write this program.Write this program.

3030

Page 31: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” Program

A teacher wants to write a program to help A teacher wants to write a program to help young children learn their multiplication young children learn their multiplication tables between 1 and 10.tables between 1 and 10.

If the child chooses the number 7, the If the child chooses the number 7, the screen displays:screen displays:

The algorithm to produce this output is The algorithm to produce this output is represented by the flowchart shown:represented by the flowchart shown:

The program needs the following three The program needs the following three integer variables:integer variables:

NumberNumber ii ResultResult

Write this ‘main’ program.Write this ‘main’ program.

313121/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 32: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” ProgramThe teacher then wants the program to:The teacher then wants the program to:

show a visual representation of a multiplicationshow a visual representation of a multiplication ask the child to key in an answer.ask the child to key in an answer.

For example, the multiplication of 3 × 4 is represented as shown.For example, the multiplication of 3 × 4 is represented as shown.

Add the code for this in the main program but note:Add the code for this in the main program but note:

1.1. I suggest you ask the child if they want to show another times table or start the test first.I suggest you ask the child if they want to show another times table or start the test first.

2.2. If the child wants to start the test I suggest you use:If the child wants to start the test I suggest you use:• Console.Clear() Console.Clear() ‘Clear the console‘Clear the console..

3.3. Use Use a a function function Random(X)Random(X) that returns a whole number in the range 1 to X that returns a whole number in the range 1 to X inclusiveinclusive..

• Note that the previous slide stated that the teacher wants the children learn the multiplication tables 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 between 1 and 10, so in the main program this function will be used with X X as as 1010..

n Use a Use a procedureprocedure Display(Number1, Number2)Display(Number1, Number2) to display the question as shown to display the question as shown above.above.

n Use a Use a procedure procedure ShowMultiplicationGrid(Number1, Number2)ShowMultiplicationGrid(Number1, Number2) to produce to produce the grid of asterisks (*)the grid of asterisks (*) . .

1.1. Called from Called from Display(Number1, Number2)Display(Number1, Number2) above. above.

3232Continued on the next slide.Continued on the next slide.

Page 33: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” Program

Write a function Write a function CheckAnswerCorrectCheckAnswerCorrect that gives a that gives a child three chances to type in the child three chances to type in the correct answer. The function returns correct answer. The function returns TRUE if the child typed the correct TRUE if the child typed the correct answer, and FALSE if all three answer, and FALSE if all three attempts are incorrect.attempts are incorrect.

Complete the flowchart opposite, using Complete the flowchart opposite, using the given statements. the given statements.

Now write this function and use it Now write this function and use it appropriately in the main program.appropriately in the main program.

I suggest:I suggest:DoDo

……..

Loop Until Loop Until CheckAnswerCorrectCheckAnswerCorrect = False = False

333321/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 34: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” Program

The teacher now wants the program to output the number of The teacher now wants the program to output the number of questions the child answers correctly before the program questions the child answers correctly before the program stops.stops.

Now write this as a function Now write this as a function TestScoreTotalTestScoreTotal that returns that returns the number of questions answered correctlythe number of questions answered correctly and use it and use it appropriately in the main program.appropriately in the main program.

Note:Note:1.1. Random(X)Random(X), , Display(Number1, Number2)Display(Number1, Number2) and and

CheckAnswerCorrectCheckAnswerCorrect w will be used in this ill be used in this TestScoreTotalTestScoreTotal function now so move their use from the main program into this function.function now so move their use from the main program into this function.

2.2. I suggest that in the main program you simply display the result of the I suggest that in the main program you simply display the result of the TestScoreTotalTestScoreTotal function. function.

e.g. Console.WriteLine(“The number of questions you answered correctly e.g. Console.WriteLine(“The number of questions you answered correctly was: “ & was: “ & TestScoreTotal TestScoreTotal ))

343421/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 35: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” Program

During the school day, several children in the class will During the school day, several children in the class will use this program. The teacher wants to store each use this program. The teacher wants to store each child’s name and their best test score so far.child’s name and their best test score so far.

Assume there will be no more than 30 children in the class.Assume there will be no more than 30 children in the class.

In the main program:In the main program: Declare a record structure Declare a record structure StudentScoreStudentScore t to store the data o store the data

for one child.for one child. Declare a one-dimensional array of records to store the data for Declare a one-dimensional array of records to store the data for

the whole class. Use the identifier the whole class. Use the identifier StudentStudent..

Write a function Write a function FindArrayIndexFindArrayIndex to return the array index of to return the array index of the record in which the child’s name is stored in the the record in which the child’s name is stored in the StudentStudent array or the next available new array index if the child is new.array or the next available new array index if the child is new.

Use this function appropriately in the main program. Use this function appropriately in the main program. See the next slide for some hints.See the next slide for some hints.

353521/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 36: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” Program

e.g. As the e.g. As the TestScoreTotalTestScoreTotal function is now needed twice, I function is now needed twice, I suggest now storing the value returned.suggest now storing the value returned.

NumberOfCorrectQuestionsNumberOfCorrectQuestions = = TestScoreTotal TestScoreTotal Console.WriteLine(“The number of questions you answered correctly Console.WriteLine(“The number of questions you answered correctly

was: “ & was: “ & NumberOfCorrectQuestionsNumberOfCorrectQuestions)) If If NumberOfCorrectQuestionsNumberOfCorrectQuestions > > StudentStudent (Score. (Score.

FindArrayIndexFindArrayIndex)) Then Then

Make sure that if a student types Make sure that if a student types a mixture of upper and lower a mixture of upper and lower case letters case letters (e.g. ALI and Ali)(e.g. ALI and Ali), the program allows for this treats , the program allows for this treats them as the same name.them as the same name.

Write a procedure to display all students’ names and test scores.Write a procedure to display all students’ names and test scores. Call this procedure in the appropriate location in the main Call this procedure in the appropriate location in the main

program.program.

363621/04/2321/04/23Continued on the next slide.Continued on the next slide.

Page 37: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Learn Multiplication Tables” ProgramExtension “Learn Multiplication Tables” Program

The teacher wants to store in a file the name and best The teacher wants to store in a file the name and best score so far for each of the children.score so far for each of the children.

Write a procedure, Write a procedure, SaveToFileSaveToFile, to save the data stored , to save the data stored in the in the StudentStudent array of records. The data must be array of records. The data must be stored in a file named stored in a file named StudentFileStudentFile..

Note that you will have to write a procedure which is called at the Note that you will have to write a procedure which is called at the beginning of the main program, to copy the contents of beginning of the main program, to copy the contents of StudentFile StudentFile into the array into the array StudentStudent, every time the program , every time the program starts.starts.

373721/04/2321/04/23

Page 38: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Token Game”Extension “Token Game”A game is played by two players. Player A uses white tokens ( ). Player B A game is played by two players. Player A uses white tokens ( ). Player B uses black tokens ( ).uses black tokens ( ).

The players take turns dropping tokens into a vertical grid. The players take turns dropping tokens into a vertical grid.

The tokens fall straight down and occupy the next available space in the The tokens fall straight down and occupy the next available space in the chosen column. chosen column.

The aim of the game is to connect four of one’s own colour tokens. 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.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 Here is one example after Player A has had 2 turns and Player B has had 1 turn:turn:

Nathan wants to write a program to allow two users to play the game on the Nathan wants to write a program to allow two users to play the game on the computer.computer.

The program will display a simplified version of the above grid which is The program will display a simplified version of the above grid which is redrawn after every turn.redrawn after every turn.

3838Continued on the next slide.Continued on the next slide.

Page 39: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Token Game”Extension “Token Game”Before any tokens have been dropped into the grid, all grid Before any tokens have been dropped into the grid, all grid cells are empty.cells are empty.

The array The array GridGrid is to be used to represent the contents of the is to be used to represent the contents of the game grid.game grid.

After a player takes their turn, the new state of the grid is to be 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 displayed on the screen. The display will show only the cell contents.contents.

Write a main program to initialise the array Write a main program to initialise the array Grid Grid andand implement the algorithm represented by the flowchart.implement the algorithm represented by the flowchart.

To drop a token into the grid, the player enters the chosen To drop a token into the grid, the player enters the chosen column number.column number.

The function The function ColumnNumberValidColumnNumberValid has a parameter ( has a parameter (xx) ) which is the chosen column number. The function returns:which is the chosen column number. The function returns:

TRUE if x is between 1 and 7 inclusive and there is still space in TRUE if x is between 1 and 7 inclusive and there is still space in the columnthe column

FALSE otherwiseFALSE otherwise

Write this function.Write this function.

3939Continued on the next slide.Continued on the next slide.

Page 40: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Token Game”Extension “Token Game”The program stores in the variable NextPlayer the character 'A' or 'B' to The program stores in the variable NextPlayer the character 'A' or 'B' to show whose turn it is next.show whose turn it is next.

The chosen column number is validated using the function from part on The chosen column number is validated using the function from part on the last slide the last slide ColumnNumberValidColumnNumberValid . .

The program then sets the relevant empty grid cell to the player’s token The program then sets the relevant empty grid cell to the player’s token value.value.

Write the code to do this at an appropriate location in the main program Write the code to do this at an appropriate location in the main program code written earlier on the last slidecode written earlier on the last slide..

4040Continued on the next slide.Continued on the next slide.

Page 41: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

Extension “Token Game”Extension “Token Game”Nathan wants a single player to play against the computer. He uses the 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 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 column. This function returns a whole number in the range 1 to n inclusive.inclusive.

Write a procedure GetColumn to input the next move either from the Write a procedure GetColumn to input the next move either from the computer or Player ‘B’. This procedure has two parameters which are computer or Player ‘B’. This procedure has two parameters which are passed either by reference or by value.passed either by reference or by value.

Call this procedure at the appropriate place in the main program code Call this procedure at the appropriate place in the main program code written earlier on the last slide.written earlier on the last slide.

The exam question did not ask for this but obviously there is no function 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.to see if a player has won. If you wish to try this please feel free.

4141

Page 42: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

424221/04/2321/04/23

Extension Extension “Factorial “Factorial Iterative Iterative Function”Function” Program Program

Change the Change the “Factorial” Program “Factorial” Program - - 3.1 Loops3.1 Loops so that it uses a function. so that it uses a function.

This is called an iterative function.This is called an iterative function.

Make a copy of the previous program’s whole folder to Make a copy of the previous program’s whole folder to keep the original program but rename this folder with the keep the original program but rename this folder with the same name but add same name but add ((Iterative Function Version)Iterative Function Version)..

Page 43: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

434321/04/2321/04/23

PlenaryPlenary

What is the difference between functions What is the difference between functions and sub procedures?and sub procedures? Function ProceduresFunction Procedures

Always returns one item of data to the calling Always returns one item of data to the calling procedure.procedure.

Sub procedures:Sub procedures:May return one or more items of data or no data at May return one or more items of data or no data at all to the calling procedure.all to the calling procedure.

Page 44: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

444421/04/2321/04/23

PlenaryPlenary

How do we write functions?How do we write functions? Private Function …(ByVal … As …, ByVal… As …)Private Function …(ByVal … As …, ByVal… As …) DimDim (Variable name to be returned) (Variable name to be returned) As As

(Data Type)(Data Type) …… Return (Variable name to be returned) Return (Variable name to be returned) End FunctionEnd Function

Page 45: 30/08/20151 8.2 Procedures Function Procedures. 230/08/2015 Learning Objectives Describe the difference between functions and sub procedures. Explain

454521/04/2321/04/23

PlenaryPlenary

How do we call functions?How do we call functions? Assign a function’s return value to a variable.Assign a function’s return value to a variable.

(Variable name)(Variable name) = = (Function Name)(Function Name)(Parameters)(Parameters) Display a function’s return value e.g. to the text Display a function’s return value e.g. to the text

property of a control.property of a control.(Control Name)(Control Name).Text = .Text = (Function Name)(Function Name)(Parameters)(Parameters)