0% found this document useful (0 votes)
140 views

Homework #08 - Answers: FOR Count 1 TO 1000 INPUT A (Count) NEXT Count

Uploaded by

Amira Okasha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views

Homework #08 - Answers: FOR Count 1 TO 1000 INPUT A (Count) NEXT Count

Uploaded by

Amira Okasha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 93

Homework #08 – Answers

One Dimensional Array Questions

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

Rewrite your algorithm using another loop structure. [2]


Example1
Count ← 1
REPEAT
INPUT A[Count]
Count ← Count + 1
UNTIL Count > 1000

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]

Membership Details Data Type


Name String
Gender Char / String
Status Char / String
Fee Real
Team member Boolean

The swimming club has 50 members.


State the data structure that would be most suitable to use and give a reason for your choice. [2]
Data Structure – several Arrays
Reason – to simplify programming/ make programs shorter/index can be used to identify the
same member across the arrays etc.
Question 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

Rewrite the following pseudocode algorithm using a WHILE … DO … ENDWHILE loop.


INPUT Num
FOR Counter ← 1 TO 12
Num ← Num * Counter
A[Counter] ← Num
NEXT
INPUT Num
Counter ← 1
WHILE Counter <= 12 DO
Num ← Num * Counter
A [Counter] ← Num
Counter ← Counter + 1
ENDWHILE
Question 7

Describe the purpose of each statement in this algorithm.


FOR I ← 1 TO 300
INPUT Name[I]
NEXT

 Loop with 300 repetitions (starting at 1) / Loops from 1 to 300


 Values input/stored (in consecutive/different locations) in an array (at position I)
 Increases the loop counter/I value by 1 (and returns to the start of the loop)
Identify, using pseudocode, another loop structure that the algorithm in previous part could have
used.
REPEAT … UNTIL
WHILE … DO … ENDWHILE
Question 8

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'

There are four lines of code that contain errors.


State the line number for each error and write the correct code for that line.
Line 4 correct line WHILE Number <= 99 OR Number > 1000
Line 7 correct line Num[Index] = Number
Line 9 correct line NEXT (Index)
Line 10 correct line PRINT Count
Question 9

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

The flowchart below represents a program routine.


The array used in the flowchart contains the following data:

Complete the trace table using the data given in the array.

Describe what the algorithm represented by the flowchart is doing.


 Sorting the names
 Ascending order / A to Z / lowest to highest / Alphabetic order
Convert the flowchart in question 10 to pseudocode
REPEAT
Count ← 1
Flag ← 0
REPEAT
IF Name[Count] > Name[Count + 1] THEN
Temp ← Name[Count]
Name[Count] ← Name[Count + 1]
Name[Count + 1] ← Temp
Flag ← 1
ENDIF
Count ← Count + 1
UNTIL Count = 4
Until Flag = 0
Question 11

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

Complete the trace table for the input data: 5, 7, 0, 1, 2, 3, 4

Complete the trace table for the input data: 4, 3, 1, 0, 2, 3, 1


Explain how you would change the algorithm to input eight digits (seven digits and the check digit)
and output if the check digit entered is correct or not.
1 Change first loop to 8 iterations
2 Check that the input Digit(8) is equal to the calculated Digit(8)…
3 if equal output check digit correct
4 otherwise output check digit incorrect
Or
1 Change first loop to 8 iterations
2 Put all 8 digits through the algorithm to calculate Sum …
3 if MOD(Sum,10) is equal to zero, check digit correct
4 otherwise output check digit incorrect
Question 12

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

An algorithm is written in pseudocode:


Total ← 0
FOR Count ← 1 TO 50
INPUT Num
Total ← Total + Num
NEXT Count
OUTPUT Total

Describe the purpose of the algorithm.


 Expects 50 numbers to be input
 Totals the numbers as they are entered / carries out a running total
 Outputs the result after the numbers have all been entered
Re-write the algorithm in pseudocode using a different type of loop.
Total ← 0
Count ← 1
WHILE Count <= 50 DO
INPUT Num
Total ← Total + Num
Count ← Count + 1
ENDWHILE
OUTPUT Total
Total ← 0
Count ← 0
REPEAT
INPUT Num
Total ← Total + Num
Count ← Count + 1
UNTIL Count = 50
OUTPUT Total

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

The flowchart performs a mathematical process on a number input called TestNum

DIV is used to represent integer division e.g. 7 DIV 3 = 2


Complete the trace table for the input data: 7

Complete the trace table for the input data: 6

State the purpose of the algorithm in the flowchart.


Works out if the number entered is a prime number
Question 15

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.

 Selection use of IF statement to check the values of the meter readings


 IF Reading > 400 and Reading < 900 THEN …
 Repetition use of FOR loop to check all 2000 meter readings
 FOR Meter = 1 TO 2000 … NEXT
Question 17

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

Input data: 4, 3, 1.5

