Visual Studio 2012 Pupil Workbook

Higher Computing Science Software Design and Development Programming with Visual Studio 2012 1 CONTENTS Topic 1 Get...

0 downloads 157 Views 2MB Size
Higher Computing Science

Software Design and Development Programming with Visual Studio 2012

1

CONTENTS Topic 1

Getting started

Topic 2

Strings and Pre-Defined Functions

Topic 3

Selection

Topic 4

1-D Arrays

Topic 5

User-defined functions

Topic 6

Parameter passing

Topic 7

Standard Algorithms

Topic 8

Reading from a sequential file

Topic 9

Using records

Higher Computing Science

2

TOPIC 1 – GETTING STARTED You will have used a variety of different data types in the Nat 5 programming unit. These are: Integer - stores whole numbers Single

- stores real numbers (numbers with a decimal point in them)

String

- stores alphanumeric characters (letters / symbols / numbers)

Boolean

- stores one of two values: True or False

Task 1: Wages program - Using variables: Real (single) Program specification – Wages calculator Design and write a program that asks the user to enter their hourly rate and the number of hours worked. The total pay should be calculated and displayed.

FORM DESIGN

PROPERTIES HEADING Label: EXIT Button: CLEAR button: START button: LISTBOX1:

Name is lblHeading Name is cmdExit Name is cmdClear Name is cmdStart Name is listbox1

Text is Real Numbers Text is EXIT Text is CLEAR Text is START

DESIGN 1. Take in pay details 2. Calculate wages Refine Step 1: Take in pay details 1.1 Ask for hourly rate. 1.2 Display hourly rate. 1.3 Ask for number of hours worked. 1.4 Display number of hours worked. Refine Step 2: calculate wages 2.1 Total pay = hourly rate * hours worked 2.2 Display total pay

Higher Computing Science

3

TOPIC 1 – GETTING STARTED CODE Public Class Form1 'Task 1: Real Variables ‘program to calculate the total pay from hours worked and work rate 'set the data types of the global variables required in the program Dim hours_per_week, hourly_rate, total_pay As Single

Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'main steps to calculate total pay take_in_details() calculate_wage() End Sub

Private Sub take_in_details() ' Step 1: take in hourly rate and hours worked and convert to a value hourly_rate = Val(InputBox("Please enter your hourly rate.")) ListBox1.Items.Add("The hourly rate is " & hourly_rate) hours_per_week = Val(InputBox("Please enter your hours worked this week.")) ListBox1.Items.Add("The number of hours worked is " & hours_per_week) End Sub

Private Sub calculate_wage() ' Step 2: calculate and display the total wage total_pay = hourly_rate * hours_per_week ListBox1.Items.Add("") ' display a blank line ListBox1.Items.Add("The total pay for the week is " & total_pay) End Sub

Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click 'clear the contents of the list box ListBox1.Items.Clear() End Sub

Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

Load and run the program called Higher Task1 Real.

Higher Computing Science

4

TOPIC 1 – GETTING STARTED OUTPUT Run your program with the test data below.

You will notice from the output that the total pay is not displayed properly:  The pay has 3 decimal places  The pay does not have a pound sign

Formatting output In your calculate_wage procedure change the line that displays the wage to this: ListBox1.Items.Add("The total pay for the week is " & Format(total_pay, ".000"))

Copy the table below and adapt your program to the different formats shown. Decsribe the output that each format command produces:

Format Command

Description of this function

Format(average, ".000") Format(average, "000.0") Format(average, "###.0") Format(average, "fixed") Format(average, "currency") Format(average, "percent")

Higher Computing Science

5

TOPIC 1 – GETTING STARTED Task 2: Ask a question - Using Variables: Boolean Program specification – Ask a question Design and write a program that asks the user to enter the answer to a question. The user will be told whether they are correct or wrong.

FORM DESIGN

PROPERTIES HEADING Label: EXIT Button: CLEAR button: START button: LISTBOX1:

Name is lblHeading Name is cmdExit Name is cmdClear Name is cmdStart Name is listbox1

Text is Boolean Variables Text is EXIT Text is CLEAR Text is START

DESIGN 1. Ask question() 2. Check answer() 3. Display result() Refine Step 1: Ask Question 1.1 set correct to False 1.2 ask for answer to question “what is capital of Norway?”. 1.3 Display user’s answer Refine Step 2: check answer is correct 2.1 if answer is Oslo 2.2 set correct to True 2.3 end if

Refine Step 3: Ask Question 3.1 If correct is True 3.2 display “well done” message 3.3 Else 3.4 Display “wrong” message 3.5 End if

Higher Computing Science

6

TOPIC 1 – GETTING STARTED CODE Public Class Form1 'Task 2: program with Boolean value 'Quiz program which asks for the capital of Norway 'set the data types of the global variables required in the program Dim answer As String Dim correct As Boolean Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'main steps to calculate total pay Ask_question() Check_answer() Display_message() End Sub

Private Sub ask_question() ' ask the user the question and display their answer correct = False answer = InputBox("What is the capital city of Norway?") ListBox1.Items.Add("The answer you gave is " & answer) ListBox1.Items.Add("") End Sub Private Sub check_answer() ' check if the users answer is correct If answer = "Oslo" Then correct = True End Sub Private Sub display_message() ' display an appropriate message to the user If correct = True Then ListBox1.Items.Add("Your answer is correct - well done!") Else ListBox1.Items.Add("Your answer is not correct") End If End Sub

Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click 'clear the contents of the list box ListBox1.Items.Clear() End Sub

Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

Load and run the program called Higher Task 2 Boolean

Higher Computing Science

7

TOPIC 1 – GETTING STARTED OUTPUT Run your program with the test data below:

Task 3: Charity Collection – Procedures and formatting Problem: Three friends have been collecting money for charity. A local company has offered to add a donation based on the total amount they manage to raise. Write a program that allows the friends to enter their individual amounts. The program should then add the three amounts and store the total. The following decisions on the donation from the company are made: a) any amount raised less than £1000 has a £100 bonus (for example £345 raised = £445 total) b) the company will double the amount raised between (and including) £1000 and £2000 (for example £1282 raised = £2564 total) c) if the amount is over £2000 the initial £2000 is doubled but any amount after that is not (for example £2054 raised = 2*£2000 + £54 = £4054 total)

Create a design for your Form and for your Code. Show this to your teacher before you implement this program. Typical Inputs and Output

Higher Computing Science

8

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS Topic 2 - Working with Strings Visual Studio provides a number of useful pre-defined functions for manipulating strings. Name Len

How it works Input(s) Output String Integer

Ucase

String

Lcase

What it does

Example

calculates the number of characters in a string

Letters = Len(“blob”) will result in Letters = 4

String

converts lower-case characters into upper-case characters

String_in = Ucase(“blob”) will result in String_in = “BLOB”

String

String

converts upper-case characters into lower-case characters

String_in = Lcase(“XX”) will result in String_in = “xx”

Asc

String

Integer

Returns the ASCII value of a character

Ascii-no = Asc(“A”) will result in Ascii_no = 65

Chr

Integer

String

takes an ASCII value and returns the corresponding character

Letter = Chr(65) will result in Letter = “A”

Left

String Integer

String

Extracts a sub-string from a string

Part = Left(“Word”, 3) will result in Part = “Wor”

Right

String Integer

String

Extracts a sub-string from a string

Part = Right(“Word”, 2) will result in Part = “rd”

Mid

String Integer Integer

String

extracts a sub-string from a string

Part = Mid$(“Word”, 2, 3) will result in Part = “ord”

NOTE: Every function above has one or more inputs to the functions BUT every function has only ONE OUTPUT!!!

Higher Computing Science

9

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS Task 4: String functions Program specification The program will ask the user to enter a name and will then carry out a series of string operations on the name.

FORM DESIGN

PROPERTIES HEADING Label:

Name is lblHeading

Text is Pre-Defined String Functions

EXIT Button:

Name is cmdExit

Text is EXIT

CLEAR button:

Name is cmdClear

Text is CLEAR

LowerCase button: Name is cmdLower

Text is Lower case

UpperCase button: Name is cmdUpper

Text is Upper case

Left button:

Name is cmd Left

Text is Left

Right button:

Name is cmdRight

Text is Right

Middlebutton:

Name is cmdMiddle

Text is Middle

Capitalise button:

Name is cmdCapFirst Text is Capitalise First

Convert button:

Name is cmdConvert Text is Convert first to ASCII

LISTBOX1:

Name is listbox1

Higher Computing Science

10

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS DESIGN

Lowercase 1. Read in originalname 2. Change originalname to lowercase and store in newname 3. Display originalname 4. Display newname

Uppercase 1. Read in originalname 2. Change originalname to uppercase and store in newname 3. Display originalname 4. Display newname

Left 1. 2. 3. 4.

Read in originalname Store the left 2 characters in newname Display originalname Display newname

Right 1. 2. 3. 4.

Read in originalname Store the right 2 characters in newname Display originalname Display newname

