Homework #08 - Answers: FOR Count 1 TO 1000 INPUT A (Count) NEXT Count
Homework #08 - Answers: FOR Count 1 TO 1000 INPUT A (Count) NEXT Count
Question 1
Write an algorithm, using pseudocode and a FOR … TO … NEXT loop structure, to input 1000
numbers into an array. [2]
FOR Count ← 1 TO 1000
INPUT A[Count]
NEXT Count
Example2
Count ← 0
WHILE Count < 1000
DO
Count ← Count + 1
INPUT A[Count]
ENDWHILE
Question 2
A routine checks the weight of melons to be sold in a supermarket. Melons weighing under
0.5 kilograms are rejected and melons weighing over 2 kilograms are also rejected. Give an
example of each type of test data for this routine.
Normal e.g. 1.7
Extreme 0.5 or 2.0 only
Abnormal e.g. one
Question 3
A routine checks the age and height of children who are allowed to enter a play area. The children
must be less than 5 years of age and under 1 metre in height.
The first set of test data used is age 3 and height 0.82 metres. State what type of test data this is. [1]
Normal
Give a reason for using this test data. [1]
Acceptable data to test that the results are as expected.
Provide two additional sets of test data. For each, give
the type of each set of test data
the reason why it is used
Each type of test data and reason for use must be different. [6]
Set 1 – Age 4, height 0.9
Type – Boundary/Extreme
Reason – Data to test the validation that is just within the limits of acceptability
Set 2 – Age 10, height 1.4
Type – Abnormal
Reason – Data that should be rejected and produce an error message
Question 4
A program will be written to store information about members of a swimming club. The following
membership details will be recorded:
Name
Gender
Status: (Senior or Junior)
Fee
Team member (Yes or No)
Choose a suitable data type for each of the membership details to be recorded [5]
A programmer writes a program to store a patient’s temperature every hour for a day.
State the data structure that would be most suitable to use and give the reason for your choice.
Data structure (one—dimensional) array
Reason to simplify programming/ make programs shorter, etc
Question 6
This section of program code asks for 80 numbers between 100 and 1000 to be entered. It checks
that the numbers are in the correct range, and stores them in an array. It counts how many of the
numbers are larger than 500 and then outputs the result when the program is finished.
1 Count = 0
2 FOR Index = 1 TO 80
3 INPUT 'Enter a number between 100 and 1000', Number
4 WHILE Number = 99 AND Number = 1001
5 INPUT 'This is incorrect, please try again', Number
6 ENDWHILE
7 Num[80] = Number
8 IF Number > 500 THEN Count = Count + 1
9 UNTIL Index = 80
10 PRINT Index
11 PRINT ' numbers were larger than 500'
Write an algorithm in pseudocode, using a single loop, to print 50 names that have been stored in an
array.
Count ← 0
WHILE Count < 50 DO
OUTPUT Name[Count]
Count ← Count + 1
ENDWHILE
Question 10
Complete the trace table using the data given in the array.
The global trade item number (GTIN-8) barcode has seven digits and a check digit.
This pseudocode algorithm inputs seven digits and calculates the eighth digit, then outputs the
GTIN-8. DIV(X,Y), finds the number of divides in division for example DIV(23,10) is 2.
MOD(X,Y), finds the remainder in division for example MOD(23,10) is 3.
FOR Count ← 1 TO 7
INPUT Number
Digit(Count) ← Number
NEXT
Sum ← (Digit(1)+Digit(3)+Digit(5)+Digit(7))*3+Digit(2)+Digit(4)+Digit(6)
IF MOD(Sum,10) <> 0
THEN Digit(8) ← DIV(Sum,10)*10 + 10 - Sum
ELSE
Digit(8) ← 0
ENDIF
OUTPUT "GTIN-8"
FOR Count ← 1 TO 8
OUTPUT Digit(Count)
NEXT
A program checks that the weight of a basket of fruit is over 1.00 kilograms and under
1.10 kilograms. Weights are recorded to an accuracy of two decimal places and any weight not in
this form has already been rejected.
Give three weights as test data and for each weight state a reason for choosing it. All your reasons
must be different.
1.00 – boundary rejected//rejected (underweight) // out of range
1.02 – normal // valid // accepted weight in range
1.10 – abnormal // erroneous // invalid // rejected (overweight)
Question 13
Describe how you could modify the original algorithm shown at the start of question 13, to allow
any number of inputs.
loop using a condition control
until condition is met
Question 14
Write an algorithm, using pseudocode, to input three different numbers, multiply the two larger
numbers together and output the result. Use the variables: Number1, Number2 and Number3 for
your numbers and Answer for your result.
REPEAT
OUTPUT "Enter three different numbers"
INPUT Number1, Number2, Number3
UNTIL Number1 <> Number2 AND Number2 <> Number3 AND Number3 <> Number1
IF Number3 < Number2 AND Number3 < Number1
THEN Answer ← Number1 * Number2
ENDIF
IF Number2 < Number3 AND Number2 < Number1
THEN Answer ← Number1 * Number3
ENDIF
IF Number1 < Number2 AND Number1 < Number3
THEN Answer ← Number2 * Number3
ENDIF
OUTPUT "Answer = ", Answer
Give two sets of test data to use with your algorithm in part (a) and explain why you chose each
set.
7, 7, 7
should be rejected as numbers are equal
7, 8, 9
normal data answer should be 72
Question 16
A programmer wants to test that the readings from 2000 electricity meters are greater than 400 units
and less than 900 units. The programmer uses selection and repetition statements as part of the
program. Explain, using programming statements, how selection and repetition could be used in this
program.
The flowchart checks the level of chlorine and the depth of water compared to the height of the
swimming pool. Error messages are output if a problem is found.
Complete the trace tables for each set of input data. Input data: 6, 2.5, 2
Complete the trace table for this algorithm using the given input data.
Index ← 0
FOR Count ← 0 TO 7
INPUT Value
IF Value > 50 THEN
PassMarks[Index] ← Value
Index ← Index + 1
ENDIF
NEXT Count
PRINT "Number passed ", Index
This table shows the contents of the array: MyData e.g. MyData[2] stores the value 5
The pseudocode algorithm shown should allow numbers to be entered and should allow 50 numbers
to be stored in an array.
Count ← 0
REPEAT
INPUT Values[Count]
Count ← Count + 1
UNTIL Count = 0
Describe how you could change your pseudocode in previous part so that it prevents numbers
below 100 and above 200 from being stored in the array Values[ ]
An algorithm has been written in pseudocode to input the names and marks of 35
students.
The algorithm stores the names and marks in two arrays Name[ ] and Mark[ ]. The
highest
mark awarded is found and the number of students with that mark is counted. Both of
these
values are output.
01 HighestMark ← 100
02 HighestMarkStudents ← 0
03 FOR Count ← 1 TO 35
04 OUTPUT "Please enter student name"
05 INPUT Name[Count]
06 OUTPUT "Please enter student mark"
07 INPUT Mark[Counter]
08 IF Mark[Count] = HighestMark
09 THEN
10 HighestMarkStudents ← HighestMarkStudents – 1
11 ENDIF
12 IF Mark[Count] > HighestMark
13 THEN
14 Mark[Count] ← HighestMark
15 HighestMarkStudents ← 1
16 ENDIF
17 NEXT Count
18 OUTPUT "There are ", HighestMarkStudents," with the highest
mark of ",HighestMark
Give line numbers where the four errors are to be found in the pseudocode. Suggest a
correction for each error
Line 1 HighestMark ← 0
Line 7 INPUT Mark[Count]
Line 10 HighestMarkStudents ← HighestMarkStudents + 1
Line 14 HighestMark ← Mark[Count]
Explain how you could extend the algorithm to also find the lowest mark awarded, count the
number of students with that mark, and output both these values.
Add variable LowestMark …
… Set this to a high value for example 100
Add variable LowestMarkStudents …
… Set this to zero
Check if Mark[Count] = LowestMark …
… True – add 1 to LowestMarkStudents
Check if Mark[Count] < LowestMark …
… True – set LowestMarkStudenta to 1 and set LowestMark to Mark[Count]
Add extra output statement
Question 24
This flowchart inputs the points won and the points lost when playing a game. The difference
between the points won and lost is calculated and depending on the result the player can: move
up to the next level, stay at the same level, or move down to the previous level. The flowchart
finishes when the input for points won is –1.
Complete a trace table for this set of input data:
5000, 4474, 6055, 2000, 7900, 9800, 3000, 2150, –1, 6700, 7615
The flowchart needs to be changed. When the difference is more than 5000 the output message is
‘Fantastic leap up two levels’.
Describe the changes that will need to be made to the flowchart.
Add extra decision box …
… before checking for difference greater than or equal to 1000
// change Is difference >= 1000 to >= 1000 and <= 5000
Check for difference greater than 5000
Add extra Output ‘Fantastic leap up two levels’…
… before flowline returns to input
Question 25
Arrays are data structures used in programming. Explain what is meant by the terms dimension
and index in an array. Use examples of arrays in your explanations.
Dimension
The dimension is the number of indexes required to access an element.
Index
The index is the position of the element in an array
For example A[25] is the 25th element of a one-dimensional array.
Question 26
An algorithm has been written in pseudocode to input 50 numbers. Positive numbers are stored in
the array PosNum [ ]. Negative numbers are stored in the array NegNum[ ]. Zeros are not
included in the positive and negative counts.
Count ← 0
PosCount ← Count
NegCount ← Count
REPEAT
INPUT Number
IF Number > 0 THEN
PosCount ← PosCount + 1
PosNum[PosCount] ← Number
ELSE
NegCount ← NegCount + 1
NegNum[NegCount] ← Number
ENDIF
Count ← Count + 1
UNTIL Count >= 50
OUTPUT "There are ", PosCount," positive numbers"
OUTPUT "There are ", NegCount," negative numbers"
Describe the error in the pseudocode and write the correction for this error. [4]
Error:
Problem with zero …
… stored in the negative number array // negative number count increases by 1
Correction:
Replace ELSE with IF
IF Number < 0 (THEN)
The algorithm needs to be changed so there is no limit to how many numbers can be input.
When the number 9999 is input, the algorithm stops more numbers being input and outputs the
results. The number 9999 is not to be stored nor counted as a positive number.
Explain how you would change the algorithm.
Explanation:
Replace REPEAT … UNTIL with WHILE … DO … ENDWHILE
Change condition to WHILE Number <> 9999 DO
Add / Move INPUT Number to before loop // Move / Add extra INPUT Number at end
of loop
Remove (Count ← 0 and) Count ← Count + 1
Or
Any four from:
Include an IF statement after INPUT Number / before updating the arrays
IF Number <> 9999 THEN … or similar
Move output statements to be executed when Number = 9999
Change UNTIL Count >= 50 to UNTIL Number = 9999
Remove (Count ← 0 and) Count ← Count + 1
Question 27
This pseudocode algorithm allows 5000 numbers to be entered and stored in an array called
Number.
FOR Count ← 1 TO 5000
INPUT Number[Count]
NEXT Count
Extend and re-write the algorithm using pseudocode to also count and output how many of the
numbers stored in the array are greater than 500, using the variable Higher. Only output Higher
once with an appropriate message.
Higher ← 0
FOR Count ← 1 TO 5000
INPUT Number[Count]
IF Number[Count] > 500 THEN
Higher ← Higher + 1
ENDIF
NEXT Count
OUTPUT "There are ", Higher, " values that are greater than 500"
Question 28
REPEAT
Flag ← 0
FOR Count ← 0 to 3
IF Num[Count] < Num[Count + 1] THEN
Store ← Num[Count]
Num[Count] ← Num[Count + 1]
Num[Count + 1] ← Store
Flag ← 1
ENDIF
NEXT Count
UNTIL Flag = 0
Complete the trace table for the algorithm using the data given in the array.
Describe the purpose of the algorithm.
The algorithm sorts/orders numbers
… into descending order / from largest to smallest
Question 29
The pseudocode algorithm shown has been written by a teacher to enter marks for the students in
her class and then to apply some simple processing.
Describe what happens in this algorithm.
Marks input are stored in the array Score[]
Marks are checked against a range of boundaries // allow example
… and a matching grade is assigned to each mark that has been input
… then stored in the array Grade[]…
… at the same index as the mark input
The algorithm finishes after 30 marks have been input // allows 30 scores to be entered
Write the pseudocode to output the contents of the arrays Score[] and Grade[] along with
suitable messages.
Count ← 0
REPEAT
PRINT "Student: ", Count, " Mark: ", Score[Count], " Grade:
",Grade[Count]
Count ← Count + 1
UNTIL Count = 30
Count ← 0
WHILE Count < 30 DO
PRINT "Student: ", Count, " Mark: ", Score[Count], " Grade:
",Grade[Count]
Count ← Count + 1
ENDWHILE
FOR Count ← 0 TO 29
PRINT "Student: ", Count, " Mark: ", Score[Count], " Grade:
", Grade[Count]
NEXT
Describe how you could change the algorithm to allow teachers to use it with any size of class.
Add an input facility to allow teachers to enter the class size
Add a variable to store the input class size
Use the class size variable as the terminating condition for the loop
Make sure the arrays are sufficiently large to accommodate the largest possible class
size
Question 30
Write a pseudocode routine that sets each element to zero. Use the most suitable loop structure.
FOR Count ← 1 TO 20
dataArray[Count] ← 0
NEXT (Count)
Question 31
The pseudocode algorithm should allow a user to input the number of scores to be entered and then
enter the scores. The scores are totalled, the total is output and the option to enter another set of
scores is offered.
1 Count ← 0
2 REPEAT
3 FullScore ← 20
4 INPUT Number
5 FOR StoreLoop ← 1 TO Number
6 INPUT Score
7 FullScore ← FullScore
8 UNTIL StoreLoop = Number
9 OUTPUT "The full score is ", FullScore
10 OUTPUT "Another set of scores (Y or N)?"
11 OUTPUT Another
12 IF Another = "N"
13 THEN
14 Count ← 1
15 ENDIF
16 UNTIL Count = 1
Identify the four errors in the pseudocode and suggest a correction for each error.
Show how you could change the algorithm to store the individual scores in the array
ScoreArray[], then find and print the average score once the scores have all been entered.
Question 32
Question 33
Question 34
An algorithm has been written in pseudocode to generate 50 positive random integers with values
less than or equal to 100. These random integers are stored in the array RandNum[ ]
The function Rand(X, Y) generates a random integer greater than or equal to X and less than Y.
For example, Rand(1, 4) generates 1 or 2 or 3.
Find the four errors in the pseudocode and write a correction for each error. [4]
1 Count 0
2 REPEAT
3 RandNum[Counter] Rand(1, 100)
4 Count Count + 2
5 UNTIL Count <= 50
Line 1 Count 0
should be Counter ←0
Line 3 RandNum[Counter] ←Rand(1, 100)
should be RandNum[Counter] ←Rand(1, 101)
Line 4 Counter ←Counter + 2
should be Counter ←Counter + 1
Line 5 UNTIL Count <= 50
should be UNTIL Counter >= 50 // UNTIL Counter = 50
or
The pseudocode for this algorithm could be shortened by the use of a FOR … NEXT loop. Rewrite
the algorithm using a FOR … NEXT loop.
FOR Count ← 0 TO 49 // FOR Count ← 1 TO 50
RandNum[Count] ← Rand(1, 101) / Rand(0, 101)
NEXT // NEXT Count
The flowchart shows an algorithm that should allow 60 test results to be entered into the variable
Score. Each test result is checked to see if it is 50 or more. If it is, the test result is assigned to the
Pass array. Otherwise, it is assigned to the Fail array.
Complete this flowchart:
Write a pseudocode routine that will check that each test result entered into the algorithm is
between 0 and 100 inclusive.
WHILE Score < 0 OR Score > 100 (DO)
OUTPUT "Your entry must be between 0 and 100, inclusive, please try
again "
INPUT Score
ENDWHILE
Or:
REPEAT
IF Score < 0 OR Score > 100 THEN
OUTPUT "Your entry must be between 0 and 100, inclusive,
please try again "
INPUT Score
ENDIF
Question 36
Count ← 0
INPUT Limit
FOR In ← 1 TO Limit
Logic ← TRUE
Test ← 2
INPUT Number
REPEAT
IF Number / Test = Number DIV Test THEN
Logic ← FALSE
ELSE
Test ← Test + 1
ENDIF
UNTIL NOT Logic OR Test >= Number DIV 2
IF Logic THEN
Store[Count] ← Number
Count ← Count + 1
ENDIF
NEXT In
FOR Out ← 0 TO Count - 1
OUTPUT Store[Out]
NEXT Out
Complete the trace table for the algorithm using this input data:
5, 9, 5, 8, 10, 7
State the purpose of this algorithm.
to find / output prime numbers
… store prime numbers in an array
This algorithm only works for numbers that are 3 or greater.
Describe how you could change this algorithm to make sure that only numbers that are 3 or greater
are entered. Any pseudocode statements used in your answer must be fully described.
insert a WHILE loop … // pre-condition loop
… after Input Number
… with a condition to enter the loop Number < 3
an error message included within the loop to ask for a re-entry of Number
…with another input prompt for Number
ENDWHILE closes the loop and the program carries on from REPEAT in the original
algorithm
OR
insert a REPEAT loop … // post-condition loop
… before Input Number
a conditional statement should be placed after Input Number
…to check if Number < 3
if the number entered is <3, an error message included within the loop to ask for a re-
entry of Number
UNTIL Number >= 3 closes the loop and the program carries on from REPEAT in the
original algorithm
Validations , Top-Down-Design and Life Cycle Questions
Question 1
A programmer restricts input values to less than 90 and greater than 60.
State whether this is called validation or verification.
Validation
Name the check that needs to be used.
Range check
State three different types of test data the programmer would need to use. Give an example
of each type and the reason that the programmer chose that test data.
Type 1
Normal data
Example
65
Reason
To show that the program accepts this value
Type 2
Erroneous data
Example
seventy
Reason
To show that the program rejects this value
Type 3
Extreme data
Example
89
Reason
To show that the program accepts this value
Question 2
Complete the trace table for this program code using the test data: 200, 300, –1, 50, 60
Draw a flowchart to represent this section of program code.
Question 3
Programs can perform validation and verification checks when data is entered. Give the names of
two different validation checks and state the purpose of each one.
Range
To make sure the data entered falls within a specific set of values
Length
To make sure the data entered is no longer than specified
Type
To make sure the data entered follows rules related to whether it is numbers of
letters
Check Digit
To make sure an identification code entered is genuine or possible
Give the name of one verification check.
A code must take the form LL9 9LL where L is a letter and 9 is a digit
A presence check has already been used to ensure data has been entered. Name two other types of
validation check that can be used to test the code is valid. [2]
Length (check)
Type Check
Format Check
Give one example of invalid test data for each of the validation checks you have named in previous
question and in each case, give a reason why it fails the check. Each example of test data must be
different. [4]
LL9999LL999
Too long
5678987
All numeric
CB12EU
No space is present
Question 6
Explain why validation and verification checks are needed when data is input.
Include an example of each type of check in your answer. [4]
a validation check is needed when data is input
To check that data is sensible / reasonable / meets required criteria
a verification check is needed when data is input
To check that data is not changed on entry
example of a validation check
Range check // Length check // Type check
example of a verification check
Double entry // Visual check
Question 7
Describe, giving a different example for each, the purpose of these validation checks used in
programming. [6]
Range check
To test if the value input falls between a given upper bound and a given lower bound
Example
If a month has to be input using an integer, it must be between 1 and 12 inclusive
Length check
To test if the data input is over/under a certain number of characters
Example
An international telephone number can be no longer than 15 digits.
Type check
To test if the input is of the correct data type
Example
If the input is expecting integer(s) to be entered, it will not permit a string to be entered.
Question 9
A programmer has written a routine to check that prices are below $10.00. These values are used as
test data. [3]
10.00 9.99 ten
Explain why each value was chosen.
10.00
boundary/erroneous data // the price should be rejected // value is out of range
9.99
boundary/extreme/normal data // the prices should be accepted // value is within normal
range
ten
erroneous/abnormal data // input should be rejected // value is wrong type
Question 10
A programmer has written a routine to store the name, email address and password of a contributor
to a website’s discussion group.
The programmer has chosen to verify the name, email address and password. Explain why
verification was chosen and describe how the programmer would verify this data. [4]
To ensure no changes are made on input / accuracy of transcription
Because the details do not have fixed, values or lengths to validate
Because there is no clear set of rules that can be used for validation
The programmer could ask the contributor to type in each detail twice …
and then check that both values are equal
If they are not equal then the input should be rejected
The programmer could ask the contributor to check the details on the screen …
and confirm that they are correct / same as the original or change them
The programmer has also decided to validate the email address and the password. Describe
validation checks that could be used. [2]
Email address
check for @ / format check / no spaces /valid characters // presence
check // length check (not more than 254 characters) // uniqueness check
Password
length check / numbers and letters etc. // uniqueness check not been used before // presence
check
A program checks that the weight of a basket of fruit is over 1.00 kilograms and
under 1.10 kilograms. Weights are recorded to an accuracy of two decimal places and any weight
not in this form has already been rejected. Give three weights as test data and for each weight
state a reason for choosing it. All your reasons must be different. [3]
1.00 – boundary rejected//rejected (underweight) // out of range
1.02 – normal // valid // accepted weight in range
1.10 – abnormal // erroneous // invalid // rejected (overweight)
Question 11
Describe, using an example, the purpose of the following checks during data entry. [4]
Validation check
To test if the data entered is possible / reasonable
A range check tests that data entered fits within specified values.
Verification check
To test if the data input is the same as the data that was intended to be input
A double entry check expects each item of data to be entered twice and compares both
entries to check they are the same.
Question 12
Explain the difference between a validation check and a verification check. [2]
Validation checks whether data to be entered is possible/sensible // computer check
Verification checks that data entered is the data that was intended to be entered // can
be a human check // matches the source
Describe, using an example, how data could be verified on data entry. [2]
Double Entry // suitable practical example
the data will be entered twice
compared by the computer or by a human
if a discrepancy is found, the data entry operator is asked to re-enter the data
Or
Visual Verification // suitable practical example
the data will be compared to the source ‘document’
compared by a human
if a discrepancy is found, the data is re-entered
Explain what is meant by the term library routine. [3]
Library routine is a list of instructions // block of code // subroutine
that is used often
which is given a name
and which can be called from other programs
Library routines make writing programs easier and faster as the code is already
written
Library routines make program testing easier as the code has already been tested and
debugged
Question 14
A satellite navigation system works using destination details entered by the user, either a new
destination or chosen from previously saved destinations. The satellite navigation system will then
output directions to the destination in the form of either a visual map or a list of directions. A
satellite navigation system is an example of a computer system that is made up of sub-systems. This
structure diagram shows some of its sub-systems. Complete the diagram by filling in the empty
boxes. [2]
Question 15
Identify three different types of test data. For each type, give an example of the test data you would
use to test this algorithm and state a reason for your choice of test.
Extreme data
5000
to check it is accepted
Normal data
300
To check it is accepted
Abnormal data
10000
To check it is rejected
Question 16
Identify a suitable validation check that could be used for each piece of normal test data and
describe how it would be used. Each validation check must be different.
Test data for entering an email address: [email protected]
Validation check name
Length (check)
Description of use
Counts the number of characters in the data to make sure it isn’t too long (max length 320
characters).
Test data for entering a year: 2021
Validation check name
Range (check)
Description of use
Checks that the number entered fits within given parameters
Test data for entering a name: Ericson-Bower
Validation check name
Type (check)
Description of use
Checks the type of data entered (in this case) to make sure no numbers are present
Question 17
A program has been written to check the value of a measurement. The measurement must be a
positive number and given to three decimal places, for example, 3.982. State suitable examples of
normal and erroneous test data that could be used to test this program. For each example give the
reason for your choice of test data.
Normal Sample any positive value with three decimal places e.g. 5.682
Reason to test that normal data is accepted and processed correctly
Erroneous Sample any value that would be rejected e.g. 5.6 or -1.345 or seven
Reason to test that erroneous data is rejected
Explain why two pieces of boundary test data are required for this program. Give an example of
each piece of boundary test data.
Reason to test that 0.000 / -0.001 / highest possible non-positive is rejected and 0.001 /
0.000 / lowest positive number is accepted
Sample 1 0.000
Sample 2 0.001
Explain why verification is needed and how verification could be performed by this program.
To check that values are entered as intended // to prevent incorrect values that meet the
validation criteria being accepted
Asking the user to enter the value twice and comparing the values // double entry only
accepting a value if both entries are identical
or
Displaying the value as it is entered so the user can put right errors have been made as the
value was entered
Question 18
A program checks that the data entered is between 1 and 100 inclusive.
Identify one piece of normal, extreme and erroneous test data for this program, and give a reason
for each.
Normal test data
Test data e.g. 50 (allow any number between 1 and 100 inclusive)
Reason
Data that is within range and should be accepted
Extreme test data
Test data 100 / 1
Reason
Data at the maximum / minimum end of the range and should be accepted
Erroneous test data
Test data e.g. 300 (allow anything that isn’t between 1 and 100 inclusive, including
other data types)
Reason
Data outside the range that should be rejected
Question 19
A program has been written to check the length and content of a password. The password must be
eight or more characters long and contain at least one special character, for example, Secret!*!
State suitable examples of normal and erroneous test data that could be used to test this program.
For each example give the reason for your choice of test data.
Normal Sample any password with at least 8 characters and one special character e.g.
Password!
Reason to test that normal data is accepted and processed correctly
Erroneous Sample any value that would be rejected e.g. secret
Reason to test that erroneous data is rejected
Explain why two pieces of boundary test data are required for this program.
Give an example of each piece of boundary test data.
Boundary Sample 1 – Secret?
Boundary Sample 2 – Secret??
Describe two methods of verification that could be used to verify this data as it is input.
Asking the user to enter the password twice and comparing the values only accepting the data
if both entries are identical
Displaying the password as it is entered so the user can put right errors have been made as
the password was typed
Question 20
Question 01
A programmer is writing a treasure island game to be played on the computer. The island is a
rectangular grid, 30 squares by 10 squares. Each square of the island is represented by an element
in a 2D array. The top left square of the island is represented by the array element [0, 0]. There are
30 squares across and 10 squares down.
The computer will:
generate three random locations where treasure will be buried
prompt the player for the location of one square where the player chooses to dig
display the contents of the array by outputting for each square:
'.' for only sand in this square
'T' for treasure still hidden in sand
'X' for a hole dug where treasure was found
'O' for a hole dug where no treasure was found.
Here is an example display after the player has chosen to dig at location [9, 3]:
Write pseudocode to declare a constant called SAND and assign the value '.' to it
CONSTANT SAND = '.'
Step 2
Complete the missing pseudocode statement for the InitialiseGrid()procedure.
PROCEDURE InitialiseGrid()
DECLARE X, Y : INTEGER
FOR X ← 0 TO 9
FOR Y ← 0 TO 29
Grid[X,Y] ← SAND
NEXT Y
NEXT X
ENDPROCEDURE
Step 3
Complete the missing pseudocode statement for the DisplayGrid()procedure.
PROCEDURE DisplayGrid()
DECLARE R, C : INTEGER
FOR R ← 0 TO 9
FOR C ← 0 TO 29
PRINT (Grid[R,C])
NEXT C
PRINT() //New line
NEXT R
ENDPROCEDURE
Step 4
HideTreasure()
Generates a pair of random numbers used as the grid location of treasure and marks the
square with 'T'
Use RAND (x : INTEGER) RETURNS REAL returns a real number in the range 0 to x
(not inclusive of x) Example: RAND(87) could return 35.43
Write Pseudocode for the HideTreasure procedure. Your procedure should check that
the random location generated does not already contain treasure. The value to represent
treasure should be declared as a constant.
PROCEDURE HideTreasure()
CONSTANT Treasure = 'T'
DECLARE X,Y : INTEGER
X ← INT (RAND(10))
Y ← INT (RAND(30))
WHILE Grid[X][Y] = Treasure DO
X ← INT (RAND(10))
Y ← INT (RAND(30))
ENDWHILE
Grid[X][Y] ← Treasure
ENDPROCEDURE
Step 5
DigHole(Row, Col)
Takes as parameters a valid grid location and marks the square with 'X' or 'O' as
appropriate
Write program code for the DigHole procedure. The values to represent treasure, found
treasure and hole should be declared as constants
PROCEDURE DigHole(Row: INTEGER, Col: INTEGER)
CONSTANT Hole = 'O'
CONSTANT Treasure = 'T'
CONSTANT FoundTreasure = 'X'
Write pseudocode for the StartDig procedure. Ensure that the user input is fully validated.
PROCEDURE StartDig()
DECLARE X, Y : INTEGER
PRINT("Enter position from 0 to 9: ")
INPUT X
WHILE X < 0 OR X > 9 DO
PRINT ("Invalid position - try again")
INPUT X
ENDWHILE
Step 7
Now it is the fun part, the main program is designed as follows to give execution to all the previous
procedure and you can play the game !!!!!
CALL InitialiseGrid()
CALL DisplayGrid()
FOR i ← 1 TO 3
CALL HideTreasure()
NEXT i
CALL StartDig()
CALL DisplayGrid()
Question 4
A program uses two 1D arrays of type integer. Array1 contains 600 elements and Array2
contains 200 elements.
Array1 contains sample values read from a sensor. The sensor always takes three consecutive
samples and all of these values are stored in Array1.
A procedure Summarise() will calculate the average of three consecutive values from Array1
and write the result to Array2. This will be repeated for all values in Array1.
The diagram below illustrates the process for the first six entries in Array1.
The given algorithm is a simple bubble sort that arranges a set of scores stored in a one dimensional
array into descending order, and orders the corresponding students’ names stored into a two-
dimensional array in the same order as the scores. All the arrays are indexed from 1. The contents of
both arrays after sorting are shown.
Kris has written a program that will work out the wages for her staff. The main steps for
each employee are: to work out the hours worked, work out the total earnings, work out tax and
finally print out how much will be taken home.
Complete the structure diagram to show the modules that will be needed.
Write an algorithm using pseudocode to perform this task. (Ensure that you use meaningful variable
names)
INPUT OldString
NewString ← " "
FOR i ← 1 TO LENGTH(OldString)
NextChar ← SUBSTRING(OldString,i,1)
IF NextChar <> '*' THEN
NewString ← NewString & NextChar
ENDIF
NEXT
OUTPUT NewString
Question 11
A teacher wants to write a program to help young children learn their multiplication tables.
The teacher wants the program to:
show a visual representation of a multiplication
ask the child to key in an answer.
For example, the multiplication of 3 × 4 is represented as shown.
NumberOfTries ← 1
Result ← Number1 * Number2
OUTPUT "Type your answer. "
INPUT Answer
WHILE Answer <> Result AND NumberOfTries < 3 DO
OUTPUT "Incorrect. Try again."
INPUT Answer
NumberOfTries ← NumberOfTries + 1
ENDWHILE
IF Answer <> Result THEN
OUTPUT "You need to practice more.
The correct answer is ", Result
ELSE
OUTPUT "Correct. Well done! "
ENDIF
ENDPROCEDURE
Question 12
Ahmed needs to be aware of his average mark and declares a variable with identifier MyAvMark
which he decides will be a global variable.
State where in the program a global variable will be declared.
at the beginning / before any modules
Using only global variables is poor programming practice.
Give a possible problem that could result from this.
Difficult to find where variable value was changed
Makes re-use of modules more difficult
Two threads running simultaneously could try to modify the value
Question 13
The 1D array StudentName[] contains the names of students in a class. The 2D array
StudentMark[] contains the mark for each subject, for each student. The position of each
student’s data in the two arrays is the same, for example, the student in position 10 in
StudentName[] and StudentMark[] is the same. The variable ClassSize contains the
number of students in the class. The variable SubjectNo contains the number of subjects studied.
All students study the same number of subjects. The arrays and variables have already been set up
and the data stored. Students are awarded a grade based on their average mark.
StudentName[1:3] StudentMark[1:3,1:2]
1 2 3 ClassSize SubjectNo M1 M2
Ahmed Samir Mona 3 2 Student1 50 70
Student2 80 90
Student3 60 30
Pseudocode Solution #1
CONSTANT Distinction = 70
CONSTANT Merit = 55
CONSTANT Pass = 40
//Initialising the running totals used for grades
DistinctionNo ← 0
MeritNo ← 0
PassNo ← 0
FailNo ← 0
//Output Name, Total mark, and average mark for each student
OUTPUT "Name ", StudentName[StudentCounter]
OUTPUT "Combined total mark ", TotalMark[StudentCounter]
OUTPUT "Average mark ", AverageMark[StudentCounter]
//Decide the awarded grade based on their average mark
IF AverageMark[StudentCounter] >= Distinction THEN
DistinctionNo ← DistinctionNo + 1
OUTPUT "Grade Distinction"
ELSE
IF AverageMark[StudentCounter] >= Merit THEN
MeritNo ← MeritNo + 1
OUTPUT "Grade Merit"
ELSE
IF AverageMark[StudentCounter] >= Pass THEN
PassNo ← PassNo + 1
OUTPUT "Grade Pass"
ELSE
FailNo ← FailNo + 1
OUTPUT "Grade Fail"
ENDIF
ENDIF
ENDIF
NEXT StudentCounter
DECLARE TotalMark
DECLARE AverageMark
DECLARE SubjectCounter : INTEGER
DECLARE StudentCounter : INTEGER
DECLARE DistinctionNo : INTEGER
DECLARE MeritNo : INTEGER
DECLARE PassNo : INTEGER
DECLARE FailNo : INTEGER
//Output Name, Total mark, and average mark for each student
OUTPUT "Name ", StudentName[StudentCounter]
OUTPUT "Combined total mark ", TotalMark
OUTPUT "Average mark ", AverageMark
//Decide the awarded grade based on their average mark
CASE OF AverageMark
>= 70:
DistinctionNo ← DistinctionNo + 1
OUTPUT "Grade Distinction"
>= 55:
MeritNo ← MeritNo + 1
OUTPUT "Grade Merit"
>= 44:
PassNo ← PassNo + 1
OUTPUT "Grade Pass"
OTHERWISE
FailNo ← FailNo + 1
OUTPUT "Grade Fail"
ENDCASE
NEXT StudentCounter
DistinctionNo ← 0
MeritNo ← 0
PassNo ← 0
FailNo ← 0
CALL InitiliseTotal()
CALL CalculateTotal()
CALL CalculateAverage()
CALL DecideGrade()
CALL Output()
Question16
The following pseudocode algorithm attempts to check whether a string is a valid email address.
FUNCTION IsValid(InString : STRING) RETURNS BOOLEAN
DECLARE Index, Dots, Ats, Others : INTEGER
DECLARE NextChar : CHAR
DECLARE Valid : BOOLEAN
Index ← 1
Dots ← 0
Ats ← 0
Others ← 0
Valid ← TRUE
REPEAT
NextChar ← SUBSTRING(InString, Index, 1)
CASE OF NextChar
'.' : Dots ← Dots + 1
'@' : Ats ← Ats + 1
IF Ats > 1 THEN
Valid ← FALSE
ENDIF
OTHERWISE : Others ← Others + 1
ENDCASE
IF Dots > 1 AND Ats = 0 THEN
Valid ← FALSE
ELSE
Index ← Index + 1
ENDIF
UNTIL Index > LENGTH(InString) OR Valid = FALSE
IF NOT (Dots >= 1 AND Ats = 1 AND Others > 8) THEN
Valid ← FALSE
ENDIF
RETURN Valid
ENDFUNCTION
State the values that would result in the condition evaluating to TRUE.
State the value returned when IsValid() is called using the previous expression
FALSE
Question17
CLOSEFILE ThisFile
ENDPROCEDURE
Question18
The factorial of a number is the product of all the integers from 1 to that number.
For example:
factorial of 5 is given by 1 × 2 × 3 × 4 × 5 = 120
factorial of 7 is given by 1 × 2 × 3 × 4 × 5 × 6 × 7 = 5040
factorial of 1 = 1
Note: factorial of 0 = 1
A function Factorial() will:
be called with an integer number as a parameter
calculate and return the factorial of the number
return −1 if the number is negative.
Write pseudocode for the function Factorial().
FUNCTION Factorial(ThisNum : INTEGER) RETURNS INTEGER
DECLARE Value : INTEGER
IF ThisNum < 0 THEN
Value -1
ELSE
Value 1
WHILE ThisNum <> 0
Value Value * ThisNum
ThisNum ThisNum – 1
ENDWHILE
ENDIF
RETURN Value
ENDFUNCTION
A procedure FirstTen() will output the factorial of the numbers from 0 to 9. The procedure will
use the function from previous part
The required output is:
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 2 is 2
.
.
.
Factorial of 9 is 362880
Complete the table by writing the text that should replace each label A to F.
Label Text
A Is Num > 9?
B YES
C NO
D Value ← Factorial(Num)
F Num ← Num + 1
Question19
A program is to be written which accepts a string and then calculates a numeric value from this
string. The input string and the calculated value are then to be sent to a remote computer over a
communications link. Study the following pseudocode:
NOTE
ASC(ThisChar : CHAR) RETURNS INTEGER
Explain the purpose of sending the value of StringTotal to the remote computer, in addition to
MyString.
Index 0 1 2 3
0 3 15 6 17
1 6 3 1 1
2 17 2 33 3
X Y DataArray[x,y] Count
0 0 3 0
1 0 15 1
2 0 6
3 0 17
0 1 6
1 1 3 2
2 1 1
3 1 1
0 2 17
1 2 2
2 2 33
3 2 3 3
Question 22
Create a text file with the name "store.txt". Write a program to read a word
from the user and store it in this file.
PRINT("Enter a word")
INPUT Data
OPENFILE "store.txt", FOR WRITE
WRITEFILE "store.txt" Data
CLOSE "store.txt"
Question 23
Write an algorithm using pseudocode to store a total in a text file with the
name "TotalData.txt".
The algorithm asks the user to enter numbers to add to this total. The program
then stores the new total in the same text file.
Continue ← "Yes"
WHILE Continue = "Yes" DO
PRINT ("Enter a number")
INPUT Num
Total ← Total + Num
PRINT("Continue? Enter Yes")
INPUT Continue
ENDWHILE
OPENFILE "TotalData.txt" FOR WRITE
WRITEFILE "TotalData.txt" Total
CLOSEFILE "TotalData.txt"
Question 24
A company creates two new websites, Site X and Site Y, for selling bicycles.
Various programs are to be written to process the sales data.
These programs will use data about daily sales made from Site X and Site Y
The one-dimensional (1D) array SalesDate[1:28] contains the dates for the
sales made to site X and site Y
You must use pseudocode or program code and add comments to explain how your code works.
You do not need to declare any arrays Sales[] and SalesDate[]
//Initialise variables
TotalSiteX ← 0
TotalSiteY ← 0
CountDays ← 0
//Output totals
PRINT("Site X total is",TotalSiteX)
PRINT("Site X total is",TotalSiteY)
The variables X, Y and Z are used in a program: X stores a whole number, Y stores a decimal
Function definition
FUNCTION Same(A : INTEGER, B : REAL) RETURNS BOOLEAN
IF A = ROUND(B,0) THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION
Function call
Z ← Same(X,Y)
The one-dimensional (1D) array TeamName[] contains the names of teams in a sports league.
The two-dimensional (2D) array TeamPoints[] contains the points awarded for each match.
The position of each team’s data in the two arrays is the same. For example, the team stored at
index 10 in TeamName[] and TeamPoints[] is the same.
The variable LeagueSize contains the number of teams in the league. The variable MatchNo
contains the number of matches played. All teams have played the same number of matches.
The arrays and variables have already been set up and the data stored.
Each match can be played at home or away. Points are recorded for the match results of each
team with the following values:
3 – away win
2 – home win
1 – drawn match
0 – lost match.
Write a program that meets the following requirements:
calculates the total points for all matches played for each team
counts the total number of away wins, home wins, drawn matches and lost matches for each
team
outputs for each team:
– name
– total points
– total number of away wins, home wins, drawn matches and lost matches
finds and outputs the name of the team with the highest total points
finds and outputs the name of the team with the lowest total points.
You must use pseudocode or program code and add comments to explain how your code works.
You do not need to declare any arrays, variables or constants; you may assume that this has
IF TeamCounter = 1 THEN
HighestResult ← TotalPoints[TeamCounter]
LowestResult ← TotalPoints[TeamCounter]
ENDIF
IF TotalPoints[TeamCounter] > HighestResult THEN
HighestResult ← TotalPoints[TeamCounter]
TopTeam ← TeamCounter
ENDIF
IF TotalPoints[TeamCounter] < LowestResult THEN
LowestResult ← TotalPoints[TeamCounter]
BottomTeam ← TeamCounter
ENDIF
NEXT TeamCounter
// output highest and lowest
OUTPUT "Top Team ", TeamName[TopTeamteam]
OUTPUT "Bottom Team ", TeamName[BottomTeam]
Question 27
A program halted unexpectedly with the error message ‘File not found’ whilst trying to read
data from a file. Outline the actions that the program needs to take to prevent this error occurring
before trying to open the file
check the file exists
if the file does not exist, then output a suitable error message
Question 28
F ← SUBSTRING(P,1,8)
Question 29
The names of patients are stored in the one-dimensional (1D) array Patient[] of type string. A
separate two-dimensional (2D) array Readings[] stores the latest data recorded about each
patient. The array already contains the readings taken by a nurse for each patient:
temperature measured to one decimal place
pulse rate, a whole number.
Temperature readings should be in the range 31.6 to 37.2 inclusive.
Pulse readings should be in the range 55.0 to 100.0 inclusive.
The hospital number given to the patient is used for the index on both arrays, this is a value between
1 and 1000 inclusive.
When the data for a patient is checked a warning is given if any of the readings are out of range. If
both readings are out of range, then a severe warning is given.
Write a procedure, using pseudocode or program code, that meets the following requirements:
takes the hospital number as a parameter
checks if the number is valid
outputs an error message and exits the procedure if the number is not valid
if the hospital number is valid: output the patient’s name
output ‘Normal readings’ if both the readings are within range
output ‘Warning’ and the name of the reading e.g. ‘Pulse’ if one reading is out of range
output ‘Severe warning’ and the names of the two readings ‘Pulse and temperature’ if
both readings are out of range
exits the procedure.
You must use pseudocode or program code and add comments to explain how your code works.
You do not need to initialise the data in the arrays.
//Declaration of constants
CONSTANT TempHigh = 37.2
CONSTANT TempLow = 31.6
CONSTANT PulseHigh = 100.0
CONSTANT PulseLow = 55.0
PROCEDURE CheckPatient(HospitalNumber :INTEGER)
//Check for valid hospital number
IF HospitalNumber < 1 OR HospitalNumber > 1000 THEN
OUTPUT "Hospital number not valid"
ELSE
OUTPUT "Name of Patient ",Patient[HospitalNumber]
//Check if all readings normal
IF Reading[HospitalNumber,1] <= TempHigh AND
Reading[HospitalNumber,1] >= TempLow AND
Reading[HospitalNumber,2] <= PulseHigh AND
Reading[HospitalNumber,2] >= PulseLow THEN
OUTPUT "Normal readings"
ENDIF
//Check if pulse out of range
IF (Reading[HospitalNumber,1] <= TempHigh AND
Reading[HospitalNumber,1] >= TempLow) AND
(Reading[HospitalNumber,2] > PulseHigh OR
Reading[HospitalNumber,2] < PulseLow) THEN
OUTPUT "Warning Pulse"
ENDIF
//Check if temp out of range
IF (Reading[HospitalNumber,1] > TempHigh OR
Reading[HospitalNumber,1] < TempLow) AND
(Reading[HospitalNumber,2] <= PulseHigh AND
Reading[HospitalNumber,2] >= PulseLow) THEN
OUTPUT "Warning temperature"
ENDIF
//Check if both out of range
IF (Reading[HospitalNumber,1] > TempHigh OR
Reading[HospitalNumber,1] < TempLow) AND
(Reading[HospitalNumber,2] > PulseHigh OR
Reading[HospitalNumber,2] < PulseLow) THEN
OUTPUT "Severe warning, Pulse and temperature"
ENDIF
ENDIF
ENDPROCEDURE