Input data: 6, 3.5, 4

Identify a problem with the algorithm that the flowchart represents.


 Cannot add more water if the water is too deep
 No validation e.g. allows a negative height/depth/amount of chlorine
 Tells you to add chlorine when there is no water
 Runs only once
Question 18

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

Input data: 58, 40, 67, 85, 12, 13, 75, 82


Give the purpose of the algorithm
 Stores numbers greater than 50 in an array
 Outputs number of times pass mark has been met
 Find the number of pass marks
Question 19

Explain why constants, variables and arrays are used in programming.


Constants
 The value cannot be changed accidentally…
 …during the execution of the program
 Value only needs to be changed once if circumstances change/during the
initialisation process
Variables
 Stores a value that can change …
 …during the execution of the program
 Can use a variable without knowing its value
Arrays
 A list of items of the same data type…
 …stored under a single name
 To reduce the number of variables used
 Any item can be found using an index number to show its place in the list
Question 20

The algorithm performs an operation on the array named MyData


DIV means integer division, so only the whole number part of the result is returned
e.g. 7 DIV 2 returns a value of 3
First ← 0
Last ← 16
Found ← FALSE
INPUT UserIn
WHILE (First <= Last) AND (Found = FALSE) DO
Middle ← (First + Last) DIV 2
IF MyData[Middle] = UserIn THEN
Found ← TRUE
ELSE
IF UserIn < MyData[Middle] THEN
Last ← Middle – 1
ELSE
First ← Middle + 1
ENDIF
ENDIF
ENDWHILE
OUTPUT Found

This table shows the contents of the array: MyData e.g. MyData[2] stores the value 5

Complete the trace table for the input data: 10


Describe the function being performed by the algorithm
 Search for the value input…
 …using an array…
 …of sorted data
Question 21

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

Explain why the algorithm will never end.


 The value of the variable Count begins as 0 …
 … and is incremented by 1 before it is tested by the loop condition
 Count will never be 0 at the end of the loop
Re-write the original pseudocode so that it terminates correctly and also prevents numbers
below 100 from being stored in the array Values[ ]
Count ← 0
REPEAT
INPUT Number
IF Number >= 100 THEN
Values[Count] ← Number
ENDIF
Count ← Count + 1
UNTIL Count = 50

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[ ]

 Alter the IFstatement/add a second IF statement/comparison that’s already there …


 …so that additional criteria set an upper limit of <=200
Question 22

The flowchart represents an algorithm.


The predefined function DIV gives the value of the result of integer division,
for example, y ← 9 DIV 4 gives y a value of 2
An input value of –1 ends the algorithm.
Complete the trace table for the input data:
50, 33, 18, 15, 30, –1, 45, 12, 90, 6

Describe the purpose of the algorithm.


 The program outputs a value
 That is divisible by 6 // 2 and 3
Question 23

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

This pseudocode represents an algorithm.

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

The contents of the array at the start of the algorithm are:

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

A one-dimensional array dataArray[1:20] needs each element set to zero.

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)

Explain why you chose this loop structure.


 (A FOR loop has) a fixed number of repetitions //
 No need to manage the loop counter //
 no need to use another variable for the array index

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.

 Line 3 – should be FullScore ←0


 Line 7 – should be FullScore ←FullScore + Score
 Line 8 – should be NEXT Allow ENDFOR // alternatively Line 5 could be REPEAT
with StoreLoop ←0 just above it and StoreLoop ←StoreLoop + 1
between lines 7 and 8.
 Line 11 – should be INPUT Another

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.

 After line 6 // replace line 6


 ScoreArray[StoreLoop] ← Score //
 INPUT ScoreArray[StoreLoop] between lines 8 and 10
 AverageScore ← FullScore/Number
 OUTPUT "The average score is ", AverageScore

Question 32

The flowchart represents an algorithm.


The algorithm will terminate if 0 is entered at the Op input.
Complete the trace table for the algorithm using this input data:
1, 87, 14, 3, 2, 30, 5, 10, 6, 4, 10, 2, 0, 2, 90, 6
State the purpose of the algorithm.
To work as a calculator // to add, subtract, multiply or divide a pair of numbers
Suggest an addition that could be made to the algorithm to make it more useful.
To output/store the result/the value of Ans // Adding prompts for data entry.

Question 33

Explain why constants, variables and arrays are used in programming.


Constants
 The value cannot be changed accidentally …
 …during the execution of the program
 Value only needs to be changed once if circumstances change/during the initialisation
process
Variables
 Stores a value that can change …
  during the execution of the program
 Can use a variable without knowing its value
Arrays
 A list of items of the same data type …
 … stored under a single name
 To reduce the number of variables used
 Any item can be found using an index number to show its place in the list

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

Line 3 RandNum[Counter] should be RandNum[Count]