Middle 1. Read in originalname 2. Get the length of originalname 3. Store the middle two characters in newname 4. Display length 5. Display originalname 6. Display newname

Higher Computing Science

11

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS Capitalise First 1. Read in originalname 2. Get the length of original name 3. Store the first character in firstletter 4. Store the rest of the characters in restofname 5. Make firstletter a capital and store it in capital 6. Concatenate the capital and the restofname 7. Display length 8. Display original name 9. Display new name Convert to Ascii 1. Read in originalname 2. Store the first character in firstletter 3. Convert firstletter to an Ascii value and store it in letterasascii 4. Display original name 5. Display first letter 6. Display first letter as Ascii

CODE Public Class Form1

'Task 3 : program with pre-defined string functions 'set the data types of the global variables required in the program Dim originalname, newname, firstletter, restofname, capital As String Dim letterasascii, length As Integer

Private Sub cmdLower_Click(sender As Object, e As EventArgs) Handles cmdLower.Click ' convert the name to lower case letters originalname = InputBox("Please enter a name") newname = LCase(originalname) ListBox1.Items.Add("the original name is : " & originalname) ListBox1.Items.Add("the new name name is :" & newname) ListBox1.Items.Add("") End Sub Private Sub cmdUpper_Click(sender As Object, e As EventArgs) Handles cmdUpper.Click ' convert the name to upper case letters originalname = InputBox("Please enter a name") newname = UCase(originalname) ListBox1.Items.Add("the original name is :" & originalname) ListBox1.Items.Add("the new name name is : " & newname) ListBox1.Items.Add("") End Sub

Higher Computing Science

12

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS Private Sub cmdLeft_Click(sender As Object, e As EventArgs) Handles cmdLeft.Click ' extract the first character on the left originalname = InputBox("Please enter a name") newname = Microsoft.VisualBasic.Left(originalname, 2) ListBox1.Items.Add("the original name is : " & originalname) ListBox1.Items.Add("the first two characters are : " & newname) ListBox1.Items.Add("") End Sub Private Sub cmdRight_Click(sender As Object, e As EventArgs) Handles cmdRight.Click ' extract the last character from the right originalname = InputBox("Please enter a name") newname = Microsoft.VisualBasic.Right(originalname, 2) ListBox1.Items.Add("the original name is : " & originalname) ListBox1.Items.Add("the last two characters are : " & newname) ListBox1.Items.Add("") End Sub Private Sub cmdMiddle_Click(sender As Object, e As EventArgs) Handles cmdMiddle.Click ' extract the middle two characters of the name originalname = InputBox("Please enter a name") length = Len(originalname) newname = Microsoft.VisualBasic.Mid(originalname, length / 2, 2) ListBox1.Items.Add("The length of the original name is " & length) ListBox1.Items.Add("the original name is : " & originalname) ListBox1.Items.Add("the middle two characters are : " & newname) ListBox1.Items.Add("") End Sub Private Sub cmdCapFirst_Click(sender As Object, e As EventArgs) Handles cmdCapFirst.Click ' extract the first letter of the name and capitalise it originalname = InputBox("Please enter a name") length = Len(originalname) firstletter = Microsoft.VisualBasic.Left(originalname, 1) restofname = Microsoft.VisualBasic.Right(originalname, length - 1) capital = UCase(firstletter) newname = capital + restofname ListBox1.Items.Add("The length of the original name is " & length) ListBox1.Items.Add("the original name is : " & originalname) ListBox1.Items.Add("The new name with a capital letter is : " & newname) ListBox1.Items.Add("") End Sub Private Sub cmdConvertASCII_Click(sender As Object, e As EventArgs) Handles cmdConvertASCII.Click ' extract the first character of the name and convert to ASCII originalname = InputBox("Please enter a name") firstletter = Microsoft.VisualBasic.Left(originalname, 1) letterasascii = Microsoft.VisualBasic.Asc(firstletter) ListBox1.Items.Add("the original name is : " & originalname) ListBox1.Items.Add("The first letter of name is : " & firstletter) ListBox1.Items.Add("The first letter as ASCII is : " & letterasascii) ListBox1.Items.Add("") End Sub End Class

Load and run the program called Higher Task 4 String functions.

Higher Computing Science

13

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS OUTPUT Run your program with the test data below:

Lower case, Upper case, Left , Right:

Middle, Capitalise First, Convert first to ASCII:

Higher Computing Science

14

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS Task 5: Devising User IDs – String functions Problem: A program is required which will automatically generate a password from information provided by the user. The program should generate the password from the first letter of their first name, second letter of their surname, last two letters of their birth month converted to upper case, second and third letters of their favourite colour, first 3 letters of their street name, the second -last character in their name then converted to an ASCII value and finishing with the letters VB. For example,  Brenda McSporran,  born in NovembER,  likes the colour green  lives in Market Place,  second last letter is a and converted to 97,  so her password will be BcERreMar97VB.

Create a design for your Form and for your Code. Show this to your teacher before you implement this program.

Pre-defined Numeric Functions There are pre-defined functions that work in a mathematical way. These include: name

what it does

example

Rnd

generates a random number between 0 and 1

X = Rnd * 10

Int

returns the whole number part of a real number

Answer = Int(3.24) returns Answer = 3

Round

Rounds a value to a specified number of decimal places

Answer = Round(3.24, 1) returns Answer = 3.2

Val

Is used to convert a string to a numeric value

Number=Val(txtInput.text)

Higher Computing Science

15

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS Task 6: Using Pre-defined Numeric Functions Problem specification Create a program which will generate a random number. The program will use the INT function on a random number and also the ROUND function.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text: Pre-Defined Numeric Functions

EXIT Button:

Name: cmdExit

Text: EXIT

CLEAR button:

Name: cmdClear

Text: CLEAR

Random button:

Name: cmdRandom

Text: Random Number

Int button:

Name: cmdInt

Text: Int

Roundbutton:

Name: cmdRound

ListBox:

Name: listbox1

Higher Computing Science

Text: Round

16

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS DESIGN

Random Number 1. Generate random number 2. Display random number 3. Display blank line

Int 1. Generate random number 2. Apply INT function to remove decimal part of random number and store as result 3. Display random number 4. Display result 5. Display blank line

Round 1. Generate random number 2. Apply ROUND function to round random number to one decimal place and store as result 3. Display random number 4. Display result 5. Display blank line

Higher Computing Science

17

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS CODE Public Class Form1

'Task 4: program with pre-defined maths functions Dim randomnumber, result As Single Private Sub cmdRandom_Click(sender As Object, e As EventArgs) Handles cmdRandom.Click ' generate a random number between 0 and 1 Randomize() randomnumber = Microsoft.VisualBasic.Rnd() ListBox1.Items.Add("the random number generated was : " & randomnumber) ListBox1.Items.Add("") End Sub Private Sub cmdInt_Click(sender As Object, e As EventArgs) Handles cmdInt.Click 'remove the decimal part of a number Randomize() randomnumber = Microsoft.VisualBasic.Rnd() * 10 result = Int(randomnumber) ListBox1.Items.Add("the random number multiplied by 10 is : " & randomnumber) ListBox1.Items.Add("INT converts this number to : " & result) ListBox1.Items.Add("") End Sub Private Sub cmdRound_Click(sender As Object, e As EventArgs) Handles cmdRound.Click 'round a random number to one decimal place Randomize() randomnumber = Microsoft.VisualBasic.Rnd() result = Math.Round(randomnumber, 1) ListBox1.Items.Add("the random number generated was : " & randomnumber) ListBox1.Items.Add("Rounded to one decimal place : " & result) ListBox1.Items.Add("") End Sub Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click ListBox1.Items.Clear() End Sub End Class

Load and run Higher Task 6 Maths Functions.

Higher Computing Science

18

TOPIC 2 – STRINGS & PRE-DEFINED FUNCTIONS OUTPUT Run your program a few times like the test runs below.

Task 7: Painting a fence – Procedures, rounding and formatting Problem:

The program should calculate the number of tins of paint to paint a rectangular fence and the total cost of buying the tins. The user should enter the dimensions of the fence (the length and height in metres), the cost of one tin of paint and the coverage factor for one tin of paint (how many metres squared can be painted). Both the front and the back of the fence will need to be painted. The program should display the following details:  The total area to be painted (to one decimal place)  The number of tines required (rounded up to a whole number)  The total cost of buying the tins (formatted as currency). 

Create a design for your Form and for your Code. Show this to your teacher before you implement this program.

Higher Computing Science

19

TOPIC 3 - SELECTION TOPIC 1 – GETTING STARTED Topic 3 - Selection using CASE A Case statement is an alternative to using multiple IF statements. This method has the same outcome but requires less code and is easier to read.

Task 8: Assign a grade – Case statement Problem specification Design and write a program that asks the user to enter their mark. A grade is assigned as follows:80 or over is a grade 1, 60 to 79 is a grade 2, 40 to 59 is a grade 3, 20 to 39 is a grade 4, 10 to 19 is a grade 5, less than 10 is a grade 6. The grade should be displayed.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Case Statement

EXIT Button:

Name: cmdExit

Text:

EXIT

CLEAR button:

Name: cmdClear

Text:

CLEAR

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

Higher Computing Science

20

TOPIC 3 - SELECTION TOPIC 1 – GETTING STARTED DESIGN – MAIN STEPS 1. Take in mark() 2. Display grade() DESIGN - REFINEMENTS Refine Step 1: Take in Mark ()

1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15

Read in the pupils mark In the case of mark Greater than or equal to 80 Grade is 1 Greater than or equal to 60 Grade is 2 Greater than or equal to 40 Grade is 3 Greater than or equal to 20 Grade is 4 Greater than or equal to 10 Grade is 5 Less than 10 Grade is 6 End Case Statement

Refine Step 2: Display Grade () 2.1 Display the mark 2.2 Display the grade

2.3 Display a blank line

Higher Computing Science

21

TOPIC 1 – GETTING STARTED TOPIC 3 - SELECTION CODE Public Class Form1 'task 3.1 Using a case statement to decide on a student grade Dim mark, grade As Integer Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click take_in_mark() display_grade() End Sub Private Sub take_in_mark() ' ask user to enter the mark out of 100 mark = Val(InputBox("Please enter pupil's mark out of 100")) 'decide on an appropriate grade Select Case mark Case Is >= 80 grade = 1 Case Is >= 60 grade = 2 Case Is >= 40 grade = 3 Case Is >= 20 grade = 4 Case Is >= 10 grade = 5 Case Is < 10 grade = 6 End Select End Sub Private Sub display_grade() ' display the pupil's mark and grade ListBox1.Items.Add("The pupil's mark is " & mark) ListBox1.Items.Add("Their grade is " & grade) ListBox1.Items.Add("") End Sub End Class

OUTPUT Test your program with sample output similar to below:

Load and run Higher Task 8 Assign a grade.

Higher Computing Science

22

TOPIC 3 - SELECTION TOPIC 1 – GETTING STARTED Task 9: Posting a Package – Case statement Design, implement and test a program to calculate the cost of posting a package by first class mail, based on the following table: Weight up to and including:

Cost

100g 300g 450g 600g 800g 900g 1000g each extra 250g

42p 99p £1.68 £2.03 £2.73 £3.10 £3.45 add 86p

Create a design for your Form and for your Code. Show this to your teacher before you implement this program.

Theory Task 1: Error detection Ask your teacher for a printed copy of this task.

Higher Computing Science

23

TOPIC 4 - ARRAYS

Topic 4: Arrays Task 10: Store 10 marks - Fill an array using a For Loop Problem specification Design and write a program that asks the user to enter 10 marks. The marks should then be displayed.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Fill an Array

EXIT Button:

Name: cmdExit

Text:

EXIT

CLEAR button:

Name: cmdClear

Text:

CLEAR

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

Higher Computing Science

24

TOPIC 4 - ARRAYS DESIGN

1. Take in Marks() 2. Display Marks() Refine Step 1 Take in Marks 1.1 repeat 10 times 1.2 read in current mark into correct location in array 1.3 end loop Refine Step 2 Display Marks 2.1 Display heading 2.2 Display blank line 2.3 Repeat 10 times 2.4 Display current mark 2.5 End loop CODE Public Class Form1 ' Topic 4: Filling a array within a fixed loop Dim mark(9) As Integer Dim pupil As Integer Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'main steps of the problem take_In_Marks() display_marks() End Sub Private Sub take_in_marks() 'ask for 10 marks For pupil = 0 To 9 mark(pupil) = Val(InputBox("Please enter the mark for pupil " & pupil + 1)) Next pupil End Sub Private Sub display_marks() 'display the marks in the listbox ListBox1.Items.Add("Here are the marks for the class") ListBox1.Items.Add("") For pupil = 0 To 9 ListBox1.Items.Add("Pupil " & pupil + 1 & "- mark is " & mark(pupil)) Next pupil End Sub End Class

Higher Computing Science

25

TOPIC 4 - ARRAYS Load and run the program called Higher Task 10 Fill an array. OUTPUT

Theory Task 2: Error detection Ask your teacher for a printed copy of this task.

Task 11: Lottery Winner – Using arrays & RND function . Problem Specification Design, implement and test a program to do the following: The program should prompt the user to enter 10 names and 4 different prizes. The program should select a lucky winner at random and assign them a prize also chosen at random. The program should display all ten possible winners and all 4 possible prizes. It should also display the name of the winner and the chosen prize. Create a design for your Form and for your Code. Show this to your teacher before you implement this program

Higher Computing Science

26

TOPIC – PARAMETER PASSING TOPIC 1 – 5GETTING STARTEDPASSING

Topic 5: Parameter Passing This section of the course shows algorithms including data flow as well as programs that use procedures. Data Flow: In/out In

is the equivalent of ByRef is the equivalent of ByVal

Task 12: Area of a rectangle – Parameter passing Problem specification Design and write a program that asks the user to enter a length and a breadth of a rectangle. The area of the rectangle is calculated and then displayed.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Area of a rectangle

EXIT Button:

Name: cmdExit

Text:

EXIT

CLEAR button:

Name: cmdClear

Text:

CLEAR

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

Higher Computing Science

27

TOPIC – PARAMETER PASSING TOPIC 1 – 5GETTING STARTEDPASSING DESIGN – MAIN STEPS

1 2 3

get values from user() calculate the area() display the area ()

in/out: length, breadth in: length, breadth in/out: area in: area

CODE DESIGN – REFINEMENTS

refine step 1 1.1 1.2 1.3 1.4

get values from user

in/out: length, breadth

Read in the length Display the length Read in the breadth Display the breadth

refine step 2

calculate the area

in: length, breadth

in/out: area

2.1 multiply length by breadth to give area refine step 3 1.1 1.2

display the area

in: area

display a blank line display a message to the use giving the area

Higher Computing Science

28

TOPIC 1 – 5GETTING STARTEDPASSING TOPIC – PARAMETER PASSING CODE Public Class Form1 ' this program calculates the area of a rectangle using parameter passing Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'the main steps of the problem ‘declare the parameter data types Dim length, breadth, area As Single getvalues(length, breadth) calculatearea(length, breadth, area) displayarea(area) End Sub Private Sub getvalues(ByRef length, ByRef breadth) ' ask the user to enter the dimensions of the rectangle length = Val(InputBox("Please enter the length of the rectangle (in centimetres)")) ListBox1.Items.Add("The length is " & length & "cm") breadth = Val(InputBox("Please enter the breadth of the rectangle (in centimetres)")) ListBox1.Items.Add("The breadth is " & breadth & "cm") End Sub Private Sub calculatearea(ByVal length, ByVal breadth, ByRef area) ' this module will calculate the area area = length * breadth End Sub Private Sub displayarea(ByVal area) ' this module will display the area ListBox1.Items.Add("") ListBox1.Items.Add("The area of the rectangle is " & area & "cm squared") End Sub End Class

Load and run Higher Task 12 Area of a rectangle. OUTPUT Test your program with sample output similar to below:

Higher Computing Science

29

TOPIC – PARAMETER PASSING TOPIC 1 – 5GETTING STARTEDPASSING Task 13: Estimate Grades – Parameter passing Problem specification Design, implement and test a program to do the following: The program will estimate a pupil’s grade for their Nat5 Computing Science exam based on a mark from their prelim and their coursework total. Their prelim mark is out of 90 and their coursework is out of 60. The total is converted to a percentage and the following estimates are applied: >= 85% >= 70% >= 65% >= 60% >= 55% >= 50% >= 45% <45%

= = = = = = = =

Band Band Band Band Band Band Band Band

1 2 3 4 5 6 7 8

Your program should display the total mark out of 150, their percentage and their Band estimate. Create a design for your Form and for your Code showing the data flow for the problem. Show this to your teacher before you implement this program.

Higher Computing Science

30

TOPIC 6 – USER-DEFINED FUNCTIONS

Topic 6: User-defined Functions Pre-defined functions (like LEN) are already made for us. If we want to create a function we will use again and again, we create a user-defined function. Functions can input several parameters but only ever return one value. Functions are different from procedures that can input several parameters and may also return many parameters.

Task 14: Calculate an area – Using a function Problem specification Design and write a program that asks the user to enter the radius of a circle. The area is then calculated and displayed.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Area of a circle (user-defined Function)

EXIT Button:

Name: cmdExit

Text:

EXIT

CLEAR button:

Name: cmdClear

Text:

CLEAR

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

DESIGN – MAIN STEPS

1. 2.

get radius() calculate and display the area()

in/out: radius in: radius

CODE DESIGN – REFINEMENTS

Refine step 1 get radius from user 1.1 Read in the radius 1.2 Display the radius

Higher Computing Science

in/out: radius

31

TOPIC 6 – USER-DEFINED FUNCTIONS Refine step 2 calculate and display the area 2.1 calculate area 2.2 display area

in: radius

Refine Function: get Area 1. area = radius ^ 2 * 3.14 2. return area