Line 3 Rand(1, 100) should be Rand(1, 101)
Line 4 Counter ← Counter + 2 should be Count ← Count + 1
Line 5 UNTIL Count <= 50 should be UNTIL Count >= 50 // UNTIL Count = 50

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

Identify another loop structure available in pseudocode.


Precondition loop // WHILE … DO … ENDWHILE
Question 35

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

UNTIL Score >= 0 AND Score <= 100

Question 36

Describe a one-dimensional array. Include an example of an array declaration.


 a list / one column of items
 … of the same data type
 … stored under a single identifier
 … with a single index to identify each element
 example e.g. DECLARE MyArray[1:10] OF INTEGER
Explain how indexing could be used to search for a value stored in a one-dimensional array.
 using a counter to index the array
 so that the same code can be repeatedly used to check every element // every element
can be checked in a loop
Question 37

The pseudocode represents an algorithm.


The pre-defined function DIV gives the value of the result of integer division.
For example, Y = 11 DIV 4 gives the value Y = 2

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

This section of program code may be used as a validation check.


1 PRINT "Input a value between 0 and 100 inclusive"
2 INPUT Value
3 WHILE Value < 0 OR Value > 100
4 PRINT "Invalid value, try again"
5 INPUT Value
6 ENDWHILE
7 PRINT "Accepted: ", Value

Give a name for this type of validation check.


Range check
Describe what is happening in this validation check.
 The entered number (Value)is being checked to see that it is not < 0 or not > 100
 If it is, it is rejected and the user has to enter another number / an error message is
displayed
 Otherwise the number is accepted, the word ‘Accepted’ is output
along with the Value

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

Explain what is meant by validation and verification.


Give an example for each one.
Validation
 automated checking
 checking that data is reasonable / of a certain type
 checking that data meets certain criteria
Example
range check // length check // type check // check digit etc.
Verification
 checking that data has not changed…
 …during input to a computer
 …during transfer between computers / devices
Example
double entry // checking against original // visual check // use of checksum etc.
Question 4

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.

 Double (data) entry


 Visual check
Describe the difference between validation and verification.
 Validation checks if the data entered is possible/it cannot check if data has been
entered correctly.
 Verification checks if the data entered matches the data submitted for entry/ it does
not check if data matches set criteria.
Question 5

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 the use of a subroutine in a program. [2]


 Sub-program / system not the whole program / system
 To perform a frequently used operation within a program
 That can be called when needed
 That can be reused by another program
Question 8

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

A program checks if the weight of a baby is at least 2 kilograms.


Give, with reasons, two different values of test data that could be used for the baby’s weight.

Each reason must be different. [4]


Value 1
2
boundary should be accepted as weight OK (1)
Value 2
two
erroneous/abnormal should be rejected (1)
Question 13

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

This pseudocode algorithm is used as a validation check.


PRINT "Input a number from 1 to 5000"
REPEAT
INPUT Number
IF Number < 1 OR Number > 5000 THEN
PRINT "Invalid number, please try again"
ENDIF
UNTIL Number >= 1 AND Number <= 5000

PRINT Number, " is within the correct range"

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

A software company is working on a project to develop a registration system for a school.


The registration system project has progressed to the design stage.
State three activities that will take place during the design stage of the program development life
cycle.
 Data structures
 Algorithms / flowcharts / pseudocode
 Program structure (modules) / use of library routines / module – team allocation
 Testing method / plan
 Choice of programming language / program environment
Question 21

Functions and procedures are subroutines.


Explain why you should use subroutines when designing a program solution
 When a section of code would be repeated
 When a piece of code is needed to perform a specific task
 To support modular programming / step wise refinement
 Easier to debug / maintain
 Built-in / library routines are tried and tested
Question 22

Identify three different ways of presenting the design of a solution.


 Structure diagrams
 Flowcharts
 Pseudocode algorithms
Identify the four different types of test data.
 Normal
 Abnormal
 Extreme
 Boundary
Question 23

Describe the use of decomposition in the design of a solution


 Splits a system into sub-systems, then each sub-system into further sub-systems.
 Can be used to identify subroutines.
 Can be used to identify repeated elements.
 Solving many smaller problems is often easier than solving one large problem
Question 24

Explain the difference between counting and totalling.


 Totalling adds the values entered to each other.
 Counting adds 1 for each value that is entered
Question 25

A food ordering system is an example of a computer system that is made up of sub-systems.


The food ordering system:
 allows the user to enter the details of the food they want to order and to pay for the
order
 displays food available as pictures or as a list.
Complete the structure diagram for the given parts of the food ordering system.
Two-dimensional Array, Functions / Procedures and File handling Questions

Question 01

A student is developing an algorithm to count the number of times a given string,


SearchString, appears in a 2D array. The array, Item, consists of 100 elements organised as 50
rows of 2 columns. SearchString could appear in any row or column. The array is declared in
pseudocode as follows:
DECLARE Item : ARRAY [1:50, 1:2] OF STRING