in: radius

display the area

CODE Public Class Form1 'this program calculates the area of a circle 'this version uses a user-defined function to calculate the area Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'this contains the main steps of the problem 'declare parameter data type Dim radius As Single get_radius(radius) calculate_and_display(radius) End Sub Private Sub get_radius(ByRef radius) ' this module will ask the user to enter the radius radius = Val(InputBox("Please enter the radius of the circle in cm")) ListBox1.Items.Add("The radius of the circle is " & radius & "cm") End Sub Private Sub calculate_and_display(ByVal radius) Dim area As Single area = get_area(radius) ListBox1.Items.Add("The area is " & area & "cm squared") End Sub Function get_area(Radius) As Single Dim area As Single area = math.Round(Radius ^ 2 * 3.14,2) Return area End Function End Class

Load and run Higher Task 14 Area using function. OUTPUT Test your program with the following test data: Test

Type of Test

Test data

Expected Result

1

Normal

Radius = 5

Area = 78.5

2

Normal

Radius = 6.7

Area = 140.95

3

Extreme

Radius = 23.78

Area = 1775.63

Higher Computing Science

32

TOPIC 6 – USER-DEFINED FUNCTIONS Task 15: Input Validation Function Problem specification

Design a program which will ask the user to enter two numbers between 1 and 10. The program will then find the sum of these numbers. Inputs from the user must be validated.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Validation using a Function

EXIT Button:

Name: cmdExit

Text:

EXIT

CLEAR button:

Name: cmdClear

Text:

CLEAR

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

DESIGN – MAIN STEPS

1 2

get_numbers() calculate and display total()

in/out: num1, num2 in: num1, num2

DESIGN – REFINEMENTS

Refine step 1 get numbers 1.1 Validate number 1 using function 1.2 Validate number 2 using function Higher Computing Science

in/out: num1, num2

33

TOPIC 6 – USER-DEFINED FUNCTIONS Refine step 2 calculate and display total 2.1 calculate sum of number 1 and number 2 2.2 calculate and display answer

in: radius

Refine Function: get valid number in: prompt, low, high out: number 1. ask the user to enter a number between low and high 2. Loop while the number is less than low or greater than high 3. Display an error message to the user 4. Ask the user to re-enter the number 5. End loop 6. return number

CODE Public Class Form1 'program using a function to validate inputs from user Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'declare data flow parameters Dim num1, num2 As Integer 'main steps get_values(num1, num2) calculate_and_display_total(num1, num2) End Sub Private Sub get_values(ByRef num1, ByRef num2) 'procudeure to input numbers from user num1 = get_valid_number("Please enter a number between ”, 1, 10) num2 = get_valid_number("Please enter a number between ”, 1, 10) End Sub Private Sub calculate_and_display_total(ByVal num1, ByVal num2) 'procedure to calculate and display values 'declare local variable Dim answer As Integer answer = num1 + num2 ListBox1.Items.Add(num1 & " + " & num2 & " = " & answer) End Sub

Function get_valid_number(byval prompt, byval low, byval high) As Integer 'function used to validate a number between 2 boundaries Dim number as integer number = Val(InputBox(prompt & low & “ and ” & high)) Do While number < low Or number > high MsgBox("That number is invalid. Please try again") number = Val(InputBox(prompt & low & “ and ” & high)) Loop Return number End Function End Class

Load and run Higher Task 15 Input Validation

Higher Computing Science

34

TOPIC 6 – USER-DEFINED FUNCTIONS OUTPUT Test your program with the following test data: Test

Type of Test

Test data

Expected Result

1

Normal

Num1 = 4 num2 = 7

4 + 7 = 11

2

Normal

Num1 = 8 num2 = 5

8 + 5 = 13

3

Extreme

Num1 = 1 num2 = 10

1 + 10 = 11

4

Extreme

Num1 = 2 num2 = 9

2 + 9 + 11

5

Exceptional

Num1 = 14 num2 = 7

Error message for num1

6

Exceptional

Num1 = 4 num2 = 78

Error message for num2

Task 16: Input Validation – User defined functions Problem specification Design, implement and test a program to do the following: The user should enter 3 different values and each should be validated as shown: I.

II.

III.

prompt the user to enter either a ‘yes’ or a ‘no’. the program should also accept ‘yes’, ‘no’, ‘yeS’, ‘NO, ’nO’ etc… prompt the user to enter a telephone number. The program should only accept a number starting with the digit ‘0’ and with a total of 11 digits. Assume no spaces are allowed. Prompt the user to enter a password which can include any character except for a space, and must be more than 6 characters long. Create a design for your Form and for your Code. Show this to your teacher before you implement this program.

Higher Computing Science

35

TOPIC 7 – STANDARD ALGORITHMS

Topic 7: Standard Algorithms In the design and development of software, there are certain tasks which are needed over and over again. For example, almost every program uses input validation to prevent a user entering data which cannot be acceptable and which might cause the program to fail. Rather than every programmer having to write the code for an input validation routine, this module of code can be taken from a module library to be re-used or adapted. There are many other standard algorithms, including:  Finding the maximum value  Finding the minimum value  Linear Search  Counting Occurrences

Task 17: Highest Mark – find maximum algorithm Task 17:specification Finding the Maximum Value Problem Design and write a program that generates 5 random marks between 1 and 100 and stores them in an array. The marks are displayed then the highest mark is displayed.

FORM DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Findinf the Maximum

EXIT Button:

Name: cmdExit

Text:

EXIT

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

Higher Computing Science

36

TOPIC 7 – STANDARD ALGORITHMS DESIGN – MAIN STEPS

1. 2. 3. 4. 5.

initialise variables() fill array with data () display the array find the maximum value display max

in/out: max, marks_array in/out: marks_array in: marks_array in: marks_array in/out: max in: max

DESIGN – REFINEMENTS

Refine step 1 initialise variables() 1.1 clear contents of list box 1.2 start loop counter from 0 to 4 1.3 set marks_array (loop counter) to 0 1.4 End loop 1.5 Set max to 0

in/out: max, marks_array

Refine step 2 fill array with data ()

in/out: marks_array

2.1 start loop counter from 0 to 4 2.2 set marks_array (loop counter) to a random value between 1 and 100 2.3 End loop Refine step 3 display the array 3.1 3.2 3.3 3.4 3.5

in: marks_array

display title “Here are the marks:” display a blank line start loop counter from 0 to 4 display marks_array (loop counter) End loop

Refine step 4 find the maximum value

in: marks_array

in/out: max

3.1 set max to equal the first element in the array 3.2 start loop for the rest of the array 3.3 If marks_array (loop counter) is greater than max then 3.4 set max to equal marks_array (loop counter) 3.5 End If 3.6 End loop Refine step 4 display max

in: max

3.1 Display a blank line 3.2 Display “The highest mark is “ and max

Higher Computing Science

37

TOPIC 7 – STANDARD ALGORITHMS CODE Public Class Form1 'Standard Algorithm task - Find the max Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'contains the main steps of the problem 'declare the parameters Dim marks_array (4) As Integer Dim max As Integer Randomize() initialise(max, marks_array) fill_random_marks(marks_array) display_array(marks_array) find_max(max, marks_array) display_maximum(max) End Sub

Private Sub initialise(ByRef max, ByRef marks_array) ' this module sets an initial value to the parameters Dim index As Integer ListBox1.Items.Clear() For index = 0 To 4 marks_array(index) = 0 Next max = 0 End Sub

Private Sub fill_random_marks(ByRef marks_array) ' this module will populate the array with random marks between 1 and 100 Dim index As Integer For index = 0 To 4 marks_array(index) = Int(Microsoft.VisualBasic.Rnd() * 100) + 1 Next End Sub

Private Sub display_array(ByRef marks_array) 'this module will display the random marks Dim index As Integer ListBox1.Items.Add("Here are the marks:”) ListBox1.Items.Add("") For index = 0 To 4 ListBox1.Items.Add(marks_array(index)) Next End Sub

Higher Computing Science

38

TOPIC 7 – STANDARD ALGORITHMS Private Sub find_max(ByRef max, ByRef marks_array) ' this module will find the highest mark in the array Dim index As Integer max = marks_array(0) For index = 1 To 4 If marks_array(index) > max Then max = marks_array(index) End If Next End Sub

Private Sub display_maximum(ByVal max) ' this module will display the highest mark ListBox1.Items.Add("") ListBox1.Items.Add("The highest marks is ” & max) End Sub End Class

Load and run Higher Task 17 Highest mark. OUTPUT Test your program works by running it a few times. Ensure the following works correctly:  The program picks up the correct value each time  The program is correct when the max value is the first item in the array

Higher Computing Science

39

TOPIC 7 – STANDARD ALGORITHMS Task 18: Find the Min and Max temperature Problem specification Design, implement and test a program to do the following: The program should ask the user to enter the average temperature that occurred each day for one week. The program will display these temperatures and then display the highest and lowest temperature for the week. Example: Day Day Day Day Day Day Day

1: 2: 3: 4: 5: 6: 7:

12 degrees 10 degrees 17 degrees 6 degrees 18 degrees 9 degrees -6 degrees

Highest temperature was 18 degrees Lowest temperature was -6 degrees

Create a design for your Form and for your Code showing the data flow for the problem. Show this to your teacher before you implement this program.

Task 19: Find the days that had the min and max temperature Problem specification Improve your last program so that it displays output like this:Sunday: Monday: Tuesday: Wednesday: Thursday : Friday: Sunday:

12 degrees 10 degrees 17 degrees 6 degrees 18 degrees 9 degrees -6 degrees

Highest temperature was 18 degrees on Thursday Lowest temperature was -6 degrees on Sunday

Create a design for your Form and for your Code showing the data flow for the problem. Show this to your teacher before you implement this program.

Higher Computing Science

40

TOPIC 7 – STANDARD ALGORITHMS Task 20: Mark Counter - Count Occurrences Problem specification Design and write a program that asks the user to enter 10 marks between 0 and 100. The marks should be displayed then the user should be asked to enter a target mark that they want to count the occurrences of. The number of times that the target mark appears in the array should be displayed.

FORM

DESIGN

PROPERTIES HEADING Label:

Name: lblHeading

Text:

Findinf the Maximum

EXIT Button:

Name: cmdExit

Text:

EXIT

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

Higher Computing Science

41

TOPIC 7 – STANDARD ALGORITHMS DESIGN – MAIN STEPS

1. 2. 3. 4. 5.

initialise variables take in marks target = validated number count occurrences of target display results

in/out: marks_array, target, counter in/out: marks_array in: prompt, low, high in/out: target in: target, marks_array, in/out: counter in: marks_array, target, counter

DESIGN – REFINEMENTS

Refine step 1 initialise variables() 1.1 1.2 1.3 1.4 1.5

in/out: marks_array, target, counter

start loop counter from 0 to 9 set marks_array(loop counter) to 0 End loop Set counter to 0 Set target to 0

Refine step 2 take in marks in/out: marks_array 2.1 start loop counter from 0 to 9 2.2 marks_array(loop counter) = validated number (use get_valid_number function) 2.3 End loop Refine step 3: Function: get valid number in: prompt, low, high out: number 1. ask the user to enter a number between low and high 2. Loop while the number is less than low or greater than high 3. Display an error message to the user 4. Ask the user to re-enter the number 5. End loop 6. return number Refine step 4 count occurrences of target 4.1 start loop counter from 0 to 9 4.2 If marks_array(loop counter) = target 4.3 add 1 to counter 4.4 End If statement 4.5 End loop

in: target, marks_array, in/out: counter

Refine step 5 display results

in: marks_array, target, counter

5.1 5.2 5.3 5.4 5.5 5.6 5.7

Display “Here are the marks “ Start loop counter from 0 to 9 Display marks_array(loop counter) End loop Display a blank line Display “The target being counted is ” and target Display “it was found “ and counter and “times”

Higher Computing Science

42

TOPIC 7 – STANDARD ALGORITHMS CODE Public Class Form1 ' Standard algorithms task - Count Occurences of a value in a list Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'declare the parameters used Dim marks_array(9) As Integer Dim target, counter As Integer 'main steps of the problem initialise(marks_array, target, counter) take_in_marks(marks_array) target = get_valid_number("What mark do you want to search for? Enter a mark between ”, 0, 100) count_occurences(marks_array, target, counter) display_results(marks_array, target, counter) End Sub Private Sub initialise(ByRef marks_array, ByRef target, ByRef counter) 'set an initial value to all parameters used in the program Dim index As Integer For index = 0 To 9 marks_array(index) = 0 Next counter = 0 target = 0 End Sub Private Sub take_in_marks(ByRef marks_array) 'populate the array with valid marks from the user Dim index As Integer For index = 0 To 9 marks_array(index) = get_valid_number("please enter the mark for pupil " & index + 1, 1, 100)

Next End Sub Function get_valid_number(byval prompt, byval low, byval high) As Integer 'function used to validate a number between 2 boundaries Dim number as integer number = Val(InputBox(prompt & low & “ and ” & high)) Do While number < low Or number > high MsgBox("That number is invalid. Please try again") number = Val(InputBox(prompt & low & “ and ” & high)) Loop Return number End Function

Higher Computing Science

43

TOPIC 7 – STANDARD ALGORITHMS Private Sub count_occurences(ByRef marks_array, ByVal target, ByRef counter) 'count how many times the target appears in the list Dim index As Integer For index = 0 To 9 If marks_array(index) = target Then counter = counter + 1 End If Next End Sub

Private Sub display_results(ByRef marks_array, ByVal target, ByVal counter) 'display the marks entered, the targer being searched for and the number of occurrences

Dim pupil As Integer ListBox1.Items.Add("Here are the marks:") For index = 0 To 9 ListBox1.Items.Add(marks_array(index)) Next ListBox1.Items.Add("") ListBox1.Items.Add("The target being counted is :" & target) ListBox1.Items.Add("It was found " & counter & " times") End Sub End Class

Load and run Higher Task 20 Count Occurrences.

OUTPUT

Higher Computing Science

44

TOPIC 7 – STANDARD ALGORITHMS Test your program with the following test data: Test

Type of Test

Test data

1

Normal

2

Normal

3

Extreme

4

Extreme

5

Exceptional

Enter mark below 0 and over 100

Error message for mark

6

Exceptional

Enter target below 0 and over 100

Error message for target

15,45,47,45,89,62,36,34,45,25 TARGET = 45 15,95,47,45,89,62,36,34,55,25 TARGET = 45 45,45,45,45,45,45,45,45,45,45 TARGET = 45 0,0,1,1,99,99,100,100,0,100 TARGET = 45

Expected Result

Target of 45 appears 3 times

Target of 45 appears 1 times

Target of 45 appears 10 times

Target of 45 appears 0 times

Task 21: Count the number of days that were a target temperature – Count Occurrences Problem specification Improve your temperature program so that it also asks the user to enter a target temperature and displays output like this: Sunday: Monday: Tuesday: Wednesday: Thursday : Friday: Sunday:

12 degrees 10 degrees 17 degrees 10 degrees 18 degrees 9 degrees -6 degrees

Highest temperature was 18 degrees on Thursday Lowest temperature was -6 degrees on Sunday The number of days that it was 10 degrees was 2.

Create a design for your Form and for your Code showing the data flow for the problem. Show this to your teacher before you implement this program.

Higher Computing Science

45

TOPIC 7 – STANDARD ALGORITHMS Task 22: Who got a target mark - Linear search Problem specification Design and write a program that fills an array with 10 marks then asks the user to enter a target mark. The program should then display the number of each pupil who got the target mark.

FORM DESIGN

PROPERTIES Property

Property

HEADING Label:

Name: lblHeading

Text:

Linear Search

EXIT Button:

Name: cmdExit

Text:

EXIT

START button:

Name: cmdStart

Text:

START

LISTBOX1:

Name: listbox1

Higher Computing Science

46

TOPIC 7 – STANDARD ALGORITHMS DESIGN – MAIN STEPS

1. 2. 3. 4.

initialise variables() display marks () target = validated number linear search

in/out: target in: marks_array in: prompt, low, high out: target in: marks_array, target

DESIGN – REFINEMENTS

Refine step 1 initialise variables()

in/out: target

1.1 clear the contents of the listbox 1.2 Set target to 0 Refine step 2 display marks 2.1 2.2 2.3 2.4 2.5

in: marks_array

Display “Here are the marks” Display a blank line start loop counter from 0 to 9 display the pupils mark end loop

Refine step 3: Function: get valid number in: prompt, low, high out: number 1. ask the user to enter a number between low and high 2. Loop while the number is less than low or greater than high 3. Display an error message to the user 4. Ask the user to re-enter the number 5. End loop 6. return number Refine step 4 linear search 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9

in: marks_array, target

set flag to false Display a blank line Start loop from 0 to 9 If the value in marks_array(loop counter) = target Display the position of this target – loop counter Set flag to true End if statement End loop If flag is false display “Target not found in list”

Higher Computing Science

47

TOPIC 7 – STANDARD ALGORITHMS CODE Public Class Form1 ' Standard Algorithms - Linear Search Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click ' declare parameters and initialise array with values Dim marks_array() As Integer = {10, 15, 14, 13, 9, 14, 12, 18, 9, 10} Dim target As Integer initialise(target) display_marks(marks_array) target = get_valid_number("What mark do you want to search for? Enter a number between ", 0, 20)) linear_search(marks_array, target) End Sub Private Sub initialise(ByRef target) 'this module will set an initial value for the target ListBox1.Items.Clear() target = 0 End Sub Private Sub display_marks(marks_array) 'this module will display the values stored in the array Dim index As Integer ListBox1.Items.Add("Here are the marks out of 20:") ListBox1.Items.Add("") For index = 0 To 9 ListBox1.Items.Add("Pupil " & index + 1 & ": " & marks_array(index)) Next End Sub Private Sub linear_search(ByRef marks_array, ByVal target) 'this module will search the array for occurences of the target value and report their position