The structured English description of the algorithm is:


1. SET Count to 0.
2. Examine the first row of the array.
3. IF column 1 element value is equal to SearchString, ADD 1 to Count.
4. IF column 2 element value is equal to SearchString, ADD 1 to Count.
5. REPEAT from step 3 for next row, UNTIL row is last row.
6. OUTPUT a suitable message and Count.
Write pseudocode for the algorithm.
DECLARE Index, Count : INTEGER
Count ← 0
FOR Index ← 1 TO 50
IF Item[Index, 1] = SearchString THEN
Count ← Count + 1
ENDIF
IF Item[Index, 2] = SearchString THEN
Count ← Count + 1
ENDIF
NEXT
OUTPUT "The number of times SearchString found: ", Count
Alternative
DECLARE I, J, Count : INTEGER
Count ← 0
FOR I ← 1 TO 50
FOR J ← 1 TO 2
IF Item[I, J] = SearchString THEN
Count ← Count + 1
ENDIF
NEXT
NEXT
OUTPUT "The number of times SearchString found: ", Count
Question 2

A function, ProcessMarks(), is required to analyse test marks for a class of students.

 There are 20 students in the class.


 A mark is between 0 and 100.
 The marks for the class are stored in an array, Mark, which has 20 elements.
 The array is passed to the function as a parameter.
 The function will output a message stating the average and highest marks. For
example: "The average mark is 34 and the highest mark is 76"
 The function returns the subscript of the highest mark.
Write pseudocode to implement the ProcessMarks(), function
FUNCTION ProcessMarks(Mark: ARRAY[1:20] OF INTEGER) RETURNS INTEGER
DECLARE Highest : INTEGER
DECLARE Average : REAL
DECLARE Total : INTEGER
DECLARE Position : INTEGER
Total ← 0
Highest ← Mark[1] //The highest mark is the first one
Position ← 1
FOR i ← 1 TO 20
Total ← Total + Mark[i]
IF Mark[i] > Highest THEN
Highest ← Mark[i]
Position ← i
ENDIF
NEXT
Average ← Total/20
OUTPUT ("The average mark is " , Average , " and the highest mark
is " , Highest)
RETURN Position
ENDFUNCTION
Question 3

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]:

The game is to be implemented using the following procedures :


 InitialiseGrid()
 DisplayGrid()
 HideTreasure()
 DigHole(Row,Col)
 StartDig()
We are going to design the algorithm for this program using pseudocode step by step
Step 1
Write pseudocode to declare a 2D array called Grid to represent the squares of the island
DECLARE Grid ARRAY [0:9, 0:29] OF CHAR

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'

IF Grid[Row][Col] = Treasure THEN


Grid[Row][Col] ← FoundTreasure
ELSE
Grid[Row][Col] ← Hole
ENDIF
ENDPROCEDURE
Step 6
StartDig()

 Prompts the player for a location to dig


 Validates the user input
 Calls the DigHole procedure from step 5

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

PRINT("Enter position from 0 to 29: ")


INPUT Y
WHILE Y < 0 OR Y > 29 DO
PRINT("Invalid position - try again")
INPUT Y
ENDWHILE
CALL DigHole(X,Y)
ENDPROCEDURE

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.

Write pseudocode for the procedure Summarise().


PROCEDURE Summarise()
DECLARE Value : REAL
DECLARE IxA, IxB : INTEGER // Index variables
IxB ← 1
FOR IxA ← 1 TO 598 STEP 3
Value ← Array1[IxA] + Array1[IxA + 1] + Array1[IxA + 2]
Value ← Value / 3
Array2[IxB] ← INT(Value)
IxB ← IxB + 1
NEXT IxA
ENDPROCEDURE
Question 5

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.

Complete the missing pseudocode statement


YearSize ← 249
Flag ← TRUE
WHILE Flag = TRUE
Flag ← FALSE
FOR Student ← 1 TO YearSize - 1
IF Score[Student] < Score[Student + 1] THEN
Temp1 ← Score[Student]
Temp2 ← Name[Student,1]
Temp3 ← Name[Student,2]
Score[Student] ← Score[Student + 1]
Name[Student,1] ← Name[Student + 1,1]
Name[Student,2] ← Name[Student + 1,2]
Score[Student + 1] ← Temp1
Name[Student + 1,1] ← Temp2
Name[Student + 1,2] ← Temp3
Flag ← TRUE
ENDIF
NEXT Student
ENDWHILE
Question 6

The following pseudocode declares and initialises an array.


DECLARE Code : ARRAY[1:100] OF STRING
DECLARE Index : INTEGER
FOR Index 1 TO 100
Code[Index] ← ""
NEXT Index

The design of the program is changed as follows:


 the array needs to be two dimensional, with 500 rows and 4 columns
 the elements of the array need to be initialised to the string "Empty"

Re-write the pseudocode to implement the new design.