Dim index As Integer Dim found As Boolean found = False ListBox1.Items.Add("") For index = 0 To 9 If marks_array(index) = target Then ListBox1.Items.Add("The target of " & target & " was found for pupil " & index + 1)

found = True End If Next If found = False Then ListBox1.Items.Add("Target " & target & " not found in the list")

End Sub Function get_valid_number(byval prompt, byval low, byval high) As Integer 'function used to validate a number between 2 boundaries Dim number as integer number = Val(InputBox(prompt & low & “ and ” & high)) Do While number < low Or number > high MsgBox("That number is invalid. Please try again") number = Val(InputBox(prompt & low & “ and ” & high)) Loop Return number End Function End Class

Higher Computing Science

48

TOPIC 7 – STANDARD ALGORITHMS Load and run Higher Task 22 Linear search. OUTPUT Your output should look like this:

Adapt your program to work with the following test data: Test

1

2

Type of Test

Test data

Expected Result

Normal

11, 12, 10, 12, 10, 19, 18, 20, 12, 8

Normal

TARGET = 12 11, 12, 10, 12, 10, 19, 18, 20, 12, 8

Target appears for pupil 2 Target appears for pupil 4 Target appears for pupil 9

TARGET = 10 3

Extreme

4

Extreme

5

Exceptional

6

Exceptional

11,11,11,11,11,11,11,11,11,11 TARGET = 20 0,0,1,1,9,9,10,20,10,18 TARGET = 0 0,0,1,1,9,9,10,20,10,18 TARGET = -3 0,0,1,1,9,9,10,20,10,18 TARGET = 21

Higher Computing Science

Target appears for pupil 3 Target appears for pupil 5 Target 20 not on the list Target appears for pupil 1 Target appears for pupil 2 Error message for target

Error message for target

49

TOPIC 7 – STANDARD ALGORITHMS Task 23: Search for the days that were a target temperature Problem specification Improve your temperature program so that it also displays the days that matched the target temperature. It should display output like this: Sunday: Monday: Tuesday: Wednesday: Thursday : Friday: Sunday:

12 degrees 10 degrees 17 degrees 10 degrees 18 degrees 9 degrees -6 degrees

Highest temperature was 18 degrees on Thursday Lowest temperature was -6 degrees on Sunday The number of days that it was 10 degrees was 2. It was 10 degrees on Monday. It was 10 degrees on Wednesday.

Higher Computing Science

50

TOPIC 8 – READING FROM A SEQUENTIAL FILE

Topic 8 – Reading from a sequential file Task 24: Read hotel data from a Comma Separated Value file and store it in arrays Problem specification Design and create a program that reads data from a file and stores it in arrays. The output should look like this:-

The Comma Separated Value file looks like this:-

Higher Computing Science

51

TOPIC 8 – READING FROM A SEQUENTIAL FILE DESIGN – MAIN STEPS

1. initialize

2. read_file_into_records()

3. display_records()

in/out: hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels in/out: hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels in: hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels

DESIGN – REFINEMENTS

Refine step 1 initialise

in/out: hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels 1.1 start loop counter from 1 to 5 1.2 set hotelName(loop counter) to “” 1.3 set hotelRating(loop counter) to 0 1.4 set hotelCity(loop counter) to “” 1.5 set hotelPricePerNight(loop counter) to 0 1.6 set hotelMealsIncluded(loop counter) to “” 1.7 end loop 1.8 set countOfHotels to 0

Refine step 2 read_file_into_arrays()

in/out: hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels 2.1 Using myReader to Open a file to read from it 2.2 set countOfHotels to 0 2.3 loop while not at the end of the data 2.4 try 2.5 set currentRow to a line in the file 2.6 add 1 to countOfHotels 2.7 set allHotels(countOfHotels).hotelName field to string 0 in the current line 2.8 set allHotels(countOfHotels). hotelRating field to value 1 in the current line 2.9 set allHotels(countOfHotels). hotelCity field to string 2 in the current line 2.10 set allHotels(countOfHotels). hotelPricePerNight field to value 3 in the current line 2.11 set allHotels(countOfHotels). hotelMealsIncluded field to string 4 in the current line 2.12 Catch file error 2.13 display error message 2.1 end try 2.1 end loop 2.1 End Using 2 Higher Computing Science

52

TOPIC 8 – READING FROM A SEQUENTIAL FILE Refine step 3 display_records()

in/out: hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels

3.1 start loop counter from 1 to countOfHotels 3.2 send allHotels(loop counter).hotelName to display 3.3 send allHotels(loop counter).hotelRating to display 3.4 send allHotels(loop counter).hotelCity to display 3.5 send allHotels(loop counter).hotelPricePerNight to display 3.6 send allHotels(loop counter).hotelMealsIncluded to display 3.7 end loop -----------------------------------------------------------------------------------------Public Class Form1 Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click Dim Dim Dim Dim Dim Dim

hotelName(5) As String hotelRating(5) As Integer hotelCity(5) As String hotelPricePerNight(5) As Single hotelMealsIncluded(5) As String countOfHotels As Integer

initialise(hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels) read_file_into_arrays(hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels) display_arrays(hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels) End Sub -----------------------------------------------------------------------------------------Private Sub initialise(ByRef hotelName, ByRef hotelRating, ByRef hotelCity, ByRef hotelPricePerNight, ByRef hotelMealsIncluded, ByRef countOfHotels) Dim index As Integer For index = 1 To 5 hotelName(index) = "" hotelRating(index) = 0 hotelCity(index) = "" hotelPricePerNight(index) = 0 hotelMealsIncluded(index) = "" Next countOfHotels = 0 End Sub ------------------------------------------------------------------------------------------

Higher Computing Science

53

TOPIC 8 – READING FROM A SEQUENTIAL FILE Private Sub read_file_into_arrays(ByRef hotelName, ByRef hotelRating, ByRef hotelCity, ByRef hotelPricePerNight, ByRef hotelMealsIncluded, ByRef countOfHotels) 'reads a comma separated value file into 5 arrays Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("N:\Visual Studio 2012\Hotel Info.csv") MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") Dim currentRow As String() ' Dim numberOfFields As Integer While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() 'numberOfFields = currentRow.GetUpperBound(0) ' MsgBox(numberOfFields) countOfHotels = countOfHotels + 1 hotelName(countOfHotels) = currentRow(0).ToString hotelRating(countOfHotels) = Val(currentRow(1).ToString) hotelCity(countOfHotels) = currentRow(2).ToString hotelPricePerNight(countOfHotels) = Val(currentRow(3).ToString) hotelMealsIncluded(countOfHotels) = currentRow(4).ToString

Catch ex As Microsoft.VisualBasic. FileIO.MalformedLineException MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While End Using End Sub -----------------------------------------------------------------------------------------Private Sub display_arrays(ByRef hotelName, ByRef hotelRating, ByRef hotelCity, ByRef hotelPricePerNight, ByRef hotelMealsIncluded, ByVal countOfHotels) For index = 1 To countOfHotels ListBox1.Items.Add(hotelName(index)) ListBox2.Items.Add(hotelRating(index)) ListBox3.Items.Add(hotelCity(index)) ListBox4.Items.Add(hotelPricePerNight(index)) ListBox5.Items.Add(hotelMealsIncluded(index)) Next End Sub Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

Copy the CSV file called Hotel Info into your Visual Studio 2012 folder. Load and run Higher Task 24 Read a hotel file into arrays.

Higher Computing Science

54

TOPIC 8 – READING FROM A SEQUENTIAL FILE Task 25: Notice the difference here – actual and formal parameter can have different names Load and run Higher Task 25 Read a hotel file into arrays using standard modules. Public Class Form1 Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'This module contains the main program Dim Dim Dim Dim Dim Dim

hotelName(5) As String hotelRating(5) As Integer hotelCity(5) As String hotelPricePerNight(5) As Single hotelMealsIncluded(5) As String countOfHotels As Integer

initialise(hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels) read_file_into_arrays(hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels) display_arrays(hotelName, hotelRating, hotelCity, hotelPricePerNight, hotelMealsIncluded, countOfHotels) End Sub -----------------------------------------------------------------------------------------Private Sub initialise(ByRef hotelName, ByRef hotelRating, ByRef hotelCity, ByRef hotelPricePerNight, ByRef hotelMealsIncluded, ByRef countOfHotels) 'This module will initialise the records so that the string fields are set to "" and the numeric fields, countOfHotels and are set to 0 Dim index As Integer For index = 1 To 5 hotelName(index) = "" hotelRating(index) = 0 hotelCity(index) = "" hotelPricePerNight(index) = 0 hotelMealsIncluded(index) = "" Next countOfHotels = 0 End Sub ------------------------------------------------------------------------------------------

Higher Computing Science

55