DECLARE Code : ARRAY[1:500, 1:4] OF STRING
DECLARE RowIndex : INTEGER
DECLARE ColIndex : INTEGER
FOR RowIndex ← 1 TO 500
FOR ColIndex ← 1 TO 4
Code[RowIndex, ColIndex] ← "Empty"
NEXT
NEXT
Question 8

The following pseudocode is an example of nested IF statements


IF MyVar = 1 THEN
CALL Proc1()
ELSE
IF MyVar = 2 THEN
CALL Proc2()
ELSE
IF MyVar = 3 THEN
CALL Proc3()
ELSE
OUTPUT "Error"
ENDIF
ENDIF
ENDIF

Use pseudocode to write a CASE statement with the same functionality


CASE OF MyVar
1: CALL Proc1()
2: CALL Proc2()
3: CALL Proc3()
OTHERWISE
OUTPUT "Error"
ENDCASE
Question 9

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.

correct names in order: HOURS, TOTAL, TAX


The printout will be different for those staff who receive cash and those who have their earnings
paid directly to a bank account. Add the next level to the print module.

PRINT has two boxes under: CASH and BANK


Explain how it is possible to use the same variable name for different variables in different
modules.
 each variable has local scope // scope within block only – does not affect same variable
name in a different block
Question 10

Gina is developing her programming skills in string handling.


She is going to input one string.
The string contains letters and zero or more '*' characters in any positions.
Gina wants to remove all the '*'s and output the letters in their original order.
For example:
• input "com*put**er*", the output is "computer"

• input " hardware", the output is "hardware"

Write an algorithm using pseudocode to perform this task. (Ensure that you use meaningful variable
names)

You will need to use:


 & Concatenates (joins) two strings Example: "Summer" & " " & "Pudding" evaluates to
"Summer Pudding" Note: This operator may also be used to concatenate a character with a
string
 SUBSTRING
 LENGTH
DECLARE OldString, NewString : STRING
DECLARE i : INTEGER
DECLARE NextChar : CHAR

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.

This grid of asterisks (*) is produced by the procedure call:


ShowMultiplicationGrid(3, 4)

Complete the pseudocode for this procedure:


PROCEDURE ShowMultiplicationGrid(Number1 : INTEGER,
Number2: INTEGER)
DECLARE Row , Column : INTEGER
FOR Row ← 1 TO Number1
FOR Column ← 1 TO Number2
OUTPUT ('*')
NEXT Column
OUTPUT() //NewLine
NEXT Row
ENDPROCEDURE
The procedure CheckAnswerCorrect gives the child three chances to type in the correct
answer.
OUTPUT "Correct. Well done! " if the child typed the correct answer,
OUTPUT "You need to practice more. The correct answer is ", Result

if all three attempts are incorrect.


Write an algorithm using pseudocode for the procedure CheckAnswerCorrect .

PROCEDURE CheckAnswerCorrect(Number1 : INTEGER,


Number2: INTEGER)
DECLARE NumberOfTries : INTEGER
DECLARE Result : INTEGER
DECLARE Answer : INTEGER

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

Explain why a program might need to store data in a file.


 data is not lost when the computer is switched off // data is stored permanently
 data can be used by more than one program or reused when a program is run again
 data can be backed up or archived • data can be transported from one place / system to
another
Question 14

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.

Write a program that meets the following requirements:


 calculates the combined total mark for each student for all their subjects
 calculates the average mark for each student for all their subjects, rounded to the nearest
whole number
 outputs for each student
 name
 combined total mark
 average mark
 grade awarded
 calculates, stores and outputs the number of distinctions, merits, passes and fails for the
whole class.
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 array.
NOTE
You can conceptually think about it using the following data to plane your solution, this is not part
of the question:

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

DECLARE TotalMark : ARRAY[1:50] OF INTEGER


DECLARE AverageMark : ARRAY[1:50] OF INTEGER
DECLARE SubjectCounter : INTEGER
DECLARE StudentCounter : INTEGER
DECLARE DistinctionNo : INTEGER
DECLARE MeritNo : INTEGER
DECLARE PassNo : INTEGER
DECLARE FailNo : INTEGER

CONSTANT Distinction = 70
CONSTANT Merit = 55
CONSTANT Pass = 40
//Initialising the running totals used for grades
DistinctionNo ← 0
MeritNo ← 0
PassNo ← 0
FailNo ← 0

//Initialising the array TotalMark with a zero value


FOR StudentCounter ← 1 TO ClassSize
TotalMark[StudentCounter] ← 0
NEXT StudentCounter

//Loop starting from 1 to the calss size


FOR StudentCounter ← 1 TO ClassSize

//Loop starting from 1 to the subject number


//To calculate the total mark for each student
FOR SubjectCounter ← 1 TO SubjectNo
TotalMark[StudentCounter] ← TotalMark[StudentCounter] +
StudentMark[StudentCounter,SubjectCounter]
NEXT SubjectCounter

//Calculate the average mark for each student


//and round the average to 0 decimal places
AverageMark[StudentCounter] ←
ROUND((TotalMark[StudentCounter] / SubjectNo) ,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

OUTPUT "Number of Distinctions ", DistinctionNo


OUTPUT "Number of Merits ", MeritNo
OUTPUT "Number of Passes ", PassNo
OUTPUT "Number of Fails ", FailNo
Pseudocode Solution #2

DECLARE TotalMark
DECLARE AverageMark
DECLARE SubjectCounter : INTEGER
DECLARE StudentCounter : INTEGER
DECLARE DistinctionNo : INTEGER
DECLARE MeritNo : INTEGER
DECLARE PassNo : INTEGER
DECLARE FailNo : INTEGER

//Initialising the running totals used for grades


DistinctionNo ← 0
MeritNo ← 0
PassNo ← 0
FailNo ← 0

//Loop starting from 1 to the calss size


FOR StudentCounter ← 1 TO ClassSize
//Initialising the TotalMark with a zero value
TotalMark ← 0

//Loop starting from 1 to the subject number


//To calculate the total mark for each student
FOR SubjectCounter ← 1 TO SubjectNo
TotalMark ← TotalMark +
StudentMark[StudentCounter,SubjectCounter]
NEXT SubjectCounter

//Calculate the average mark for each student


//and round the average to 0 decimal places
AverageMark ←
ROUND((TotalMark[StudentCounter] / SubjectNo) ,0)

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

OUTPUT "Number of Distinctions ", DistinctionNo


OUTPUT "Number of Merits ", MeritNo
OUTPUT "Number of Passes ", PassNo
OUTPUT "Number of Fails ", FailNo
Pseudocode Solution #3 Using Procedures

DECLARE TotalMark : ARRAY[1:50] OF INTEGER


DECLARE AverageMark : ARRAY[1:50] OF INTEGER
DECLARE StudentGrade : ARRAY[1:50] OF INTEGER
DECLARE DistinctionNo, MeritNo, PassNo, FailNo : INTEGER

//Initialising the array TotalMark with a zero value


PROCEDURE InitiliseTotal()
DECLARE StudentCounter : INTEGER
FOR StudentCounter ← 1 TO CalssSize
TotalMark[StudentCounter] ← 0
NEXT StudentCounter
ENDPROCEDURE
//Calculate the total mark for each student
PROCEDURE CalculateTotal()
DECLARE StudentCounter : INTEGER
DECLARE SubjectCounter : INTEGER
FOR StudentCounter ← 1 TO CalssSize
FOR SubjectCounter ← 1 TO SubjectNo
TotalMark[StudentCounter] ← TotalMark[StudentCounter]
+ StudentMark[StudentCounter, SubjectCounter]
NEXT SubjectNo
NEXT StudentCounter
ENDPROCEDURE
//Calculate the average mark for each student
//and round the average to 0 decimal places
PROCEDURE CalculateAverage()
DECLARE StudentCounter : INTEGER
FOR StudentCounter ← 1 TO CalssSize
AverageMark[StudentCounter] ←
ROUND((TotalMark[StudentCounter]/SubjectNo),0)
NEXT StudentCounter
ENDPROCEDURE
//Decide the awarded grade based on their average mark
PROCEDURE DecideGrade()

DistinctionNo ← 0
MeritNo ← 0
PassNo ← 0
FailNo ← 0

FOR StudentCounter ← 1 TO CalssSize


IF AverageMark[StudentCounter] >= 70 THEN
DistinctionNo ← DistinctionNo + 1
StudentGrade[StudentCounter] ← "Distinction"
ELSE
IF AverageMark[StudentCounter] >= 55 THEN
MeritNo ← MeritNo + 1
StudentGrade[StudentCounter] ← "Merit"
ELSE
IF AverageMark[StudentCounter] >= 40 THEN
PassNo ← PassNo + 1
StudentGrade[StudentCounter] ← "Pass"
ELSE
FailNo ← FailNo + 1
StudentGrade[StudentCounter] ← "Fail"
ENDIF
ENDIF
ENDIF
NEXT StudentCounter
ENDPROCEDURE
//Output Name, Total mark, and average mark and grade for each student
PROCEDURE Output()
FOR StudentCounter ← 1 TO CalssSize
PRINT ("Name: ",StudentName[StudentCounter])
PRINT ("Combined Total Mark: ",TotalMark[StudentCounter])
PRINT ("Average Mark: ",AverageMark[StudentCounter])
PRINT ("Grade: ",StudentGrade[StudentCounter])
PRINT ("Number of Distinctions ", DistinctionNo)
PRINT ("Number of Merits ", MeritNo)
PRINT ("Number of Passes ", PassNo)
PRINT ("Number of Fails ", FailNo)
NEXT StudentCounter
ENDPROCEDURE

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

Part of the validation is implemented by the line:


IF NOT (Dots >= 1 AND Ats = 1 AND Others > 8) THEN

State the values that would result in the condition evaluating to TRUE.

 Condition evaluates to TRUE if bracket contents evaluate to FALSE:


 Bracket contents evaluate to FALSE if:
 Dots: zero / less than one
or
 Ats: not equal to one
or
 Others: less than nine
Complete the trace table by dry running the function when it is called as follows:
Result ← IsValid("Liz.123@big@net")

State the value returned when IsValid() is called using the previous expression

FALSE
Question17

A procedure FirstLines() will:

 take the name of a text file as a parameter


 output the first three lines from that file, in the same order as they appear in the file.
Note:
 You may assume the file exists and contains the three lines.
Write pseudocode for the procedure FirstLines().
PROCEDURE FirstLines(ThisFile : STRING)
OPENFILE ThisFile FOR READ
READFILE Thisfile, ThisLine // read the first line
OUTPUT ThisLine

READFILE Thisfile, ThisLine // read the second line


OUTPUT ThisLine

READFILE Thisfile, ThisLine // read the third line


OUTPUT ThisLine

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

The program flowchart represents an algorithm for FirstTen().

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)