TOPIC 8 – READING FROM A SEQUENTIAL FILE Private Sub read_file_into_arrays(ByRef array1, ByRef array2, ByRef array3, ByRef array4, ByRef array5, ByRef count) 'this module reads a comma separated value file into some arrays Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("N:\Visual Studio 2012\Hotel Info.csv") MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") Dim currentRow As String() While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() 'reads a line of the csv and stores it in the string variable called currentrow count = count + 1 'keeps track of which line of the file was read ‘puts the values that are separated by the commas into the arrays array1(count) = currentRow(0).ToString array2(count) = Val(currentRow(1).ToString) 'val converts a string to a value array3(count) = currentRow(2).ToString array4(count) = Val(currentRow(3).ToString) 'val converts a string to a value array5(count) = currentRow(4).ToString

Catch ex As Microsoft.VisualBasic. FileIO.MalformedLineException MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While End Using End Sub -----------------------------------------------------------------------------------------Private Sub display_arrays(ByRef array1, ByRef array2, ByRef array3, ByRef array4, ByRef array5, ByVal count) 'this module will display the contents of some arrays Dim index As Integer For index = 1 To count ListBox1.Items.Add(array1(index)) ListBox2.Items.Add(array2(index)) ListBox3.Items.Add(array3(index)) ListBox4.Items.Add(array4(index)) ListBox5.Items.Add(array5(index)) Next End Sub -----------------------------------------------------------------------------------------Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

Higher Computing Science

56

TOPIC 8 – READING FROM A SEQUENTIAL FILE Task 26: Improve the hotel data program so that it uses the “Find max” and “Linear search” procedures Problem specification Improve the hotel data program that reads data from a file and stores it in arrays so that it also displays the highest rating and the hotels that had that rating. To test it you should change your Comma Separated Value file so that the Paisley Palm hotel has a rating of 5. The output should look like this:-

Task 27: Read pupil data from a Comma Separated Value file and store it in arrays Problem specification Design and create a program that reads data from a file and stores it in arrays. The data should include Forename, Surname, Register Class, Date of Birth.

You will need to create a Comma Separated Value file like this:-

Higher Computing Science

John, Smith,5L,18/1/1998 Susan, Brown,5M,20/3/1998 Katie,Jones,5L,12/4/1998 Kara,Green,5M,2/1/1998

57

TOPIC 9 – USING RECORDS

Topic 9 – Using records Task 28: Enter hotel data and store it in records Problem specification Design and create a program that allows the user to enter data about hotels and stores it in records. It should display output like this:-

The data will be stored in records in an array of records like this:Array Index 0 1 2 3 4 5

hotelName

Glasgow Caledonian Aberdeen Arms Paisley Palm Premier Inn Premier Inn

hotelRating

hotelCity

hotelPricePerNight

hotelMealsIncluded

5

Glasgow

59.99

Breakfast

3 4 2 2

Aberdeen Paisley Glasgow Carlisle

39.99 99.99 19.99 19.99

Breakfast None None All meals

Higher Computing Science

58

TOPIC 9 – USING RECORDS DESIGN – MAIN STEPS

1. 2. 3.

initialise variables() store_data_in_records() display_records()

in/out: allHotels, countOfHotels in/out: allHotels, countOfHotels in: allHotels, countOfHotels

DESIGN – REFINEMENTS

Refine step 2 initialise variables()

in/out: allHotels, countOfHotels

1.1 set countOfHotels to 5 1.2 start loop counter from 1 to countOfHotels 1.3 set allHotels(loop counter).hotelName to “ 1.4 set allHotels(loop counter).hotelRating to 1.5 set allHotels(loop counter).hotelCity to “” 1.6 set allHotels(loop counter).hotelPricePerNight to 1.7 set allHotels(loop counter).hotelMealsIncluded to “” 1.8 end loop

Refine step 2 store_data_in_records()

in/out: allHotels, countOfHotels

2.1 start loop counter from to countOfHotels 2.2 receive set allHotels(loop counter).hotelName from keyboard 2.3 receive set allHotels(loop counter).hotelRating from keyboard 2.4 receive set allHotels(loop counter).hotelCity from keyboard 2.5 receive set allHotels(loop counter).hotelPricePerNight from keyboard 2.6 receive set allHotels(loop counter).hotelMealsIncluded from keyboard 2.7 end loop

Refine step 3: display_records()

in: allHotels, countOfHotels

3.1 start loop counter from to countOfHotels 3.2 send allHotels(loop counter).hotelName to display 3.3 send allHotels(loop counter).hotelRating to display 3.4 send allHotels(loop counter).hotelCity to display 3.5 send allHotels(loop counter).hotelPricePerNight to display 3.6 send allHotels(loop counter).hotelMealsIncluded to display 3.7 end loop

Higher Computing Science

59

TOPIC 9 – USING RECORDS Public Class Form1 Structure hotelRecord 'Declare the strucre of a record Dim hotelName As String Dim hotelRating As Integer Dim hotelCity As String Dim hotelPricePerNight As Single Dim hotelMealsIncluded As String End Structure -----------------------------------------------------------------------------------------Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click ' Main program Dim countOfHotels As Integer Dim allHotels(5) As hotelRecord initialise(allHotels, countOfHotels) store_data_in_records(allHotels, countOfHotels) display_records(allHotels, countOfHotels) End Sub -----------------------------------------------------------------------------------------Private Sub initialise(ByRef allHotels() As hotelRecord, ByRef countOfHotels As Integer) 'This module gives the records and countOfHotels initial values Dim index As Integer countOfHotels = 5 'Set the number of hotels that are to be stored For index = 1 To countOfHotels allHotels(index).hotelName = "" allHotels(index).hotelRating = 0 allHotels(index).hotelCity = "" allHotels(index).hotelPricePerNight = 0 allHotels(index).hotelMealsIncluded = "" Next End Sub -----------------------------------------------------------------------------------------Private Sub store_data_in_records(ByRef allHotels() As hotelRecord, ByVal countOfHotels As Integer) 'This module invites the user to enter data that is stored in an array of records Dim index As Integer For index = 1 To countOfHotels allHotels(index).hotelName = InputBox("Enter the name of hotel " & index) allHotels(index).hotelRating = InputBox("Enter the rating of hotel " & index) allHotels(index).hotelCity = InputBox("Enter the city of hotel " & index) allHotels(index).hotelPricePerNight = InputBox("Enter the price per night of hotel " & index) allHotels(index).hotelMealsIncluded = InputBox("Enter the meals included of hotel " & index) Next End Sub

Higher Computing Science

60

TOPIC 9 – USING RECORDS Private Sub display_records(ByRef allHotels() As hotelRecord, ByVal countOfHotels As Integer) 'This module displays the data that is stored in an array of records Dim index As Integer For index = 1 To countOfHotels ListBox1.Items.Add(allHotels(index).hotelName) ListBox2.Items.Add(allHotels(index).hotelRating) ListBox3.Items.Add(allHotels(index).hotelCity) ListBox4.Items.Add(allHotels(index).hotelPricePerNight) ListBox5.Items.Add(allHotels(index).hotelMealsIncluded) Next End Sub Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

Load and run the program called Higher Task 28 Enter hotel data into records. Try changing it store a different number of records.

Higher Computing Science

61

TOPIC 9 – USING RECORDS Task 29: Read hotel data from a Comma Separated Value file and store it in records Problem specification Improve the hotel records program so that the data is read from a file instead of the user entering it. The output should still looks like this:-

The Comma Separated Value file looks like this:-

Higher Computing Science

62

TOPIC 9 – USING RECORDS DESIGN – MAIN STEPS

1. read_fie_into_records() 2. display_records()

in/out: allHotels, countOfHotels in: allHotels, countOfHotels

DESIGN – REFINEMENTS

Refine step 1 read_fie_into_records() 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1 2.1

Using myReader to Open a file to read from it set countOfHotels to 0 loop while not at the end of the data try set currentRow to a line in the file add 1 to countOfHotels set allHotels(countOfHotels).hotelName field to string 0 in the current line set allHotels(countOfHotels). hotelRating field to value 1 in the current line set allHotels(countOfHotels). hotelCity field to string 2 in the current line set allHotels(countOfHotels). hotelPricePerNight field to value 3 in the current line set allHotels(countOfHotels). hotelMealsIncluded field to string 4 in the current line Catch file error display error message end try end loop End Using

Refine step 2 display_records() 3.1 3.1 3.1 3.1 3.1 3.1 3.1

in/out: allHotels, countOfHotels

in: allHotels, countOfHotels

start loop counter from to countOfHotels send allHotels(loop counter).hotelName to display send allHotels(loop counter).hotelRating to display send allHotels(loop counter).hotelCity to display send allHotels(loop counter).hotelPricePerNight to display send allHotels(loop counter).hotelMealsIncluded to display end loop

Higher Computing Science

63