E OUTPUT "Factorial of ", Num, " is ", Value

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

returns an integer value (the ASCII value) of ThisChar

Example: ASC('A') returns 65


OUTPUT "Enter string"
INPUT MyString
StringTotal ← 0
FOR i ← 1 TO LENGTH(MyString)
NextNum ← ASC(SUBSTRING(MyString, i))
StringTotal ← StringTotal + NextNum
NEXT i
OUTPUT MyString, StringTotal

Explain the purpose of sending the value of StringTotal to the remote computer, in addition to
MyString.

 Used to provide an integrity/verification check


 Used as a checksum
 The total can be recalculated by the receiving software
 If any of the characters have been incorrectly transmitted the recalculated total and
transmitted total will not match
Question 20

The company maintains a file of product data


The program records the following data for each product:
 product code
 product description
 product retail price
The text file PRODUCTS.TXT stores each data item on a separate line, as shown below:

The program uses the variables shown in the identifier table.

Identifier Data type Description

TEXT FILE Storing the code, description and


PRODUCTS.TXT
retail price for all current products

PCode ARRAY[1:1000] OF STRING Array storing the product codes

ARRAY[1:1000] OF STRING Array storing the product


PDescription
descriptions

ARRAY[1:1000] OF REAL Array storing the product retail


PRetailPrice
prices

INTEGER Array index used by all three


i
arrays
The program reads all the product data held in file PRODUCTS.TXT and write them into the three
1D arrays. Complete the pseudocode below.
OPENFILE "PRODUCTS.TXT " FOR READ
i ← 1
READFILE "PRODUCTS.TXT ", PCode[i]
WHILE LENGTH(PCode[i]) > 0 DO
READFILE "PRODUCTS.TXT ", PDescription[i]
READFILE "PRODUCTS.TXT ", PRetailPrice[i]
READFILE "PRODUCTS.TXT ", PCode[i]
i ← i + 1
ENDWHILE
CLOSE "PRODUCTS.TXT"
OUTPUT "Product file contents written to arrays"
Question 21

Complete the trace table for the following algorithm


Count ← 0
FOR y ← 0 TO 2
FOR x ← 0 TO 3
IF DataArray[x][y] = 3 THEN
Count ← Count + 1
ENDIF
NEXT x
NEXT y
OUTPUT(Count)

The array DataArray currently stores the data:

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

Why do programs sometimes need to store data in a file?


To prevent data being lost when the program ends / to store data permanently to be loaded
next time the program is opened
What are the three stages of reading data from a file?
 Open the file
 Read the data
 Close the file
What are the three stages of storing data into a file?

 Open the file


 Write the data
 Close the file
Create a text file with the name "myData.txt". Enter a word in the file.
Write a program to read the word from the file and output it.

OPENFILE "myData.txt" FOR READ


READFILE "myData.txt" , Data
CLOSEFILE "myData.txt"
OUTPUT(Data)

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.

OPENFILE "TotalData.txt" FOR READ


READFILE "TotalData.txt", Total
CLOSEFILE "TotalData.txt"

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

The two-dimensional (2D) array Sales[1:28,1:2] contains the number of sales


made for each site

Data for the first 28 days is shown below.

SalesDate SiteX SiteY


1 03/06/2015 1 0 2
2 04/06/2015 2 1 8
3 05/06/2015 3 3 0
4 06/06/2015 4 0 6
5 07/06/2015 5 4 4
6 08/06/2015 6 4 9
7 09/06/2015 7 5 9
8 10/06/2015 8 11 1
… … … … …
28 01/07/2015 28 14 8