TOPIC 9 – USING RECORDS Public Class Form1 Structure hotelRecord 'Declare the structure of a record about a hotel Dim hotelName As String Dim hotelRating As Integer Dim hotelCity As String Dim hotelPricePerNight As Single Dim hotelMealsIncluded As String End Structure -----------------------------------------------------------------------------------------Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'This module contains the main Program Dim allHotels(10) As hotelRecord Dim countOfHotels As Integer read_file_into_records(allHotels, countOfHotels) display_records(allHotels, countOfHotels) End Sub -----------------------------------------------------------------------------------------Private Sub read_file_into_records(ByRef allHotels() As hotelRecord, ByRef countOfHotels As Integer) 'This module reads a Comma Separated Values file and stores the values in an array of records 'Open the file Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("N:\Visual Studio 2012\Hotel Info.csv") 'Describe the type of file MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") Dim currentRow As String() countOfHotels = 0 'while not at the end of the file a row of values is read and stored in a record While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() 'a row is read and stored in the string variable called currentRow countOfHotels = countOfHotels + 1 'keep rack of which line of the file was read i.e. which record 'each value in the row is stored in a feild of the current record allHotels(countOfHotels).hotelName = currentRow(0).ToString allHotels(countOfHotels).hotelRating = Val(currentRow(1).ToString) allHotels(countOfHotels).hotelCity = currentRow(2).ToString allHotels(countOfHotels).hotelPricePerNight = Val(currentRow(3).ToString) allHotels(countOfHotels).hotelMealsIncluded = currentRow(4).ToString 'Display an error message if there is an error in the file Catch ex As Microsoft.VisualBasic. FileIO.MalformedLineException MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While End Using End Sub

Higher Computing Science

64

TOPIC 9 – USING RECORDS Private Sub display_records(ByRef allHotels() As hotelRecord, ByVal countOfHotels As Integer) 'This module displays the data that is stored in the array of records Dim index As Integer For index = 1 To countOfHotels ListBox1.Items.Add(allHotels(index).hotelName) ListBox2.Items.Add(allHotels(index).hotelRating) ListBox3.Items.Add(allHotels(index).hotelCity) ListBox4.Items.Add(allHotels(index).hotelPricePerNight) ListBox5.Items.Add(allHotels(index).hotelMealsIncluded) Next End Sub -----------------------------------------------------------------------------------------Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

-----------------------------------------------------------------------------------------------------------------Load and run the program called Higher Task 29 Read a file into records. Add another line to the file and run the program again to check that all of the data is shown.

Task 30: Read a file of weather data and store it in an array of records Problem Specification Copy Task 23 and paste it, then rename it as Task 30. Edit it so that it stores the data in an array of records. Edit each procedure so that it works correctly. To do this you should create array of records using this code:Structure weatherRecord Dim day as string Dim temperature as integer Dim rainfall as integer End Structure Dim allWeather(7) as weatherRecord You should create a csv file containing this data:-

Higher Computing Science

Sunday Monday Tuesday Wednesday Thursday Friday Saturday

20 21 17 15 21 20 21

0 0 3 5 4 0 0

65

TOPIC 10 – WRITING TO A FILE

Topic 10 Writing to a file Task 31: Read a file and write some of it to another file Problem Statement Change the hotel records program so that the data is read from a file, stored in an array of records then a new file is written that just contains the name and rating of the hotels that are rated more than 2.

DESIGN – MAIN STEPS

1 read_fie_into_records() 2 display_records() 3 write()in:

in/out: allHotels, countOfHotels in: allHotels, countOfHotels in: allHotels, countOfHotels

DESIGN – REFINEMENTS

Refine step 1 read_fie_into_records()

in/out: allHotels, countOfHotels

1.1 Using myReader to Open a file to read from it 1.2 set countOfHotels to 1.3 loop while not at the end of the data 1.4 Try 1.5 set currentRow to a line in the file 1.6 add 1 to countOfHotels 1.7 set allHotels(countOfHotels).hotelName field to string 0 in the current line 1.8

set allHotels(countOfHotels). hotelRating field to value 1 in the current line

1.9 set allHotels(countOfHotels). hotelCity field to string 2 in the current line 1.10 set allHotels(countOfHotels). hotelPricePerNight field to value 3 in the current line 1.11 set allHotels(countOfHotels). hotelMealsIncluded field to string 4 in the current line 1.12 Catch file error 1.13 display error message 1.14 end try 1.15 end loop 1.16 End Using

Higher Computing Science

66

TOPIC 10 – WRITING TO A FILE Refine step 2 display_records()

in: allHotels, countOfHotels

2.1 start loop counter from to countOfHotels 2.2 send allHotels(loop counter).hotelName to display 2.3 send allHotels(loop counter).hotelRating to display 2.4 send allHotels(loop counter).hotelCity to display 2.5 send allHotels(loop counter).hotelPricePerNight to display 2.6 send allHotels(loop counter).hotelMealsIncluded to display 2.7 end loop Refine step 3 write() 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8

in: allHotels, countOfHotels

Open a file to write to it Start loop counter from 1 to count If current item in array > 2 then Send current item in array1 and array 2 to file End if End loop Close file Dispose of file

-----------------------------------------------------------------------------------------------------------------Public Class Form1 Structure hotelRecord 'Declare the structure of a record about a hotel Dim hotelName As String Dim hotelRating As Integer Dim hotelCity As String Dim hotelPricePerNight As Single Dim hotelMealsIncluded As String End Structure Private Sub cmdStart_Click(sender As Object, e As EventArgs) Handles cmdStart.Click 'This module contains the main Program Dim countOfHotels As Integer Dim allHotels(5) As hotelRecord

read_file_into_records(allHotels, countOfHotels) display_records(allHotels, countOfHotels) write(allHotels, countOfHotels) End Sub

Higher Computing Science

67

TOPIC 10 – WRITING TO A FILE Private Sub read_file_into_records(ByRef allHotels() As hotelRecord, ByRef countOfHotels As Integer) 'This module reads a Comma Separated Values file and stores the values in an array of records 'Open the file Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("N:\Visual Studio 2012\Hotel Info.csv") 'Describe the type of file MyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",") Dim currentRow As String() countOfHotels = 0 'while not at the end of the file a row of values is read and stored in a record

While Not MyReader.EndOfData Try currentRow = MyReader.ReadFields() 'a row is read and stored in the string variable called currentRow countOfHotels = countOfHotels + 1 'keep rack of which line of the file was read i.e. which record 'each value in the row is stored in a feild of the current record allHotels(countOfHotels).hotelName = currentRow(0).ToString allHotels(countOfHotels).hotelRating = Val(currentRow(1).ToString) allHotels(countOfHotels).hotelCity = currentRow(2).ToString allHotels(countOfHotels).hotelPricePerNight = Val(currentRow(3).ToString) allHotels(countOfHotels).hotelMealsIncluded = currentRow(4).ToString 'Display an error message if there is an error in the file Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While End Using End Sub -----------------------------------------------------------------------------------------Private Sub display_records(ByRef allHotels() As hotelRecord, ByVal countOfHotels As Integer) 'This module displays the data that is stored in the array of records Dim index As Integer For index = 1 To countOfHotels ListBox1.Items.Add(allHotels(index).hotelName) ListBox2.Items.Add(allHotels(index).hotelRating) ListBox3.Items.Add(allHotels(index).hotelCity) ListBox4.Items.Add(allHotels(index).hotelPricePerNight) ListBox5.Items.Add(allHotels(index).hotelMealsIncluded) Next End Sub ------------------------------------------------------------------------------------------

Higher Computing Science

68

TOPIC 10 – WRITING TO A FILE Private Sub write(ByRef allHotels() As hotelRecord, ByRef count As Integer) 'this module writes a comma separated value file Dim file As System.IO.StreamWriter file = My.Computer.FileSystem.OpenTextFileWriter("N:\Visual Studio 2012\short hotel.csv", True) For index = 1 To count If allHotels(index).hotelRating > 2 Then file.WriteLine(allHotels(index).hotelName & "," & allHotels(index).hotelRating) End If Next file.Close() file.Dispose() End Sub -----------------------------------------------------------------------------------------Private Sub cmdExit_Click(sender As Object, e As EventArgs) Handles cmdExit.Click End End Sub End Class

Load and run the program called Higher Task 31 - Read a hotel file and write some of it to another file.

Task 32: Read pupil data from a Comma Separated Value file, store it in arrays then write a file Problem Statement Improve the pupil data program from Task 27 so that after reading the data and displaying it a file is written that only has the pupils from 5L in it. (Remember that this task uses 4 arrays instead of an array of records.)

Higher Computing Science

69

TOPIC 10 – WRITING TO A FILE

Challenge 1 Create a csv file containing the data shown below: Forename

Surname

Lewis Tom Callum Oliver Hayley Connor Jamie

Reid Mitchell Young Heaney McAdam Smith McKiernan

Test 1

Test 2

19 18 18 20 20 18 19

0 0 0 0 0 0 0

Overall Mark 0 0 0 0 0 0 0

Design and write a program that:

reads the file and stores it in an array of records



invites the user to enter the marks for test 2 by saying e.g. “Please enter the mark that Lewis got in the second test” – these marks should be stored in the array of records



calculate the overall marks and store them in the array of recor ds



display the data



write the data to a file called completeMarks.csv

Higher Computing Science

70