Write a program that meets the following requirements:


 Calculate and output the total number of sales made for each site for the first 28 days.
 For the first seven days only, calculate the number of days that total sales were 10 or over
when you add the sales for site x plus the sales for site y. Output the corresponding date and
the final total number of days

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[]

All inputs and outputs must contain suitable messages.


You do not need to initialise the data in the arrays Sales[] and SalesDate[]
//Declare variables
DECLARE TotalSiteX : INTEGER
DECLARE TotalSiteY : INTEGER
DECLARE Day : INTEGER
DECLARE CountDays : INTEGER

//Initialise variables
TotalSiteX ← 0
TotalSiteY ← 0
CountDays ← 0

//Loop 28 times to calculate the total sales for site X


FOR Day ← 1 TO 28
TotalSiteX ← TotalSiteX + Sales[Day,1]
NEXT Day

//Loop 28 times to calculate the total sales for site Y


FOR Day ← 1 TO 28
TotalSiteY ← TotalSiteY + Sales[Day,2]
NEXT Day

//Output totals
PRINT("Site X total is",TotalSiteX)
PRINT("Site X total is",TotalSiteY)

//Loop 7 times to calculate the number of sales


//That SiteX + SiteY >=10
FOR Day ← 1 TO 7
IF Sales[Day,1] + Sales[Day,2] >= 10 THEN
PRINT(SalesDate[Day])
CountDays ← CountDays + 1
ENDIF
NEXT Day
PRINT("Number of days sales were 10 or more is ",CountDays)
Question 25

The variables X, Y and Z are used in a program: X stores a whole number, Y stores a decimal

number and Z stores a flag that can be set to TRUE or FALSE

Write pseudocode statements to declare the variables X, Y and Z


DECLARE X : INTEGER
DECLARE Y : REAL
DECLARE Z : BOOLEAN
The function Same(A,B) returns TRUE if the value of A is the same as the value of B when B

is rounded to the nearest whole number and FALSE otherwise.

Write pseudocode statements to:


 define the function
 call the function with X and Y and store the return value in Z

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)

State the difference between defining and calling a function.

 A function is defined once and called many times or


 Define – setting up the function and call is using a function
Question 26

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

already been done.


All inputs and outputs must contain suitable messages.
You do not need to initialise the data in the arrays TeamName[] and TeamPoints[] or the

variables LeagueSize and MatchNo


// meaningful identifier names and appropriate data structures to
// store the data required

DECLARE TeamCounter : INTEGER


DECLARE MatchCounter : INTEGER
DECLARE TeamPoints : INTEGER
DECLARE AwayWinNo : INTEGER
DECLARE HomeWinNo : INTEGER
DECLARE DrawNo : INTEGER
DECLARE LostNo : INTEGER
DECLARE HighestPoints : INTEGER
DECLARE LowestPoints : INTEGER
DECLARE TopTeam : INTEGER
DECLARE BottomTeam : INTEGER
CONSTANT AwayWin = 3
CONSTANT HomeWin = 2
CONSTANT Draw = 1
CONSTANT Lost = 0
// zero totals for each club’s results
FOR TeamCounter ← 1 to LeagueSize
TotalPoints [TeamCounter] ← 0
NEXT TeamCounter
FOR TeamCounter ← 1 TO LeagueSize
// zero totals for each club’s result details
AwayWinNo ← 0
HomeWinNo ← 0
DrawNo ← 0
LostNo ← 0
FOR MatchCounter ← 1 TO MatchNo
TotalPoints[TeamCounter] ← TotalPoints [TeamCounter]
+ TeamPoints[TeamCounter,MatchCounter]
CASE OF TeamPoints[TeamCounter, MatchCounter]
AwayWin : AwayWinNo ← AwayWinNo + 1
HomeWin : HomeWinNo ← HomeWinNo + 1
Draw : DrawNo ← DrawNo + 1
Lost : LostNo ← LostNo + 1
ENDCASE
NEXT MatchCounter
// Output details of a team’s results
OUTPUT "Team ", TeamName[TeamCounter]
OUTPUT "Total points ", TotalPoints[TeamCounter]
OUTPUT "Away wins ", AwayWinNo
OUTPUT "Home wins ", HomeWinNo
OUTPUT "Draws ", DrawNo
OUTPUT "Losses ", LossNo
// Check for highest and lowest results

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

A function LENGTH(X) finds the length of a string X and a function SUBSTRING(X,Y,Z)


finds a substring of X starting at position Y and Z characters long. The first character in the string
is position 1. Show the value of the variable after each pseudocode statement has been executed.
01 P ← "Computer Science" Computer Science
02 Q ← LENGTH(P) 16
03 R ← SUBSTRING(P,10,7) Science
04 S ← LENGTH(R) 7
05 T ← SUBSTRING(R,1,3) Sci
Write a pseudocode statement to extract the word Computer from P and store it in the variable F.

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

You might also like