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

As P2 Fundamental Problem-Solving and Programming Skills V24 Compress

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

As P2 Fundamental Problem-Solving and Programming Skills V24 Compress

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

COMPUTER SCIENCE WITH INQILAB PATEL

Page | 1

Contents
About the developer of this workbook ....................................................................................................................4
9 Algorithm Design and Problem-Solving .................................................................................................................6
9.1 Computational Thinking Skills ........................................................................................................................7
12.2 Structure Chart .......................................................................................................................................... 14
9.2 Algorithm ..................................................................................................................................................... 41
1 Programming ...................................................................................................................................................... 77
11.2 Control Construct: Sequence ..................................................................................................................... 77
11.2 Control Construct: Selection...................................................................................................................... 79
11.2 Control Construct: Loop .......................................................................................................................... 103
12.2 Filling in Trace Table ................................................................................................................................ 136
11.3 Structure (modular) Programming (Functions & Procedures) ................................................................ 138
10 Data Types and Structures.............................................................................................................................. 234
10.1 Record Data Type .................................................................................................................................... 234
10.2 Arrays: Data Structure ............................................................................................................................ 247
10.3 File Handling ................................................................................................................................................ 323
10.4 Introduction to Abstract Data Types (ADT) ................................................................................................. 365
11.1 String manipulation Algorithms................................................................................................................... 397
12 Software Development................................................................................................................................... 424
12.1 Program Development Life cycle .................................................................................................. 424
12.3 Program Testing and Maintenance ......................................................................................................... 437
12.2 State Transition Diagram ......................................................................................................................... 454
End of the Paper Algorithms ............................................................................................................................... 472
Insert.................................................................................................................................................................... 533

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 2

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 3

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 4

About the developer of this workbook


Inqilab Patel is an O & A Level Computer Teacher. Currently he is teaching A & O Level
Computer Science at The City School PAF Chapters, Hira Foundation School and Intellect.
He has taught in many other schools including Yaqeen Model School, Karachi Cadet School, KN
Academy, Hexis A Level, Verge and Nakhlah Boys Campus Society. Cambridge has selected
him as a Member of Cambridge Editorial Review Board. He is also associated with Aga Khan
University Examination Board in the capacity of Chief Examiner, Item Writer, E-Marker,
Karachi Board of Secondary Education the capacity of Deputy Head Examiner and Sindh
Board of Technical Education.
His entire career path revolves around computer science; either he was a student or a teacher.
He got a chance to polish his skills of teaching and studying more about computers at various
levels which has given him great confidence in presenting himself for any senior level position of
transferring his knowledge to the youth.
Inqilab Patel knows a lot of methods of teaching computers and has developed tutorial notes,
worksheets and assignments for my students. He also maintains a website
(www.inqilabpatel.com) which is specifically designed for the support of those who want to excel
in GCSE computer science. He also regularly contributes material on different websites and social
media plate forms for teachers’ and learners’ support, for which he receives appreciation from
different people across the world.
By the Grace of Almighty his students have begged following distinctions:
Top in World Position in CAIE 2017 Anas Gadar -The City School PAF Chapter
Top in World Position in CAIE 2018 Azar Khowaja
Top in Pakistan Position in CAIE 2021 Muhammad Ahmed Abyan - The City School PAF Chapter
Top in Sindh Balochistan Position in CAIE 2021 Muhammad Warris Bhutto

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 5

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 6
9 Algorithm Design and Problem-Solving
An algorithm is a series of well-
defined steps which gives a
procedure for solving a type of
problem.
The word algorithm comes from
the name of 9th century
mathematician al-Khwarizmi
(Muhammad Bin Musa Al-
Khwarizmi).
In fact, even the word algebra is
derived from his book “Hisab al-
jebrw’al-muqabala”

“An algorithm is a sequence of steps for a computer program to accomplish a


task.”
In general, an 'algorithm' is the name given to a defined set of steps used to complete a task.
For instance, you could define an algorithm to make a cup of tea. You start by filling the kettle,
and then place a tea bag in the cup and so
on.
In computer terms, an algorithm describes the
set of steps needed to carry out a software task.
This mini-web takes you through the topic of
algorithm.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 7
ͻǤͳ‘’—–ƒ–‹‘ƒŽŠ‹‹‰‹ŽŽ•
Syllabus outline:
Describe and use decomposition
Break down problems into sub-problems leading to the concept of a program module
(procedure / function)
Use a structure chart to decompose a problem into sub tasks and express the parameters
passed between the various modules/procedures functions which are part of the algorithm
design.

Abstraction – the process of extracting information that is essential, while ignoring what is
not relevant, for the provision of a solution.
Decomposition – the process of breaking a complex problem into smaller parts.
Pattern recognition – the identification of parts of a problem that are similar and could use
the same solution.
Computational thinking is used to study a problem and formulate an effective solution that can
be provided using a computer. There are several techniques used in computational thinking,
including abstraction, decomposition, and pattern recognition.
Q 1) What is meant by computational thinking?
Computational Thinking - is used to study a problem and formulate an effective solution that
can be provided using a computer. There are several techniques used in computational
thinking, including abstraction, decomposition, and pattern recognition.

Q 2) Give reason/benefits for decomposition (breaking down a problem).


x Program code is easier to implement.
x Different people can be assigned to work on different modules.
x Program code is easier to test and debug.
x Modules are re-usable.

Q 3a) Describe need for and benefits of using abstraction, Describe the purpose of
abstraction.
Abstraction involves filtering out information that is not necessary (non-essential) to solve a
problem.
Abstraction gives us the power to deal with complexity.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 8
The benefits of abstraction:
• the time required to develop the program is reduced so the program can be delivered to the
customer more quickly
• the program is smaller in size so takes up less space in memory and download times are
shortened
• customer satisfaction is greater as their requirements are met without any extraneous
features.
Q 3b) Stepwise refinement is often used in the development of an algorithm.
Describe stepwise refinement.
Stepwise refinement – is the practice of subdividing each part of a larger problem into a
series of smaller parts, and so on, as required.
Benefits of Stepwise refinement:
x Increases the level of detail of the algorithm.
x Make steps easier to solve.
x to be directly translated into lines of code.

Q 4) What is system and sub-system?


A system is a set of rules, an arrangement of things, or a group of related things that work
together to perform a function.
A system is made up of a number of subsystems. Each subsystem can be further divided
into subsystems and so on until each sub-system just performs a single action.
Computer system is often divided up into sub-systems. This division can be shown using
top-down design to produce structure diagrams that demonstrate the modular construction of
the system.
Q 5) Define System and Sub-system.
System is a set of principles or procedures according to which something is done; an
organized scheme or method.
A system is a set of rules, an arrangement of things, or a group of related things that work
together to perform a function.
A system is made up of a number of subsystems. Each subsystem can be further divided into
subsystems and so on until each sub-system just performs a single action.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 9
Q 6) What is meant by computer system?
A COMPUTER SYSTEM is made up of hardware, software & data, communications and
people; each computer system can be divided up into a set of sub-systems. Each subsystem
can be further divided into sub-systems and so on until each sub-system just performs a
single action.
Q 7) Define Top-Down Design
Top-down design is the breaking down of a computer system into a set of subsystems, then
breaking each sub-system down into a set of smaller sub-systems, until each sub-system just
performs a single action.

Q 8) What is transferable skills? Explain how it helps in work on not familiar programming
language.
Transferable skills, are the abilities programmer can transfer from one language to another.
Programmer should be able to recognise / understand in another language:
• Declaration, assignment, sequence, selection, repetition (iteration)
Subroutines, Parameters passed between modules
program structure, Input and Output

Q 8) Describe Structure Diagrams


The STRUCTURE DIAGRAM shows the design of a computer system in a hierarchical way,
with each level giving a more detailed breakdown of the system into sub-systems.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 10
Q 9) A structure chart is often used in modular program design.
State four features of structure diagram:
Feature 1: Sequence of operation
Feature 2: Selection of modules
Feature 3: Repetition
Feature 4: Parameters
Q 10) Define Library routines
A LIBRARY ROUTINE is a set of programming instructions for a given task that is already
available for use. It is pre-tested and usually performs a task that is frequently required.
Q 11) Define Sub-routines
A SUB-ROUTINE is a set of programming instructions for a given task that forms a
subsystem, not the whole system. Sub-routines written in high-level programming languages
are called ‘procedures’ or ‘functions’ depending on how they are used.
Q 11b) State three advantages of using built-in functions.
Saves development time, no need to write it again.
Pre-compiled and well tested, more reliable, less chance of error
Available to all programs
Q 12) What is meant by Function?
A Function is a sub-routine that always returns a value.
Q 13) What is meant by Procedure?
A Procedure is a sub-routine that doesn’t have to returns a value.
Q 14) Differentiate terms Parameter and Argument.
A parameter is a variable in a method definition. While the arguments are the data that are
passed.
2ac 9618 W21 P21_23
1 (c) An airline wants to provide passengers with information about individual flights and allow
them to book their flight using an online booking system.
(i) Tick one box in each row of the table to indicate whether each item of information would be
essential for the customer when making the booking. [3]
Information Essential Not essential
Departure time
Flight number
Departure airport
Aircraft type
Ticket price
Number of seats in aircraft

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 11
(ii) Identify the technique used to filter out information that is not essential when designing the
booking system and state one benefit of this technique.
Technique ..........................................................................................................................
Benefit ...............................................................................................................................
........................................................................................................................................... [2]
(iii) Identify two additional pieces of essential information that a passenger might need when
booking a flight.
1 ........................................................................................................................................
2 ........................................................................................................................................ [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 12

2b 9618 W21 P22


1 (a) A programmer applies decomposition to a problem that she has been asked to solve.
Describe decomposition.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................................... [2]

1 (a) Complete this definition of the term algorithm.


An algorithm is a solution to a problem expressed as ..............................................................
.....................................................................................................................................................
................................................................................................................................................ [2]
(b) A program design includes the use of subroutines (functions and procedures).
Give three advantages of using subroutines in a program.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
............................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 13
(c) Draw lines on the following diagram to connect each computing term with the appropriate
description. [3]
Term Description
Checking that a program performs as
Selection
expected

A method for increasing the level of


Black-box testing
detail of an algorithm

Stepwise To test a condition to determine the


refinement path of program execution

A method of executing certain lines of


Iteration
code more than once

14a 9608 Winter 21 P21


3 (c) (i) State two benefits of user-defined functions.
Benefit 1 ............................................................................................................................
...........................................................................................................................................
Benefit 2 ............................................................................................................................
........................................................................................................................................... [2]
(ii) State two benefits of built-in functions. Do not give the same answers as in part (c)(i).
Benefit 1 ............................................................................................................................
...........................................................................................................................................
Benefit 2 ............................................................................................................................
........................................................................................................................................... [2]
• Reduces the length of the overall program code
• Less chance of errors as do not need to re-write / re-test
3(c)(i) • One change in function will be applied in all places used 2
• Can use in multiple programs without rewriting
• Can share amongst other programmers to avoid everyone rewriting
• Allows the use of functions that are difficult to code
• They (should) have been more extensively tested //
3(c)(ii)
• Reduce the time to test your code
• Reduce the time to write

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 14
ͳʹǤʹ–”— –—”‡Šƒ”–
A Structure chart is graphical representation of the modular structure of a solution
It is an alternative approach to modular design is to choose the sub-tasks and then construct a
structure chart to show the interrelations between the modules. Each box of the structure chart
represents a module. Each level is a refinement of the level above.
A structure chart also shows the interface between modules, the variables. These variables are
referred to as 'parameters' (a value passed between modules). A parameter supplying a value to a
lower-level module is shown as a downwards pointing arrow. A parameter supplying a new value to
the module at the next higher level is shown as an upward pointing arrow.
Structure charts help programmers to visualise how modules are interrelated and how they interface
with each other. When looking at a larger problem this becomes even more important.
Purpose of structure chart:
Structure charts are used to demonstrate:
x Decomposition or top-down design (how a problem is broken down into smaller sub-tasks),
x Hierarchy of the program,
x Selection and repetition (loop),
x The parameters (data items being exchanged among modules),
x Modules are whether function or procedure.

Figure shows a structure chart for the Connect 4 program. It uses the following symbols:
• An arrow with a solid round end shows that the value transferred is a flag (a Boolean
value).
• A double-headed arrow shows that the variable value is updated within the
module

Symbol Name Meaning


Each Box represents a programming module, this might be
Module Name Process something that calculates the average of some figures, or
prints out some pay slips
Data being passed from module to module that needs to be
Data Couple
processed.
Check data sent to process to stop or start processes. For
example when the End of a File that is being read is
Flag
reached, or a flag to say whether data sent was in the
correct format
Parameters shows that the variable value is updated within the module
passed by
reference

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 15
Figure shows a structure chart for a module that calculates the average of two numbers. The top-level
box is the name of the module, which is refined into the three subtasks of Level 1. The input numbers
(parameters Numberl and Number2) are passed into the 'Calculate Average' sub-task and then the
Average parameter is passed into the 'OUTPUT
Average' sub-task. The arrows show how the parameters are passed between the modules. This
parameter passing is known as the 'interface'.

Module: Section of code that perform part of the task not whole task, also known as sub-routine.
Parameter: The data items being exchanged among modules.
Pass: Exchange of parameters among modules.
Call: Executing a module
Called With: Passing parameters to a module at the time of executing it.
Return: Sending data from called module to the calling module.
Function: A module that always returns a value.
Procedure: A module that never return a value.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 16
Topical Past Papers
Test Yourself 10C Winter 19 P23
3 Three program modules process updating of passwords in a file. A description of the
relationship between the modules is summarised as follows:

Module name Description


• Takes two parameters: AccountID and OldPassword
GetPassword()
• Returns a string containing the new password
• Takes two parameters: AccountID and NewPassword
UpdateFile() • Returns a Boolean value to indicate whether or not the
update was successful
• Calls GetPassword() to obtain the new password then
ChangePassword()
calls UpdateFile() to write the new password to the file

Draw a structure chart to show the relationship between the three modules and the
parameters passed between them. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 17

Winter 19 P21
2 (a) A structure chart is often used in modular program design. One feature shown is the
sequence of module execution.
State four other features that may be shown.
Feature 1 ..................................................................................................................................
...................................................................................................................................................
Feature 2 ..................................................................................................................................
...................................................................................................................................................
Feature 3 ..................................................................................................................................
...................................................................................................................................................
Feature 4 ..................................................................................................................................
.............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 18
Worked Example
3 A modular program design consists of four modules:
Module1() has three sub-tasks. Each sub-task is implemented by a single subroutine (either a
function or a procedure).
The subroutine headings are defined as follows:
FUNCTION Module2 (Weight : REAL) RETURNS BOOLEAN
PROCEDURE Module3 (Weight : REAL, Customer : STRING, Purchased : DATE)
FUNCTION Module4 (Purchased : DATE, Account : INTEGER) RETURNS INTEGER
(a) State the term given to values passed between Value Label
modules. Boolean return value A
Integer return value B
Account C
Customer D
Purchased E
Weight F
....................................................................................................[1]
(b) Draw a structure chart to represent the program design.
Use the letters in the table to label the values passed between modules.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 19
Selection Statements in Structure Chart
The diamond shape shows a condition that is either True or False. So either one branch or the other
will be followed.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 20
11a 9608 S20 P21
2 (a) Three modules form part of a program for a car rental company. A description of the
relationship between the modules is summarised as follows:
Module name Description
A customer will pay for each car rental either by bank card or by using
RentCar()
their account with the rental company.
Called with parameter HireCost, representing the cost of the rental.
PayByCard() Returns a BOOLEAN value to indicate whether or not the card payment
was successful.
Called with parameters HireCost, AccountNumber, CurrentBalance and
AccountLimit.
• Checks whether HireCost plus the CurrentBalance would exceed
PayByAccount() the AccountLimit. If so, then the rental is not authorised.
• If the rental is authorised, then the CurrentBalance is updated.
• Returns a BOOLEAN value to indicate whether or not the rental was
authorised.

Draw a structure chart to show the relationship between the three modules and the
parameters passed between them. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 21
Repetition in Structure Chart
Figure shows the structure chart for the pyramid-drawing program. The semi-circular arrow
represents repetition of the modules below the arrow. The label shows the condition when
repetition occurs.

Draw a structure chart for the following problem: A user attempts to log on with a user ID.
User IDs and passwords are stored in two 1D arrays (lists). The algorithm searches the list of
user IDs and looks up the password in the password list. The user is given three chances to
input the correct password. if the correct password is entered, a suitable message is output. If
the third attempt is incorrect, a warning message is output.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 23
1ac 9618 S21 P21
2 (a) Four program modules form part of a program for a library.
A description of the relationship between the modules is summarised as follows:
Module name Description
UpdateLoan() • Calls either LoanExtend() or LoanReturn()
• Called with parameters LoanID and BookID
• Calls CheckReserve() to see whether the book has been reserved for
LoanExtend()
another library user
• Returns TRUE if the loan has been extended, otherwise returns FALSE
• Called with BookID
CheckReserve()
• Returns TRUE if the book has been reserved, otherwise returns FALSE
• Called with parameters LoanID and BookID
LoanReturn() • Returns a REAL (which is the value of the fine to be paid in the case of an
overdue loan)
Draw a structure chart to show the relationship between the four modules and the parameters
passed between them. [5]

(b) The definition for module LoanReturn() is amended as follows:


Module name Description
Called with parameters LoanID, BookID and Fine
LoanReturn() The module code checks whether the book has been returned on time
and then assigns a new value to Fine
• LoanID and BookID are of type STRING
• Fine is of type REAL
Write the pseudocode header for the amended module LoanReturn().
.....................................................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 24

Examiner Report Question 2


(a) This part question was generally answered well.
Common mistakes included the omission of the selection diamond (MP2) and occasional confusion
over whether the circle on a parameter arrow should be shaded or unshaded.
A small number of answers suggested that the candidates concerned had not studied this topic.
(b) This part question was answered correctly by around half the candidates.
common mistake was to present the subroutine as a function. Of those that correctly identified the
subroutine as a procedure, most correctly identified the need for the BYREF keyword.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 25
3b 9618 s22p22 - 3 (a) The module headers for five modules in a program are defined in
pseudocode as fol
Pseudocode module header
FUNCTION Mod_V(S2 : INTEGER) RETURNS BOOLEAN
PROCEDURE Mod_W(P4 : INTEGER)
PROCEDURE Mod_X(T4 : INTEGER, BYREF P3 : REAL)
PROCEDURE Mod_Y(W3 : REAL, Z8 : INTEGER)
FUNCTION Mod_Z(F3 : REAL) RETURNS INTEGER
An additional module Head() repeatedly calls three of the modules in sequence.
A structure chart has been partially completed.
(i) Complete the structure chart to include the information given about the six modules.
Do not label the parameters and do not write the module names. [3]

(ii) Complete the table using the information in part 3(a) by writing each module name to
replace the labels A to F. [3]
Label Module name
A
B
C
D
E
F

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 26
(b) The structure chart represents part of a complex problem. The process of decomposition
is used to break down the complex problem into sub-problems.
Describe three benefits of this approach.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
............................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 27
Examiner Report Question 3
(a) (i) This question proved very challenging for most candidates.
Some candidates gained credit for the two parameters. Many candidates added labels to the existing
parameters, despite the question directing them otherwise.
(ii) Many correct answers were seen, suggesting that candidates were able to map the module
headers to the original diagram.
(b) Many candidates gained marks for 'easier to...' answers relating either to the problem or the
implementation of a solution. The ability to assign problems to different teams was also commonly
seen.
Many answers were vague and did not relate sufficiently to the problem or to the sub-problems.
Candidates should familiarise themselves with the meaning of the command words used in the
questions and form their answers accordingly.
A small number of candidates gave benefits of structure charts, rather than benefits of decomposition.
Use of vague terminology was commonplace, for example, 'it makes testing more convenient'.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 28
3c 9618 S22 P23
3 Four program modules are defined as follows:
Pseudocode module header
PROCEDURE Sub1_A(XT : INTEGER, PB : STRING)
FUNCTION Sub1_B(RA : INTEGER) RETURNS BOOLEAN
PROCEDURE Sub1_C(SB : INTEGER, BYREF SA : STRING)
PROCEDURE Section_1()
(a) A structure chart will be produced as part of the development process.
Describe the purpose of a structure chart.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.......................................................................................................................................[2]
(b) Module Section_1() calls one of the other three modules. The module called will be
selected when the program runs.
Draw the structure chart. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 29

Examiner Report Question 3


(a) Many fully correct answers were seen, usually quoting the relationship between modules and the
parameters that passed between them.
(b) This part was well-answered by the majority of candidates, with nearly all diagrams being
recognisable as structure charts.
Common mistakes were the omission of the decision diamond and treating the ByRef
parameter as a separate parameter plus a separate return value.
A very small number of candidates gave no answer or provided a diagram that was more akin to a
program flowchart.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 30
Test Yourself To code the ‘Search by product code’ procedure, Ahmed wants to draw a
structure chart showing the different stages. The variables used are shown in the identifier
table.
Identifier Data type Description
SearchCode STRING Product code input by the user
Details STRING Product description found

The main module has three sub modules. You can assume that before the procedure is run,
all the product data is read from file PRODUCTS.
Draw structure chart to show modular design. [4]
FUCNTION InputSearchCode( ) RETURNS STRING
FUCNTION SearchDetails(SearchCode : STRING ) RETURNS STRING
PROCEDURE OutputDetails (SearchCode: STRING, Details: STRING )

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 31
Test Yourself Summer 2019 P22
3 The following structure chart shows the relationship between three modules.

Parameters A to E have the following data types:


A, D : STRING
C : CHAR
B, E : INTEGER
(a) (i) Write the pseudocode header for module SubA(). [3]

(ii) Write the pseudocode header for module SubB(). [3]

(b) Module hierarchy and parameters are two features that may be represented on a structure
chart.
State two other features than can be represented.
Feature 1 ..................................................................................................................................
Feature 2 ................................................................................................................................ [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 32
Test Yourself 10b Winter 19 P22
5 The module headers for three modules in a program are defined in pseudocode as follows:
Pseudocode module header
PROCEDURE Lookup(P4 : INTEGER, BYREF M4 : STRING)
FUNCTION Update(T4 : INTEGER) RETURNS INTEGER
FUNCTION Validate(S2:INTEGER, P3:STRING) RETURNS BOOLEAN
A fourth module, Renew(), calls the three modules in the following sequence.
Validate()
Lookup()
Update()
Draw a structure chart to show the relationship between the four modules and the parameters
passed between them. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 33

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 34

Test Yourself Summer 2015 Paper 23


3 A flooring company provides for each customer an estimated price for a new job. Each job
is given a Job ID. The job cost is calculated from the length (nearest metre) and width
(nearest metre) of the room. The process for calculating the price is as follows:
x the floor area is calculated with 18% added to allow for wastage
x the job cost is calculated at $50 per square metre
The structure chart shows the modular design for a program to produce a new job cost.

(i) Give the data items corresponding to the labels A to E in the structure chart.
A ....................................................................... B ...........................................................
C ....................................................................... D ............................................................
E .................................................................................................................................... [5]
(ii) The procedure below is one of the modules shown on the structure chart.
Parameters can be passed ‘by value’ or ‘by reference’.
Complete the procedure header below showing for each parameter:
• its parameter passing mechanism • its identifier • its data type
PROCEDURE CalculateJobCost( ....................................................................................... )
JobCostÅ(Length * Width * 1.18) * 50
ENDPROCEDURE [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 35

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 36
Software Development Topical Past Papers from SoW
0 9618 Specimen Paper 2 - SoW
2 Roberta downloads music from an online music store. The diagram shows part of a
structure chart for the online music store program.

(a) State three items of information that the diagram shows about the design of the program.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
................................................................................................................................................ [3]
(b) Examples of the data items that correspond to the arrows are given in the table.
Arrow Data item
A 234.56
B "Ms Roberta Smith"
C TRUE
Use pseudocode to write the function header for the Card payment module.
...................................................................................................................................................
.............................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 37
9608 S16 P21-22 - SoW
4 (a) Structured programming involves the breaking down of a problem into modules.
Give two reasons why this is done.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
............................................................................................................................................. [2]
(b) A team needs to write a program to implement an online shopping system. Customers will
access the program via a website.
Customers can search for items before adding them to a virtual shopping basket. When they
have finished shopping, they pay for the items. The program provides output for the dispatch
of the items. Some of the key features of the system are as follows:
(a) a customer can add many items to the shopping basket
(b) payment may be either by credit or debit card, or by adding to a customer account
(c) the shop may dispatch the items in one or more packages
The structure chart below shows the program modules only.
(i) Draw on the chart, the symbols that represent the key features listed in part (b) above.[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 38
(ii) A section of the chart in part (b)(i) is shown below. It is to show the parameters passed
between the Checkout and Card payment modules.

Name the three data items corresponding to the arrows.


[3]
Arrow Data item
A
B
C

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 39
7a 9608/21 Jun 18 Q4b
4 (a) A structure chart is used in modular program design.
Iteration and selection are two features of an algorithm that may be shown on a structure
chart. Give three other features.
Feature 1 ..................................................................................................................................
...................................................................................................................................................
Feature 2 ..................................................................................................................................
...................................................................................................................................................
Feature 3 ..................................................................................................................................
.............................................................................................................................................. [3]
(b) Pseudocode for a function is shown.
FUNCTION ItemProcess (AddItem, InString : STRING) RETURNS BOOLEAN
DECLARE RetFlag : BOOLEAN
RetFlag Å FALSE
IF AddItem = "Yes"
THEN
RetFlag Å AddToList (InString)
ELSE
CALL RemoveFromList(InString)
ENDIF
RETURN RetFlag
ENDFUNCTION
Draw a structure chart on the next page to represent this pseudocode.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 40

Examiner Comments
(a) A minority of candidates provided correct responses for this part. It was evident from the
quality of responses that candidates were unfamiliar with a structure chart.

Candidates often stated inputs and outputs as features shown on a structure chart. These are
not a feature of a structure chart and it appeared that some candidates were mistaking a
program flowchart for a structure chart.

(b) A significant number of candidates did not attempt this question. As with the previous
question, candidates were not aware of how to draw a structure chart. The majority of
candidates who attempted this question, made an attempt to draw another program
flowchart which gained no credit. A minority of candidates were aware of the arrows used in
a structure chart to show the direction of parameters but applied them incorrectly.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 41
ͻǤʹމ‘”‹–Š

Algorithm Pseudo code

An algorithm is a series of
well-defined steps which
gives a procedure for solving
a type of problem.
The word algorithm comes
from the name of 9th
century mathematician al-
Khwarizmi (Muhammad Bin
Musa Al-Khwarizmi).
In fact, even the word
algebra is derived from his
book “Hisab al-jebrw’al-muqabala”

“An algorithm is a sequence of steps for a computer program to accomplish a


task.”
In general, an 'algorithm' is the name given to a defined set of steps used to complete a task.
For instance, you could define an algorithm to make a cup of tea. You start by filling the kettle,
and then place a tea bag in the cup and so on.
In computer terms, an algorithm describes the set of steps needed to carry out a software
task. This mini-web takes you through the topic of algorithm

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 42
10.1 Data Types Notes and guidance
Select and use appropriate data types for a problem including integer, real, char, string, Boolean,
solution date
9.2 Algorithms
Show understanding that an algorithm is a solution to a
problem expressed as a sequence of defined steps
Use suitable identifier names for the representation of data
used by a problem and represent these using an identifier
table

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 43
Variable:
Variable is memory container, where a value can be
stored. The values stored in a variable are changed
during execution.
Like in computer game you have observed Lives and
Score. At the start if game Score has a value 0, while
Lives has some values like 3. During game values stored in Score are increased with each
success and values stored in Lives decreases with failure. Here Lives and Score are
variables, storing values, which are changed during program execution.
Identifiers
Identifiers (the names given to variables, constants, procedures and functions) are in mix
case. They can only contain letters (A–Z, a–z) and digits (0–9). They must start with a letter
and not a digit. Accented letters and other characters, including the underscore, should not be
used.
As in programming, it is good practice to use identifier names that describe the variable,
procedure or function they refer to. Single letters may be used where these are conventional
(such as i and j when dealing with array indices, or X and Y when dealing with coordinates) as
these are made clear by the convention.
Keywords identified elsewhere in this guide should never be used as variables. Keywords
are written in ALL CAPS.
Identifiers should be considered case insensitive, for example, Countdown and Countdown
should not be used as separate variables.
Data types:
A data type is a classification that specifies which type of data a variable has and what type
of operations can be applied to it.
Most programming languages support various types of data, including integer, real, character
or string, and Boolean.
1. INTEGER:
A whole number (without fractional part) like COUNT which never requires fractional
part
For example, 56, 89, 1
2. REAL:
A number capable of containing a fractional part like Weight may contain fractional Part
For example, 56.8, 89.0, 1.2

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 44
CHAR:
A single character (may be letter, special character or number but number cannot be
used in calculation)
For example, ‘A’, ‘$’, ‘5’
3. STRING:
A sequence of alphanumeric and special characters but number cannot be used in
calculation
For example, “Abdullah Patel”, “0300-2724734”, “House No 56 Block 2, PECHS
Karachi”
4. BOOLEAN: A data type with two possible values
For example, TRUE and FALSE or YES or NO
5. DATE: To store a calendar date
For example, 16/04/2010
Literals
Literals of the above data types are written as follows:
Data Description Example Literals
Type
Integers: Written as normal in the denary system.
Real: Always written with at least one digit on either side of
the decimal point, zeros being added if necessary.
Char: A single character delimited by single quotes.
String: Delimited by double quotes. A string may contain no
characters (i.e. the empty string).
Boolean: Gives two possible output
Date: This will normally be written in the format dd/mm/yyyy.
However, it is good practice to state explicitly that this
value is of data type DATE and to explain the format
(as the convention for representing dates varies across
the world).

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 45
Variable declarations
It is good practice to declare variables explicitly in pseudo code.
Declarations are made as follows:
DECLARE<identifier> : <data type>
Example
DECLARE Surname : STRING
DECLARE FirstName : STRING
DECLARE DateOfBirth : DATE
DECLARE Section : CHAR
DECLARE Counter : INTEGER
DECLARE TotalToPay : REAL
DECLARE GameOver : BOOLEAN
Constant:
Constant is memory location where a value can be stored but the stored value remaining
same during execution.
It is good practice to use constants if this makes the pseudo code more readable, as an
identifier is more meaningful in many cases than a literal. It also makes the pseudo code
easier to update if the value of the constant changes.
Constant declaration
Constants are normally declared at the beginning of a piece of pseudo code (unless it is
desirable to restrict the scope of the constant).
Constants are declared by stating the identifier and the literal value in the following format:
CONSTANT<identifier> = <value> : <Data Type>
Example
CONSTANT HourlyRate = 6.50 : REAL
CONSTANT DefaultText = “N/A” : STRING

Only literals can be used as the value of a constant. A variable, another constant or an
expression must never be used.
Advantages of using Constant instead of Variable:
• One change can be reflected throughout the program
• The value of the constant cannot be accidentally changed

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 46
Assignments
Assignment is a control structure used to store value or results of an expression in a variable.
Storing values in a variable is known as assignment.
The assignment operator is ‘Å’, while ‘=’ is used to compare two values, and or variables.
Assignments should be made in the following format:
<identifier> Å <value>
<identifier> Å <expression>
Difference between Assignment and comparison
Assignment Comparison
Mark Å 75 Marks = 75
stores 75 in a variable Marks Marks == 75 (in Python)
Compares marks with 75 to check whether they are
equal or not, and returns True or False
Å is used in algorithm, while = is used in algorithm and VB.Net while
‘=’ is used in Python and VB.net == is used in Python

Example – assignments
Counter Å 0
Counter Å Counter + 1
TotalToPay Å NumberOfHours * HourlyRate

Common operations
Input and output
Values are input using the INPUT command as follows:
INPUT <identifier>
The identifier should be a variable (that may be an individual element of a data structure such
as an array, or a custom data type).
Values are output using the OUTPUT command as follows:
OUTPUT <value(s)>
Several values, separated by commas, can be output using the same command.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 47
5.2 Arithmetic operations
Standard arithmetic operator symbols are used:
Purpose Operator (Algorithm) Operator (Programming)
1 Addition
2 Subtraction
3 Multiplication
4 Division
5 Raised to the power of
Care should be taken with the division operation: the resulting value should be of data type
REAL, even if the operands are integers.
Operator Precedence: In mathematics and computer programming, the order of
operations (or operator precedence) is a collection of rules that reflect conventions about
which procedures to perform first in order to evaluate a given mathematical expression.
Should we follow BODMAS or PEMDAS?
They are basically the same

B - Brackets = P - Parentheses
O - Order = E - Exponents i.e. Powers
D - Division != M - Multiplication
M - Multiplication != D - Division
A - Addition = A - Addition
S - Subtraction = S - Subtraction
So we see the only difference is between the multiplication and division operators. Both are
acronyms designed to be easy to remember but don’t quite tell the full story. The central idea
the two acronyms try to get across is that you should do multiplication and division before
addition and subtraction.
Now there are some awkward cases like 6/2*3, 6*3/2 and 6/3/2. Neither rule works for all
these case. The real rule is that when the operations are of the same precedence, (like * and
/) you do the operations from left to right. Hence 6/2*3 = (6/2) * 3 = 3 * 3 = 9 and 6 * 3 / 2 =
(6 * 3) / 2 = 18 / 2 = 9 and 6/3/2 = (6/3)/2 = 2/2 = 1.
The same happens with + and –. So 6 – 2 – 3 = (6 – 2) – 3.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 48
Relational operations
The following symbols are used for relational operators (also known as comparison
operators):
Purpose Operator (Algorithm) Operator (Programming)
1 Greater than
2 Less than
3 Greater than or equal to
4 Less than or equal to
5 Equal to
5 Not equal to
The result of these operations is always of data type BOOLEAN.
In complex expressions it is advisable to use parentheses to make the order of operations
explicit.
Logic operators
The only logic operators (also called relational operators) used are AND, OR and NOT. The
operands and results of these operations are always of data type BOOLEAN.
In complex expressions it is advisable to use parentheses to make the order of operations
explicit.
Purpose Algorithm Programming
1 To invert the value (TRUE to FALSE or vice versa)
2 Gives TRUE only if BOTH conditions are TRUE
3 Gives TRUE if EIHER condition is TRUE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 49
String operations
Syllabus requirements The AS & A Level (9618) syllabus specifically requires candidates to
know string manipulation functions in their chosen programming language. Pseudocode string
manipulation functions will always be provided in examinations.

User-defined data types


Syllabus requirements The AS & A Level (9618) syllabus requires candidates to understand
that data structures that are not available in a particular programming language need to be
constructed from the data structures that are built-in within the language. User-defined data
types need to be defined, the syllabus requires candidates to use and define non-composite
data types such as enumerated and pointer; composite data types record, set, class/object.
Abstract Data Types (ADTs) stack, queue, linked list, dictionary and binary tree are also
defined as composite data types.
Defining user-defined data types
A composite data type is a collection of data that can consist of different data types, grouped
under one identifier. The composite type should be declared as follows:
TYPE <identifier1>
DECLARE <identifier2> : <data type>
DECLARE <identifier3> : <data type>
...
ENDTYPE
Example – declaration of composite type
This user-defined data type holds data about a student.
TYPE Student
DECLARE Surname : STRING
DECLARE FirstName : STRING
DECLARE DateOfBirth : DATE
DECLARE YearGroup : INTEGER
DECLARE FormGroup : CHAR
ENDTYPE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 50
Using user-defined data types
When a user-defined data type has been defined it can be used in the same way as any other
data type in declarations.
Variables of a user-defined data type can be assigned to each other. Individual data items are
accessed using dot notation.
Example – using user-defined data types
This pseudocode uses the user-defined type Student, Season and TAddPointer defined in the
previous section.

DECLARE Pupil1 : Student


DECLARE Pupil2 : Student
DECLARE Form : ARRAY[1:30] OF Student

Pupil1.Surname ← "Johnson"
Pupil1.Firstname ← "Leroy"
Pupil1.DateOfBirth ← 02/01/2005
Pupil1.YearGroup ← 6
Pupil1.FormGroup ← ꞌAꞌ
Pupil2 ← Pupil1
FOR Index ← 1 TO 30
Form[Index].YearGroup ← Form[Index].YearGroup + 1
NEXT INDEX


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 51
W17 P22 - 1 (a) (i) Procedural high-level languages usually support different data types.
Give an appropriate data type for each data value in the following table: [6]
Data value Data type
FALSE
03/03/2013
35
"INTEGER"
3.5
"35"
9608 P22 1 (a) A farm has a number of greenhouses used to grow vegetables. Each
greenhouse has a different identification number. A program is needed to store temperature
information for each greenhouse throughout the day. Give a suitable identifier name for each
of the data items. [4]
Description of data item Suitable identifier name
The temperature inside the greenhouse
The temperature outside the greenhouse
The greenhouse identification number
The time of the temperature measurements
9608 S18 P23 1 (a) A program controls the heating system of an energy-efficient house.
Give a suitable identifier name for each of the data items. [4]
Description of data item Suitable identifier name
The temperature inside the house
The temperature outside the house
The wind speed
Whether it was raining or not
(b) (i) Program variables have values as follows:
Variable Value
Quality 'D'
DayNumber 20
MyName "Stephen"
QualityConfirmed TRUE
Factor 6.5
(ii) Give an appropriate data type for each of these variables from part (b)(i). [5]
Variable Data type
QualityConfirmed
DayNumber
Factor
Quality
MyName

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 52
Marking Scheme
6b 9608 W17 P22 - 1 (a) (i) [6]
Data value Data type
FALSE BOOLEAN
03/03/2013 DATE / DATETIME
35 INTEGER
"INTEGER" STRING
3.5 REAL
"35" STRING
One mark for each data type
Mark first data type given in each case
7c 9608 S18 P23 1 (a) [4]
Description of data item Suitable identifier name
The temperature inside the house InsideTemperature
The temperature outside the house OutsideTemperature
The wind speed WindSpeed
Whether it was raining or not WasRaining
The above are examples only.
Names must be meaningful and unambiguous
Items 1 and 2 must have suitable prefix/suffix (i.e. not just ‘temperature’)
Reject single letter names
(b) (i) (ii)
[5]
Variable Data type
QualityConfirmed BOOLEAN
DayNumber INTEGER
Factor REAL
Quality CHAR
MyName STRING
Examiner Report
(a) The majority of candidates answered this part well, indicating a good understanding of the need for
meaningful identifier names.
Some candidates lost a mark for including spaces within the name and a few names were considered to
be too ambiguous, particularly for the final item. Simply 'Weather' was given on a few occasions but
perhaps the most noteworthy of these was 'RainingOrNot' which was suggested by a number of
candidates. Although nothing in the question explicitly implies a Boolean data type, the meaning of the
statement RainingOrNot ț TRUE is very ambiguous.
A small number of candidates gave data types instead of variable names.

(b) (i) Many candidates obtained full marks for this question. A common error was to omit the quotation
marks for the first answer required to differentiate between a string and an identifier name.
(ii) The majority of candidates answered this part well. The suggestion that variable Quality should
be a STRING rather than a CHAR was the most common mistakes. Sensible alternative types to REAL for the
Factor variable were acceptable.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 53
1ac 9618 S21 P21
1 (a) A program is being developed to help manage the membership of a football club.
Complete the following identifier table. [4]
Example Variable Data
Explanation
value name type
"Wong" The preferred name of the member joining the football club
A value to indicate whether an existing member of the club
FALSE
lives at the same address
19/02/1983 When the member joined the football club
The number of points a member has earned. Members of
1345
the club earn points for different activities.
3a 9618 S22 P21
1 (a) A programmer draws a program flowchart to show the sequence of steps required to
solve a problem. Give the technical term for a sequence of steps that describe how to solve a
problem.
............................................................................................................................................. [1]
(b) The table lists some of the variables used in a program.
(i) Complete the table by writing the most appropriate data type for each variable. [4]
Variable Use of variable Data type
Temp Stores the average temperature
PetName Stores the name of my pet
MyDOB To calculate the number of days until my next birthday
LightOn Stores state of light; light is only on or off
(ii) One of the names used for a variable in the table in part 1(b)(i) is not an example of good
practice. Identify the variable and give a reason why it is not good practice to use that name.
Variable .............................................................................................................................
Reason ..............................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 54

9608 W19 P23 –


1 (a) (ii) Identify the type of programming statement that assigns a data type to a variable.
..................................................................................................................................... [1]
9608 Summer 2015 P21, 22
Throughout the paper you will be asked to write either pseudo code or program code.
Complete the statement to indicate which high-level programming language you will use.
1 A marathon runner records their time for a race in hours, minutes and seconds.
An algorithm is shown below in structured English.
INPUT race time as hours, minutes and seconds
CALCULATE race time in seconds
STORE race time in seconds
OUTPUT race time in seconds
(a) The identifier table needs to show the variables required to write a program for this
algorithm.
Complete the table. [3]

Identifier Data type Description


RaceHours INTEGER The hours part of the race time.

(b) Before the program is written, the design is amended.


The new design includes input of the runner’s current personal best marathon time (in
seconds).
The output will now also show one of the following messages:
• “Personal best time is unchanged”
• “New personal best time”
• “Equals personal best time”
(i) Show the additional variable needed for the new design. [1]
Identifier Data type Description

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 55
9608 Summer 2015 Paper 23
1 Horses are entered for a horse race. A horse may have to carry a penalty weight in addition
to the rider. This weight is added to the saddle. The penalty weight (if any) depends on the
number of wins the horse has achieved in previous races. The penalty weight is calculated as
follows:
Number of previous wins Penalty weight (kg)
0 0
1 or 2 4
Over 2 8
A program is to be written from the following structured English design.
1 INPUT name of horse
2 INPUT number of previous wins
3 CALCULATE penalty weight
4 STORE penalty weight
5 OUTPUT name of horse, penalty weight
(a) Complete the identifier table showing the variables needed to code the program.
[3]
Identifier Data type Description

(b) Line 3 in the algorithm above does not give the detail about how the race penalty weight is
calculated; this step in the algorithm must be expressed in more detail.
(i) The algorithm above currently has five stages. One technique for program design is to
further break down, where required, any stage to a level of detail from which the program
code can be written. Name this technique.
....................................................................................................................................... [1]
(ii) Write pseudocode for the given structured English design. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 56
W18 P21 - contains statements written in pseudocode.
Give the most appropriate data type for the variable used in each statement. [5]
Statement Data type
MyAverageÅ13.5
ProjectCompletedÅTRUE
Subject Å"Home Economics"
MyMarkÅ270
MyGradeÅ'B'
W18 P22 1 (b) (i) The following table contains statements written in pseudocode. Give the
most appropriate data type for the variable used in each statement. [5]
Statement Data type
RevisionÅ 'B'
MaxValueÅ13.3
ArrayFullÅTRUE
Activity Å"Design"
NumberOfEditsÅ270
S19 P21 - 1 (b) Program variables have values as follows:
Variable Value
Title "101 tricks with spaghetti"
Version 'C'
Author "Eric Peapod"
PackSize 4
WeightEach 6.2
Paperback TRUE
(ii) Give an appropriate data type for the following variables from part (b). [5]
Variable Data type
Title
Version
PackSize
WeightEach
Paperback

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 57
S19 P22 - (b) Program variables have values as follows:
Variable Value
Married 03/04/1982
ID "M1234"
MiddleInitial 'J'
Height 5.6
IsMarried TRUE
Children 2
(ii) Give an appropriate data type for the following variables from part (b). [5]
Variable Data type
Married
ID
MiddleInitial
Height
IsMarried
W19 p21 1 (b) (i) Complete the table by giving a suitable data type for each example value.[4]
Example value Data type
"NOT TRUE"
- 4.5
NOT FALSE
132
W19 P22 1(bi) Complete the table by giving a suitable data type for each example value. [4]
Example value Data type
43
TRUE
- 273.16
"- 273.16"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 58
2ac 9618 W21 P21_23
1 Sylvia is testing a program that has been written by her colleague. Her colleague tells her
that the program does not contain any syntax errors.
(a) (i) State what her colleague means by “does not contain any syntax errors”.
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................................................ [1]
(ii) Identify and describe one other type of error that the program may contain.
Type of error ......................................................................................................................
Description ........................................................................................................................
........................................................................................................................................... [2]
(b) Complete the following table by giving the appropriate data type in each case. [4]
Use of variable Data type
The average mark in a class of 40 students
An email address
The number of students in the class
To indicate whether an email has been read

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 59
An error will be generated if a function call is not properly formed or if the parameters are of an
incorrect type or an incorrect value.

String and Character Functions

• A string of length 1 may be either of type CHAR or STRING


• A CHAR may be assigned to, or concatenated with, a STRING
• A STRING of length greater than 1 cannot be assigned to a CHAR
LEFT(ThisString : STRING, x : INTEGER) RETURNS STRING
returns leftmost x characters from ThisString
Example: LEFT("ABCDEFGH", 3) returns "ABC"

RIGHT(ThisString : STRING, x : INTEGER) RETURNS STRING


returns rightmost x characters from ThisString
Example: RIGHT("ABCDEFGH", 3) returns "FGH"

MID(ThisString : STRING, x : INTEGER, y : INTEGER) RETURNS STRING


returns a string of length y starting at position x from ThisString
Example:
MID("ABCDEFGH", 2, 3) returns string "BCD"
LENGTH(ThisString : STRING) RETURNS INTEGER
returns the integer value representing the length of ThisString
Example:
LENGTH("Happy Days") returns 10
TO_UPPER(x : <datatype>) RETURNS <datatype>
<datatype> may be CHAR or STRING
returns an object of type <datatype> formed by converting all characters of x to upper case.
Examples:
• TO_UPPER("Error 803") returns "ERROR 803"
• TO_UPPER('a') returns 'A'
TO_LOWER(x : <datatype>) RETURNS <datatype>
<datatype> may be CHAR or STRING
returns an object of type <datatype> formed by converting all characters of x to lower case.
Examples:
• TO_LOWER("JIM 803") returns "jim 803"
• TO_LOWER('W') returns 'w'
NUM_TO_STR(x : <datatype1>) RETURNS <datatype2>
returns a string representation of a numeric value.
<datatype1> may be REAL or INTEGER, <datatype2> may be CHAR or STRING
Example: NUM_TO_STR(87.5) returns "87.5"
STR_TO_NUM(x : <datatype1>) RETURNS <datatype2>
returns a numeric representation of a string.
<datatype1> may be CHAR or STRING, <datatype2> may be REAL or INTEGER
Example: STR_TO_NUM("23.45") returns 23.45

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 60
IS_NUM(ThisString : <datatype>) RETURNS BOOLEAN
returns TRUE if ThisString represents a valid numeric value.
<datatype> may be CHAR or STRING
Example: IS_NUM("-12.36") returns TRUE
ASC(ThisChar : CHAR) RETURNS INTEGER
returns an integer value (the ASCII value) of character ThisChar
Example: ASC('A') returns 65, ASC('B') returns 66, etc.

CHR(x : INTEGER) RETURNS CHAR


returns the character whose integer value (the ASCII value) is x
Example: CHR(65) returns 'A', CHR(66) returns 'B', etc.

String Operator

concatenates (joins) two strings.


& Example: "Summer" & " " & "Pudding" evaluates to "Summer Pudding"
The operator may also be used to concatenate a CHAR with a STRING

Numeric Functions
INT(x : REAL) RETURNS INTEGER
returns the integer part of x
Example: INT(27.5415) returns 27

RAND(x : INTEGER) RETURNS REAL


returns a real number in the range 0 to x (not inclusive of x).
Example: RAND(87) may return 35.43

Arithmetic Operators
An error will be generated if an operator is used with a value or values of an incorrect type.
finds the remainder when one number is divided by another.
MOD
Example: 10 MOD 3 evaluates to 1
finds the quotient when one number is divided by another.
DIV
Example 10 DIV 3 evaluates to 3

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 61
9618 Specimen Paper 1 (a) Program variables have values as follows:
Variable Value
Today "Tuesday"
WeekNumber 37
Revision 'C'
MaxWeight 60.5
LastBatch TRUE
(i) Give an appropriate data type for each variable. [5]
Variable Data type
Today
WeekNumber
Revision
MaxWeight
LastBatch

(ii) Evaluate each expression in the following table. If an expression is invalid then write
ERROR. [5]
Expression Evaluates to
MID(Today, 3, 2) & Revision & "ape"
INT(MaxWeight + 4.2)
LENGTH(MaxWeight)
MOD(WeekNumber, 12)
(Revision <= 'D') AND (NOT LastBatch)
(b) Simple algorithms usually consist of input, process and output.
Complete the table to show if each statement is an example of input, process or output.
Place one or more ticks for each statement. [4]
Item Statement Input Process Output
1 SomeChars ← "Hello World"
2 OUTPUT RIGHT(SomeChars, 5)
3 READFILE MyFile, MyChars
4 WRITEFILE MyFile, "Data is " & MyChars

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 62
Boolean Operators

performs a logical AND on two Boolean values.


AND
Example: TRUE AND FALSE evaluates to FALSE

performs a logical OR on two Boolean values.


OR
Example: TRUE OR FALSE evaluates to TRUE

performs a logical NOT on a Boolean value.


NOT
Example: NOT TRUE evaluates to FALSE

S17 P22 - 1 (b) (i) Complete the following two sentences.


A suitable operand type for an arithmetic operator is ........................................................
A suitable operand type for a logical operator is ...............................................................[2]
(ii) The following table shows the values of three variables.
Variable Value
FlagA TRUE
FlagB FALSE
FlagC TRUE
Evaluate these expressions. [3]
Expression Evaluates to
(FlagA AND FlagB) OR FlagC
FlagA AND (FlagB OR FlagC)
(NOT FlagA) OR (NOT FlagC)

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 63
Date Functions
Date format is assumed to be DD/MM/YYYY unless otherwise stated.
DAY(ThisDate : DATE) RETURNS INTEGER
returns the current day number from ThisDate
Example: DAY(04/10/2003) returns 4

MONTH(ThisDate : DATE) RETURNS INTEGER


returns the current month number from ThisDate
Example: MONTH(04/10/2003) returns 10

YEAR(ThisDate : DATE) RETURNS INTEGER


returns the current year number from ThisDate
Example: YEAR(04/10/2003) returns 2003

DAYINDEX(ThisDate : DATE) RETURNS INTEGER


returns the day index number from ThisDate where Sunday = 1, Monday = 2 etc.
Example: DAYINDEX(09/05/2023) returns 3

SETDATE(Day, Month, Year : INTEGER) RETURNS DATE


returns a value of type DATE with the value of <Day>/<Month>/<Year>
Example: SETDATE(26, 10, 2003) returns a date corresponding to
26/10/2003
TODAY() RETURNS DATE returns a value of type DATE
corresponding to the current date.

5a 9618 S23 P21


2 (b) A different part of the program uses the variable StartDate.
Write pseudocode statements to declare StartDate and assign to it the date corresponding to
15/11/2005.
Declaration ...............................................................................................................................
Assignment ............................................................................................................................. [3]

5b 9618 S23 P22


2 A program stores a user’s date of birth using a variable MyDOB of type DATE.
(a) Write a pseudocode statement, using a function from the insert, to assign the value
corresponding to 17/11/2007 to MyDOB.
............................................................................................................................................. [1]


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 64
b) MyDOB has been assigned a valid value representing the user’s date of birth.
Write a pseudocode statement to calculate the number of months from the month of the user’s birth
until the end of the year and to assign this to the variable NumMonths.
For example, if MyDOB contains a value representing 02/07/2008, the value 5 would be assigned to
NumMonths.
............................................................................................................................................. [2]
5c 9618 S23 P23
2 A program stores a date of birth for a student using a variable, MyDOB, of type DATE.
(a) MyDOB has been assigned a valid value corresponding to Kevin’s date of birth.
Complete the pseudocode statement to test whether Kevin was born on a Thursday.
IF ........................................................................................................................ THEN [2]
(b) A function CheckDate()will take three integer parameters representing a day, month and year
of a given date.
The function will validate the date of birth for a student that the parameters passed to it represent.
For a date to be valid, a student must be at least 18 in year 2020.
(i) Two of the parameter values can be checked without reference to the third parameter.
Describe these two checks.
Check 1 ......................................................................................................................................................
....................................................................................................................................................................
...................................................................................................................................................................
Check 2 ....................................................................................................................................................
....................................................................................................................................................................
....................................................................................................................................................................
.......................................................................................................................................................... [2]
(ii) Several values of the parameter representing the day can only be checked completely by referring
to the value of one other parameter. Describe this check.
....................................................................................................................................................................
....................................................................................................................................................................
....................................................................................................................................................................
........................................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 65
1ac 9618 S21 P21
1 (b) Each pseudocode statement in the following table may contain an error due to the
incorrect use of the function or operator.
Describe the error in each case, or write ‘NO ERROR’ if the statement contains no error.
You can assume that none of the variables referenced are of an incorrect type. [5]
Statement Error
Result Å 2 & 4
SubStringÅ MID("pseudocode", 4, 1)
IF x = 3 OR 4 THEN
Result Å Status AND INT(x/2)
Message Å "Done" + LENGTH(MyString)

1b 9618 S21 P22 -


1 (a) (i) Complete the following table by giving the appropriate data type in each case. [4]
Variable Example data value Data type
Name "Catherine"
Index 100
Modified FALSE
Holiday 25/12/2020
(ii) Evaluate each expression in the following table by using the initial data values shown in
part (a)(i). [4]
Expression Evaluates to
Modified OR Index > 100
LENGTH("Student: " & Name)
INT(Index + 2.9)
MID(Name, 1, 3)
(b) Each pseudocode statement in the following table contains an example of selection,
assignment or iteration. Put one tick (‘‫ )’ض‬in the appropriate column for each statement. [3]
Statement Selection Assignment Iteration
Index Å Index + 1
IF Modified = TRUE THEN
ENDWHILE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 66
2b 96 W21 P22
1 (c) Complete the pseudocode expressions so that they evaluate to the values shown. [4]
Any functions and operators used must be defined in the insert.
Expression Evaluates to

67
..................... ('C')

54
2 * ....................... ("27")

13
................... (27 / ..............)

"Subtract"
"Sub" & ........ ("Abstraction" , .......... ,.........)

(d) Evaluate the expressions given in the following table. The variables have been assigned
values as follows: [2]
PumpOn ← TRUE
PressureOK ← TRUE
HiFlow ← FALSE
Expression Evaluates to
PressureOK AND HiFlow
PumpOn OR PressureOK
NOT PumpOn OR (PressureOK AND NOT HiFlow)
NOT (PumpOn OR PressureOK) AND NOT HiFlow

3a 9618 S22 P21


1 (c) Complete the table by evaluating each expression. [4]
Expression Evaluation
INT((31 / 3) + 1)
MID(TO_UPPER("Version"), 4, 2)
TRUE AND (NOT FALSE)
NUM_TO_STR(27 MOD 3)

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 67
3b 9618 s22p22
1 (d) The pseudocode statements in the following table may contain errors.
State the error in each case or write 'NO ERROR' if the statement contains no error.
You can assume that none of the variables referenced are of an incorrect type. [4]
Statement Error
Status Å TRUE AND FALSE
IF LENGTH("Password") < "10" THEN
Code Å LCASE("Electrical")
Result Å IS_NUM(-27.3)
3c 9618 S22 P23
1(b) (i) Program variables have values as follows:
Variable Value
AAA TRUE
BBB FALSE
Count 99
Complete the table by evaluating each expression. [2]
Expression Evaluation
AAA AND (Count > 99)
AAA AND (NOT BBB)
(Count <= 99) AND (AAA OR BBB)
(BBB AND Count > 50) OR NOT AAA
(ii) Give an example of when a variable of type Boolean would be used.
.....................................................................................................................................................
........................................................................................................................... [1]
4a 9618 W22 P21 - 1 (a) An algorithm includes a number of complex calculations. A programmer is writing a
program to implement the algorithm and decides to use library routines to provide part of the solution.
State three possible benefits of using library routines in the development of the program.
1 ......................................................................................................................................................................
...................................................................................................................................................................................
2 ......................................................................................................................................................................
...................................................................................................................................................................................
3 ......................................................................................................................................................................
.......................................................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 68
(c) The pseudocode statements in the following table may contain errors.
State the error in each case or write ‘NO ERROR’ if the statement contains no error.
Assume that any variables used are of the correct type for the given function. [4]
Statement Error
IF EMPTY ← "" THEN
Status ← IS_NUM(-23.4)
X ← STR_TO_NUM("37") + 5
Y ← STR_TO_NUM("37" + "5")

4b 9618 W22 P22- 1 (c) Part of an identifier table is shown: [3]

Variable Type Example value

FlagDay DATE 23/04/2004

CharList STRING "ABCDEF"

Count INTEGER 29
Complete the table by evaluating each expression using the example values.

Expression Evaluation

MID(CharList, MONTH(FlagDay), 1)

INT(Count / LENGTH(CharList))

(Count >= 29) AND (DAY(FlagDay) > 23)


5a 9618 S23 P21
1 (b) The algorithm for function Calculate() contains the three pseudocode statements shown.
Describe the error in each statement or write ‘no error’ if the statement contains no error.
Assume any variables used are of the correct type for the given function.
Statement 1: Index STR_TO_NUM(("27") + 2)
Error ..........................................................................................................................................
..................................................................................................................................................................
Statement 2: Index STR_TO_NUM(MID("CPE1704TKS", 4, 2))
Error ..........................................................................................................................................
..................................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 69
Statement 3: IF MONTH(ThisDate) > '6' THEN
Error ..........................................................................................................................................
............................................................................................................................................................ [3]
(c) The program contains variables with values as follows:
Variable Value
Active TRUE
Points 75
Exempt FALSE

(i) Complete the table by evaluating each expression. [2]


Expression Evaluation
1 (Points > 99) OR Active
2 (Points MOD 2 = 0) OR Exempt

3 (Points <= 75) AND (Active OR Exempt)

4 (Active OR NOT Active) AND NOT Exempt

(ii) Write expression 4 from the table in part (c)(i) in its simplest form.
…………… ..................................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 70
2 (a) Two operators available in a programming language are DIV and MOD. They perform
integer arithmetic as follows:
Expression Explanation
X DIV Y Computes the number of times Y divides into X
X MOD Y Computes the remainder when X is divided by Y
Calculate the value of the variables shown for the following code fragments. [3]
Code Variable
NumberLeftOverÅ37 MOD 10 NumberLeftOver ..................
QuantityÅ 208
BoxSizeÅ100 NumberOfBoxes ....................
NumberOfBoxesÅ Quantity DIV BoxSize Temp .......................................
Temp Å(Quantity MOD BoxSize) + 1

(b) Bank customers withdraw money from their account at a cash dispenser machine using
their bank card. The machine operates as follows:
• it can dispense the following notes:
o $50
o $20
o $10
• the maximum amount for a single withdrawal is $500
When a customer withdraws money, they enter the amount to withdraw. (This must be a
multiple of $10).The machine will always dispense the least possible number of notes.
A program is designed for the machine to process a withdrawal.
The following variables are used:
Identifier Data type Description
Amount INTEGER Amount to withdraw entered by the user
FiftyDollar INTEGER Number of $50 notes to dispense
TwentyDollar INTEGER Number of $20 notes to dispense
TenDollar INTEGER Number of $10 notes to dispense
Temp INTEGER Used in the calculation of the number of each note required

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 71
(i) The following four tests have been designed.
Complete the test data table showing the expected results with comments.
[3]
Input value Output
Comment
Amount FiftyDollar TwentyDollar TenDollar
70 1 1 0 Least possible number of notes
85
130
600

(ii) Complete the pseudocode.


INPUT ...................................................
IF Amount > 500
THEN
OUTPUT "Refused – amount too large"
ELSE
................................................
THEN
OUTPUT "Refused - not a multiple of $10"
ELSE
FiftyDollarÅ Amount DIV 50
Temp Å .....................................
TwentyDollarÅ ...............................
Temp Å ......................................
.............................................
ENDIF
ENDIF [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 72
9608 Winter 2015 P22
1 Computer programs have to evaluate expressions.
Study the sequence of pseudocode statements.
Give the value assigned to each variable.
The statement may generate an error. If so, write ERROR.
The & operator is used to concatenate strings.
DECLARE N1: INTEGER
DECLARE N2: INTEGER
DECLARE Answer: REAL
DECLARE Found: BOOLEAN
DECLARE IsValid: BOOLEAN
N1 ← 3
N2 ← 9
(i) Answer ← (N1 + N2) / 6
(ii) Answer ← 3 * (N1 – 2) + N2 / 2
(iii) IsValid← (N1 > N2) AND (N2 = 9)
Found ← FALSE
(iv) IsValid← (N1 > N2 / 2) OR (Found = FALSE)
(v) Answer ← "1034" & " + " & "65"

(i) Answer .............................................................................................................................. [1]


(ii) Answer .............................................................................................................................. [1]
(iii) IsValid........................................................................................................................... [1]
(iv) IsValid........................................................................................................................... [1]
(v) Answer .............................................................................................................................. [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 73
2 A program is to simulate the operation of a particular type of logic gate.
• The gate has two inputs (0 or 1) which are entered by the user.
• The program will display the output (0 or 1) from the gate.
The program uses the following identifiers in the pseudocode below:
Identifier Data type Description
P INTEGER Input signal
Q INTEGER Input signal
X INTEGER Output signal
01 INPUT P
02 INPUT Q
03 IF (P = 1 AND Q = 0) OR (P = 0 AND Q = 1) OR (P = 0 AND Q = 0)
04 THEN
05 X ← 0
06 ELSE
07 X ← 1
08 ENDIF
09 OUTPUT X
(a) The programmer chooses the following four test cases.
Show the output (X) for each test case. [4]
Input Output
Test case
P Q X
1 1 1
2 1 0
3 0 1
4 0 0
(b) The selection statement (lines 03 – 08) could have been written with more simplified logic.
Rewrite this section of the algorithm in pseudocode.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...............................................................................................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 74
9608 Winter 2016 Paper 21
5 Study the following pseudocode statements.
CONST Pi = 3.1 : REAL
DECLARE Triangle, Base, Height, Radius, Cone : REAL
DECLARE a, b, c, Answer2 : INTEGER
DECLARE Answer1 : BOOLEAN
Base Å2.6
Height Å10
TriangleÅ (Base * Height) / 2
Radius Å1
Height Å2
Cone Å2 * Pi * Radius * (Radius + Height)
a Å13
b Å7
c Å3
Answer1Å NOT((a + b + c) > 28)
Total Å34
Total ÅTotal - 2
Answer2Å a + c * c
Give the final value assigned to each variable.
(i) Triangle ................................... [1]
(ii) Cone ................................... [1]
(iii) Answer1 ................................... [1]
(iv) Total ................................... [1]
(v) Answer2 ................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 75
9608 Summer 2016 P21-22
2 A team is designing a software system to monitor temperature in a process. To do this, the
system
needs to sample the temperature repeatedly. If the temperature exceeds a given threshold
value, an alarm will sound.
The system is to be software-based. It will include a subroutine, SampleTemp, which samples
the temperature and sets the alarm state to either ON or OFF.
The initial design stage will produce a prototype of SampleTemp with a user interface.
The structured English for this is:
1. IF the temperature does not exceed threshold value, SET alarm state to
OFF
2. INPUT threshold value (to two decimal places)
3. INPUT sensor value (a whole number in the range 0 to 100)
4. MULTIPLY sensor value by conversion factor 1.135 to give temperature
5. IF temperature exceeds threshold value SET alarm state to ON
6. IF temperature exceeds threshold value OUTPUT message “Temperature
Alarm”
7. IF temperature does not exceed threshold value OUTPUT message
“Temperature OK”
(a) The procedure needs four variables. Complete the identifier table below for these
variables. [4]
Identifier Data type Description
AlarmState
SensorValue
ThresholdValue
Temperature

(b) Write the pseudocode equivalent of the structured English. Use the identifiers from the
table in part (a). [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 76
9608 Winter 2016 P22
6 Study the sequence of pseudocode statements.
CONST a = 3.2 : REAL
DECLARE x, y, z, Answer1, Answer2, Answer3 : REAL
DECLARE p, q : BOOLEAN
x Å3
x Åx + 7
y Å6
Answer1 Å2 * (a + y)
z Å6
Answer2Å y ^ 2 + 5
p ÅTRUE
q ÅNOT(NOT(p))
Answer3Å y + a * 2
Give the final value assigned to each variable.
(i) x .............................................
(ii) Answer1 .............................................
(iii) Answer2 .............................................
(iv) q .............................................
(v) Answer3 ............................................. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 77
1 Programming
ͳͳǤʹ‘–”‘Ž‘•–”— –ǣ‡“—‡ ‡
The concept of a program
A program is a sequence of instructions or programming language statements written to make
a computer perform certain tasks.
Control Construct 1: Sequence:
Sequencing allows a programmer to solve complex tasks through a number of simple steps.
The order of steps in most tasks matters – similarly, we use brackets in maths to make sure
that certain operations are done before others (sometimes we need to add before we do
multiplication and division).
In following example statement number ‘i’ will be executed at 1st and then ‘ii’ then ‘iii’ and at
last statement number ‘iv’ will be executed:
i. INPUT Num1
ii. INPUT Num2
iii. Total Å Num1 + Num2
iv. PRINT Total
Problem 1: Input two numbers and output their sum

Problem 2: Input daily wages and number of day worked and output monthly pay.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 78
Activity

01 OUTPUT (“Enter the first number”)

02 INPUT Num1

03 OUTPUT (“Enter the second number”)

04 INPUT Num2

05 Result = Num1 - Num2

06 OUPUT (Result)

Discuss in groups and answer

Would this work if we swapped INPUT and OUTPUT statements in Line 01 and Line 02?

Would this work if we swapped Num1 with Num2?

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 79
ͳͳǤʹ‘–”‘Ž‘•–”— –ǣ‡Ž‡ –‹‘
Selection is testing a condition to determine the path of program execution.
Why use selection?
The use of selection allows a computer to ‘think’ – make decisions.
Selection changes the flow of a program, depending on a set of conditions, it is used for
validation, calculation and making sense of a user’s choices.
Selection decides which statement(s) are to be executed depending upon the result of a given
condition.
IF statements
IF statements may or may not have an ELSE clause.
IF statements without an else clause are written as follows:
IF <condition>
THEN
<statement(s)>
ENDIF
IF statements with an else clause are written as follows:
IF <condition>
THEN
<statement(s)>
ELSE
<statement(s)>
ENDIF
Note, due to space constraints, the THEN and ELSE clauses may only be indented by two
spaces rather than three. (They are, in a sense, a continuation of the IF statement rather than
separate statements).
When IF statements are nested, the nesting should continue the indentation of two spaces. In
particular, run-on THEN IF and ELSE IF lines should be avoided.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 80
Example – nested IF statements
IF ChallengerScore > ChampionScore
THEN
IF ChallengerScore > HighestScore
THEN
OUTPUT ChallengerName, " is champion and highest scorer"
ELSE
OUTPUT Player1Name, " is the new champion"
ENDIF
ELSE
OUTPUT ChampionName, " is still the champion"
IF ChampionScore > HighestScore
THEN
OUTPUT ChampionName, " is also the highest scorer"
ENDIF
ENDIF
CASE statements
CASE statements allow one out of several branches of code to be executed, depending on
the value of a variable.
CASE statements are written as follows:
CASE OF <identifier>
<value 1> : <statement1>
<statement2>
...
<value 2> : <statement1>
<statement2>
...
...
ENDCASE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 81
An OTHERWISE clause can be the last case:
CASE OF <identifier>
<value 1> : <statement1>
<statement2>
...
<value 2> : <statement1>
<statement2>
...
OTHERWISE : <statement1>
<statement2>
ENDCASE
Each value may be represented by a range, for example:
<value1> TO <value2> : <statement1>
<statement2>
...
Note that the case clauses are tested in sequence. When a case that applies is found, its
statement is executed and the CASE statement is complete. Control is passed to the
statement after the ENDCASE. Any remaining cases are not tested. If present, an
OTHERWISE clause must be the last case. Its statement will be executed if none of the
preceding cases apply.

Example – formatted CASE statement


INPUT Move
CASE OF Move
ꞌWꞌ : Position ← Position – 10
ꞌSꞌ : Position ← Position + 10
ꞌAꞌ : Position ← Position – 1
ꞌDꞌ : Position ← Position + 1
OTHERWISE : CALL Beep
ENDCASE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 82
2ac 9618 W21 P21 23
6 (b) Study the following pseudocode.
CASE OF MySwitch
1: ThisChar Å ‘a’
2: ThisChar Å’y’
3: ThisChar Å ‘7’
OTHERWISE: ThisChar Å ‘*’
ENDCASE
Write pseudocode with the same functionality without using a CASE structure.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 83
Problem 3: Input marks and output Result, the passing marks is 40 or above.

HW Write algorithm using pseudo code for the following problems:


Problem 4: Input total weight of passengers in a lift output "Overloaded, step out" if Total Weight is ab
ove 600 otherwise output "Ready to go".

Problem 5: Input age of candidates for driving license, output "Not allowed to drive" or "Kindly fill in the form".
The minimum allowed age for driving is 18 years.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 84
Problem 6: Input age of candidate in an employment center, output "You are not eligible due to age".
Allowed age is between 18 and 60 both inclusive.

Problem 7: which inputs price and quantity calculates amount and if billing amount is above 5000 then
allows a 5% discount on the billing amount.
Output billing amount, discount and amount after discount

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 85
9608 ON20 P22 - 2 (a) The following pseudocode is an attempt to define an algorithm that takes two
numbers as input and outputs the larger of the two numbers.
DECLARE A, B : INTEGER
INPUT A
INPUT B
IF A > B
THEN
OUTPUT A
ELSE
OUTPUT B
ENDIF
The algorithm needs to be amended to include the following changes:
1. Input three values, ensuring that each value input is unique.
2. Output the average.
3. Output the largest value.
Write the pseudocode for the amended algorithm.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
............................................................................................................................................................ [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 86
Exercise on Selection

Q1a) Using pseudo code or otherwise, write an algorithm which will input any three numbers and then
print the smallest number.

b) Write an algorithm to input three different numbers, and then output the largest number.
Use either pseudo code or a flowchart.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 87
Q 2) Write an algorithm, using pseudo code, to input three different numbers, multiply the two larger
numbers together and output the result. Use the variables: Number1, Number2 andNumber3 for your
numbers and Answer for your result.

Q 4) Write an algorithm, using pseudo code, to input a number between 0 and 100 inclusive. The algorithm
should prompt for the input and output an error message if the number is outside this range.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 88
Q 8) Input price and quantity, calculates amount and if billing amount is above 5000 then allows a 5%
discount on the billing amount.
Output billing amount, discount and amount after discount

Q 9) Employees of a shop are entitled to a discount of 10% on the value of goods bought from the
shop. However, if an employee has worked at the shop for five or more years they are entitled to a
discount of 20%. Only employees are allowed discounts. The discount on electrical goods is fixed at
only 10%.
Using pseudo code or otherwise, write an algorithm which will determine what discount applies when
any person buys an item.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 89
Q 10) Customers can withdraw cash from an Automatic Teller Machine (ATM).
• withdrawal is refused if amount entered > current balance
• withdrawal is refused if amount entered > daily limit
• if current balance < $100, then a charge of 2% is made
• if current balance $100, no charge is made
Write an algorithm which inputs a request for a sum of money, decides if a withdrawal can
be made and calculates any charges. Appropriate output messages should be included.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 90
Q 11) A formula for calculating the body mass index (BMI) is:

Using Flowchart, write an algorithm that will input weight (kg) and height (m) of students, calculate
their body mass index (BMI) and output their BMI and comments on BMI.
BMI <19 Under weight
BMI < =25 Normal Weight
BMI>25 Over weight

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 91
Q12) A system uses 5 digit numbers with an additional sixth digit used as a check digit.
(b) Each of the six digits in the number has a digit position. [Total=6]
6 5 4 3 2 1 ÅDigit position

a b c d e f

Check
digit
digit in position 1 is the check digit i.e. f
The validity of the check digit is found using the following calculation:
• multiply each digit by its digit position (i.e. ax6, bx5, so on)
• add together the results of the multiplications
• divide the sum by 11
• If the remainder is ZERO then the number is valid
Write an algorithm, which
• inputs six-digit barcodes in the form a, b, c, d, e and f
• Checks whether numbers are entered correctly or not and give an appropriate output.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 92
Q 13) Summer 2013
A small shop uses barcodes which represent 5 digits. The last digit is used as a check digit.
For example:
abcde
01234
The check digit (e) is found by:
• multiplying the first and third digits (i.e. a and c) by 3
• multiplying the second and fourth digits (i.e. b and d) by 2
• adding these four results together to give a total
• dividing this total by 10
• remainder is check digit (e)
Write an algorithm, which
¾ inputs five-digit barcodes in the form a, b, c, d, e
¾ re-calculates the check digit for each number and checks whether the input check digit (e) is co
rrect

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 93
Summer 2015 Paper 23
1 Horses are entered for a horse race. A horse may have to carry a penalty weight in addition
to the rider. This weight is added to the saddle. The penalty weight (if any) depends on the
number of wins the horse has achieved in previous races. The penalty weight is calculated as
follows:
Number of previous wins Penalty weight (kg)
0 0
1 or 2 4
Over 2 8
A program is to be written from the following structured English design.
1 INPUT name of horse
2 INPUT number of previous wins
3 CALCULATE penalty weight
4 STORE penalty weight
5 OUTPUT name of horse, penalty weight
(a) Complete the identifier table showing the variables needed to code the program. [3]
Identifier Data type Description

(b) Line 3 in the algorithm above does not give the detail about how the race penalty weight is
calculated; this step in the algorithm must be expressed in more detail.
(i) The algorithm above currently has five stages. One technique for program design is to
further break down, where required, any stage to a level of detail from which the program
code can be written. Name this technique.
....................................................................................................................................... [1]
(ii) Write pseudocode for the given structured English design. [5]
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.......................................................................................................................................[5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 94
2 (a) Two operators available in a programming language are DIV and MOD. They perform
integer arithmetic as follows:
Expression Explanation
X DIV Y Computes the number of times Y divides into X
X MOD Y Computes the remainder when X is divided by Y
Calculate the value of the variables shown for the following code fragments. [3]
Code Variable
NumberLeftOverÅ37 MOD 10 NumberLeftOver ..................
QuantityÅ 208
BoxSizeÅ100 NumberOfBoxes ....................
NumberOfBoxesÅ Quantity DIV BoxSize Temp .......................................
Temp Å(Quantity MOD BoxSize) + 1

(b) Bank customers withdraw money from their account at a cash dispenser machine using
their bank card. The machine operates as follows:
• it can dispense the following notes:
o $50
o $20
o $10
• the maximum amount for a single withdrawal is $500
When a customer withdraws money, they enter the amount to withdraw. (This must be a
multiple of $10).The machine will always dispense the least possible number of notes.
A program is designed for the machine to process a withdrawal.
The following variables are used:
Identifier Data type Description
Amount INTEGER Amount to withdraw entered by the user
FiftyDollar INTEGER Number of $50 notes to dispense
TwentyDollar INTEGER Number of $20 notes to dispense
TenDollar INTEGER Number of $10 notes to dispense
Temp INTEGER Used in the calculation of the number of each note required

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 95
(i) The following four tests have been designed.
Complete the test data table showing the expected results with comments. [3]
Input value Output
Comment
Amount FiftyDollar TwentyDollar TenDollar
70 1 1 0 Least possible number of notes
85
130
600

(ii) Complete the pseudocode.


INPUT
..................................................................................................................................
IF Amount > 500
THEN
OUTPUT "Refused – amount too large"
ELSE
.........................................................................................................................
THEN
OUTPUT "Refused - not a multiple of $10"
ELSE
FiftyDollarÅ Amount DIV 50
Temp Å
.............................................................................................
TwentyDollarÅ ..............................................................................
Temp Å
................................................................................................
..........................................................................................................
.......
ENDIF
ENDIF [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 96
9608 Winter 2015 P22
3 Regular customers at a supermarket use a rewards card at the point-of-sale.
Points are calculated from every transaction and added to the points total stored on the card.
One reward point is given for every $1 spent.
When the points total exceeds 500, the customer can either:
• pay the full amount due and increase their points total
• get $1 deducted from the amount due in exchange for 500 reward points
The new points total and amount to be paid is printed on the receipt.
A program is to be written with the following specification:
• read the points total from the card
• process the amount spent
• output the amount to be paid and the new points total
A user-defined function CalculatePointshas already been coded to calculate the new points
earned from the amount spent.
Study the following pseudocode:
INPUT AmountDue
NewPoints← CalculatePoints(AmountDue)
PointsTotal← PointsTotal + NewPoints
IF PointsTotal> 500
THEN
OUTPUT "Exchange points?"
INPUT Response
IF Response = "YES"
THEN
PointsTotal← PointsTotal – 500
AmountDue← AmountDue – 1
ENDIF
ENDIF
OUTPUT AmountDue, PointsTotal
The algorithm is also to be documented with a program flowchart.
Complete the flowchart by:
• filling in the flowchart boxes
• labelling, where appropriate, lines of the flowchart

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 97

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 98
Q 9) Winter 2015 P22
2 A program is to simulate the operation of a particular type of logic gate.
• The gate has two inputs (0 or 1) which are entered by the user.
• The program will display the output (0 or 1) from the gate.
The program uses the following identifiers in the pseudocode below:
Identifier Data type Description
P INTEGER Input signal
Q INTEGER Input signal
X INTEGER Output signal
01 INPUT P
02 INPUT Q
03 IF (P = 1 AND Q = 0) OR (P = 0 AND Q = 1) OR (P = 0 AND Q = 0)
04 THEN
05 X←0
06 ELSE
07 X←1
08 ENDIF
09 OUTPUT X
(a) The programmer chooses the following four test cases.
Show the output (X) for each test case. [4]
Input Output
Test case
P Q X
1 1 1
2 1 0
3 0 1
4 0 0

(b) The selection statement (lines 03 – 08) could have been written with more simplified logic.
Rewrite this section of the algorithm in pseudocode.
.....................................................................................................................................................
..............................................................................................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 99
Q10) This pseudo code algorithm inputs two non-zero numbers and a sign, and then performs the
calculation shown by the sign. An input of zero for the first number terminates the process.

(a) Complete the trace table for the input data:


5, 7, +, 6, 2, –, 4, 3, *, 7, 8, ?, 0, 0, / [3]

Number1 Number2 Sign Answer OUTPUT

(b) Show how you could improve the algorithm written in pseudo code by writing an alternative type of
conditional statement in pseudo code. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 100
Q 11 9608 Summer 20 P21
2 The following pseudocode algorithm has been developed to check whether a string contains a valid password.
To be a valid password, a string must:
• be longer than 6 characters • contain at least one lower case letter
• contain at least one upper case letter • contain at least one non-alphabetic character.
10 FUNCTION Check(InString : STRING) RETURNS BOOLEAN
11
12 DECLARE Index : INTEGER
13 DECLARE StrLen : INTEGER
14 DECLARE NumUpper, NumLower : INTEGER
15 DECLARE NumNonAlpha : INTEGER
16 DECLARE NextChar : CHAR
18 NumUpper ← 0
19 NumLower ← 0
20 NumNonAlpha ← 0
22 StrLen ← LENGTH(InString)
23 IF StrLen < 7
24 THEN
25 RETURN FALSE
26 ELSE
27 FOR Index← 1 TO StrLen
28 NextChar ← MID(InString, Index, 1)
29 IF NextChar >= 'a' AND NextChar <= 'z'
30 THEN
31 NumLower ← NumLower + 1
32 ELSE
33 IF NextChar >= 'A' AND NextChar <= 'Z'
34 THEN
35 NumUpper ← NumUpper + 1
36 ELSE
37 NumNonAlpha ← NumNonAlpha + 1
38 ENDIF
39 ENDIF
40 NEXT Index
41 ENDIF
43 IF (NumUpper >= 1) AND (NumLower >= 1) AND (NumNonAlpha >= 1)
44 THEN
45 RETURN TRUE
46 ELSE
47 RETURN FALSE
48 ENDIF50 ENDFUNCTION
Rewrite lines 29 to 39 of the original pseudocode using a CASE structure. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 101
Q12 The following pseudocode algorithm uses nested IF statements.
IF Response = 1 THEN
XÅX+Y
ELSE
IF Response = 2 THEN
XÅ X-Y
ELSE
IF Response =3 THEN
XÅ X * Y
IF Response = 4 THEN
X Å X/Y
ELSE
OUTPUT "No response"
ENDIF
ENDIF
ENDIF
ENDIF
(a) Name the type of statement demonstrated by the use of IF … THEN … ELSE … ENDIF
...................................................................................................................................................................
............................................................................................................................................................. [1]
(b) Re-write the pseudo code algorithm using a CASE statement.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 102
Q13 Summer 2019 P21
2 (b) Chris is asked to work on a program that has been coded in a language he is not
familiar with.
He has identified that the program contains the constructs: sequence, iteration and selection.
Identify three other features of the program that he should expect to recognise.
Feature 1 ..................................................................................................................................
Feature 2 ..................................................................................................................................
Feature 3 ................................................................................................................................[3]
(c) The following lines of code are taken from a program in a high-level language.
ON x {
15: Call ProcA
20: y := 0
25: y := 99
NONE: Call ProcError
}
Identify the type of control structure and describe the function of the code.
Control structure .......................................................................................................................
Description ................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 103
ͳͳǤʹ‘–”‘Ž‘•–”— –ǣ‘‘’
Iteration is used to execute a set of instructions multiple times. It is also referred as LOOP or ITERATI
ON.
In the following example statement number ‘ii’ will be executed 10 times:
Problem: Print the name of Allah 10 times.

LOOPING STATEMENTS:
1. FOR … TO…NEXT: Count Controlled loop
2. REPEAT … UNTIL : Post Condition loop
3. WHILE…DO…ENDWHILE: Pre-Condition Loop
Count-controlled (FOR) loops
FOR…TO…NEXT is a count-controlled loop that is executed a set number of time.
It is written as follows:
FOR <identifier> ← <value1> TO <value2>
<statement(s)>
NEXT <identifier>
The identifier must be a variable of data type INTEGER, and the values should be
expressions that evaluate to integers.
The variable is assigned each of the integer values from value1 to value2 inclusive, running
the statements inside the FOR loop after each assignment. If value1 = value2 the statements
will be executed once, and if value1 > value2 the statements will not be executed.
It is good practice to repeat the identifier after NEXT, particularly with nested FOR loops. An
increment can be specified as follows:
FOR <identifier> ← <value1> TO <value2> STEP <increment>
<statement(s)>
NEXT <identifier>
The increment must be an expression that evaluates to an integer. In this case the identifier w
ill be assigned the values from value1 in successive increments of increment until it reaches v
alue2. If it goes past value2, the loop terminates. The increment can be negative.
Example – nested FOR loops
Total ← 0
FOR Row ← 1 TO MaxRow
RowTotal ← 0
FOR Column ← 1 TO 10
RowTotal ← RowTotal + Amount[Row, Column]
NEXT Column
OUTPUT "Total for Row ", Row, " is ", RowTotal
Total ← Total + RowTotal
NEXT Row
OUTPUT "The grand total is ", Total

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 104
Post-condition (REPEAT) loops
Post-condition loops are written as follows:
REPEAT
<Statement(s)>
UNTIL <condition>
The condition must be an expression that evaluates to a Boolean.
The statements in the loop will be executed at least once. The condition is tested after the stat
ements are executed and if it evaluates to TRUE the loop terminates, otherwise the statement
s are executed again.
Example – REPEAT UNTIL statement
REPEAT
OUTPUT "Please enter the password"
INPUT Password
UNTIL Password = "Secret"
Pre-condition (WHILE) loops
WHILE is a pre-condition loop, that executes a block of statements repeatedly until given
condition is True. It is written as follows:
WHILE <condition>
<statement(s)>
ENDWHILE
The condition must be an expression that evaluates to a Boolean.
The condition is tested before the statements, and the statements will only be executed if the
condition evaluates to TRUE. After the statements have been executed the condition is tested
again. The loop terminates when the condition evaluates to FALSE.
The statements will not be executed if, on the first test, the condition evaluates to FALSE.

Example – WHILE loop


WHILE Number > 9
Number ← Number – 9
ENDWHILE

Problem 1: Input daily wages and number of day worked and output monthly pay for 100
employees.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 105
Problem 2: Input marks of a student in a class output result. Passing marks is 40

Problem: Input marks of 30 students in a class output result of each student. Passing marks is 40

Problem: Print name of Allah 10 times

Flowchart of pre-condition and post condition loops


Problem: Print name of Allah 10 times using all types of loops

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 106
Pre-Condition Loop:
When condition to continue the loop is given
Æ
Æ
Æ

problem: To input and add a series of positive numbers in total. Continue this process for
input of positive numbers
WHILE

Problem: Input a number, calculate and


output sum of digits.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 107
Post-Condition
When condition is given at the end of loop
Æ
Æ
Æ
Problem: Input a series of numbers, calculate their total, stop input if total is more than 100
REPEAT … UNTIL Loop

Differences between
Pre-Condition Post Condition

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 108
3c 9618 S22 P23
1 (a) The following table contains pseudocode examples.
Each example may include all or part of:
• selection
• iteration (repetition)
• assignment.
Complete the table by placing one or more ticks (‫ )ض‬in each row. [5]
Pseudocode example Selection Iteration Assignment
FOR Index Å 1 TO 3
Safe[Index] Å GetResult()
NEXT Index
OTHERWISE : OUTPUT "ERROR 1202"
REPEAT UNTIL Index = 27
INPUT MyName
IF Mark > 74 THEN
Grade Å 'A'
ENDIF

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 109
9618 Paper
(c) Write in pseudocode a post-condition loop to output all the odd numbers between 100
and 200.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [4]

1a 9618 S21 P21


(c) A program will:
• input 50 unique integer values
• output the largest value
• output the average of the values excluding the largest value.
Draw a program flowchart to represent the algorithm. Variable declarations are not required.
It is not necessary to check that each input value is unique. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 110

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 111
Summer 21 P22
4 A teacher uses a paper-based system to store marks for a class test. The teacher requires
a program to assign grades based on these results.
The program will output the grades together with the average mark.
Write a detailed description of the algorithm that will be needed.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.......................................................................................................................................... [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 112
Winter 21 P22
2 (a) An algorithm will:
1. input an integer value
2. jump to step 6 if the value is zero
3. sum and count the positive values
4. sum and count the negative values
5. repeat from step 1
6. output the two sum values and the two count values.
Draw a program flowchart on the following page to represent the algorithm.
Note that variable declarations are not required in program flowcharts. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 113

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 114
9618 P22 4 The following is a procedure design in pseudocode.
Line numbers are given for reference only.
10 PROCEDURE Check(InString : STRING)
11 DECLARE Odds, Evens, Index : INTEGER
12
13 Odds ← 0
14 Evens ← 0
15 Index ← 1
16
17 WHILE Index <= LENGTH(InString)
18 IF STR_TO_NUM(MID(InString, Index, 1)) MOD 2 <> 0 THEN
19 Odds ← Odds + 1
20 ELSE
21 Evens ← Evens + 1
22 ENDIF
23 Index ← Index + 1
24 ENDWHILE
25
26 CALL Result(Odds, Evens)
27 ENDPROCEDURE
(a) Complete the following table by giving the answers, using the given pseudocode. [5]
Answer
A line number containing a variable being incremented
The type of loop structure
The number of functions used
The number of parameters passed to STR_TO_NUM()
The name of a procedure other than Check()
(b) The pseudocode includes several features that make it easier to read and understand.
Identify three of these features.
1 ................................................................................................................................................
2 ................................................................................................................................................
3 ........................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 115
(c) (i) The loop structure used in the pseudocode is not the most appropriate.
State a more appropriate loop structure and justify your choice.
Loop structure .............................................................................................................................
Justification .................................................................................................................................
.....................................................................................................................................................
................................................................................................................................................ [2]
(ii) The appropriate loop structure is now used. Two lines of pseudocode are changed and
two lines are removed.
Write the line numbers of the two lines that are removed.
.....................................................................................................................................................
............................................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 116
4 An algorithm has been written in pseudo code to input 100 numbers and print out the sum.
A REPEAT … UNTIL loop has been used.
Count ← 0
Sum ←0
REPEAT
INPUT Number
Sum ← Sum + Number
Count ←Count + 1
UNTIL Count > 100
PRINT Sum

(a) Find the error in the pseudo code and suggest a correction.
Error 1 ................................................................................................................................................
Correction ...........................................................................................................................................
......................................................................................................................................................[2]
(b) Rewrite the correct algorithm using a more suitable loop structure.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
............................................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 117
There are three different types of looping structures. Write procedure or function pseudo code for each
of following three problems using different looping structure:
a) Write a pseudo code for function Average() that input daily temperature for a month of 30 days,
calculate and return their average.
………………………………………………………..............................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
....................................................................................................................................................... [6]
Summer 2018 P22
a) Write a pseudo code for function that input numbers. Reject any numbers that are negative
and count how many numbers are positive. When the number zero is input, the process ends
and the count of positive numbers is returned.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 118
Extracted from exam paper
b) Write a procedure that input the weight in kilograms of a passenger stepping into a lift. The lift
can take a maximum weight of 640 kilograms. Stop input when total weight is greater than or
equal to maximum allowed weight and display message “Ready to Go”
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.............................................................................................................................................................
.................................................................. [6]

Q 9.6) Write an algorithm, using pseudo code and a FOR … TO … NEXT loop structure, to input 1000
numbers into an array.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
....................................................................................................................[2]
Summer 2015 P22

(b) Rewrite your algorithm using another loop structure.


...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.............................................................................................................[4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 119
Q 9.8a) Write a pseudo code algorithm to input weight of 30 items in kilograms to be loaded on a trailer.
Calculate the average weight items under or of 25 kg.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.................................................................. [6]
Q 9.8b) Explain how you change your pseudo code to reject any item over 25 Kg.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 120
Control Constructs
Q 1) Write down different statements for following tasks
Input Output Selection Iteration

Q 2) Show what type of programming construct each statement represents.


Complete the table by putting a tick (‫ )ݱ‬in the appropriate column for each item.
Item Statement Selection Iteration Assignment
1 MyScore = 65
2 FOR IndexVal = 0 TO 99
3 MyArray[3] = MID(MyString,3,2)
4 IF MyScore>= 70 THEN
5 ENDWHILE
6 ELSE Message = "Error"

Q 3) Show what type of programming construct each statement represents.


Complete the table by putting a tick (‫ )ݱ‬in the appropriate column for each item.
Item Statement Selection Iteration Assignment
1 WHILE DegF> 37.5
2 MyName = "Gordon"
3 DegF = INT(DegF)
4 ENDIF
5 CASE OF MyFavourite
6 UNTIL x = 5

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 121
Winter 2018 P21
1 (a) The following table contains statements written in pseudocode.
Show what type of programming construct each statement represents.
Put a tick in the appropriate column for each statement. [6]
Repetition
Statement Selection Assignment
(Iteration)
WHILE Count < 20
Count ÅCount + 1
IF MyGrade<> 'C' THEN
Mark[Count]ÅGetMark(StudentID)
ELSE OUTPUT "Fail"
NEXT

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 122
Winter 2018 P22
1 (a) The following table contains statements written in pseudocode.
Show the type of programming construct each statement represents.
Put a tick in the appropriate column for each statement. [6]
Repetition
Statement Selection Assignment
(Iteration)
IndexÅIndex + 5
FOR Count Å1 TO 100
TempValue[Index]ÅReadValue(SensorID)
IF Index < 30
UNTIL DayNumber> 7
OTHERWISE OUTPUT "ERROR"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 123
Summer 2019 P21
1 (a) (i) Algorithms may be expressed using four basic constructs. One construct is sequence.
Complete the following table for two other constructs. [4]
Construct Pseudocode example

..................................................................................................................
......................... ..................................................................................................................
..................................................................................................................
..................................................................................................................

..................................................................................................................
......................... ..................................................................................................................
..................................................................................................................
..................................................................................................................
(ii) Simple algorithms usually consist of input, process and output.

Complete the table by placing ticks (‘3’) in the relevant boxes. [4]
Pseudocode statement Input Process Output
Temp ÅSensorValue * Factor
WRITEFILE "LogFile.txt", TextLine
WRITEFILE "LogFile.txt", MyName&MyIDNumber
READFILE "AddressBook.txt", NextLine

(c) White-box and black-box are two types of testing. In white-box testing, data are chosen to
test every possible path through the program.
Explain how data are chosen in black-box testing.
...................................................................................................................................................
............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 124

Winter 16 P21 The program design is to be amended. The value input by the user for the
ticket type is to be validated. Part of the amended flowchart is shown below.

Write pseudocode to use a pre-condition loop for this validation.


.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 125
The programmer amends the design to validate the value of player game grade that the user
inputs. The amended part of the flowchart is shown below.

Write the equivalent pseudocode using a pre-condition loop, for this part of the amended
flowchart.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 126
Radhika was interviewed for the job. Part of the interview process was to study some program
code written in language ABC.
11 settype($TimesTable, Integer);
12 settype($upTo, Integer);
13 settype($Posn, Integer);
14 settype($Product, Integer);
15 $TimesTable = 7;
16 $UpTo = 10;
17
18 $Posn = 1
19 While ($Posn< $UpTo + 1)
20 {
21 $Product = $Posn * $TimesTable;
22 Echo $Posn . ' X' . $TimesTable . ' = ' . $Product . "<br>";
23 $Posn = $Posn + 1;
24 }

Answer the following questions taken from the interview.


(i) State what the settype keyword does in this language. [1]
(ii) Name one variable that the code uses. [1]
(iii) Give a line number for an assignment statement. [1]
(iv) Line 19 is the start of a pre-condition loop.
State the syntax that language ABC uses to indicate which statements must be executed
inside a loop. [1]
(b) (i) Describe what is meant by a transferable skill. [2]
(ii) Give two examples which suggest that programming in a high-level language is a
transferrable skill.
1 .......................................................................................................................................
...........................................................................................................................................
2 .......................................................................................................................................
...................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 127
9608 Winter 2016 Paper 21
1 A programmer wants to write a program to calculate the baggage charge for a passenger’s
airline flight. Two types of ticket are available for a flight:
• economy class (coded E)
• standard class (coded S)
Each ticket type has a baggage weight allowance as shown below. The airline makes a
charge if the weight exceeds the allowance.
Ticket type Baggage allowance(kg) Charge rate per additional kg($)
'E' 16 3.50
'S' 20 5.75
(a) A program flowchart will document the program. The flowchart will contain the following
statements:
Statement no. Statement
1 Charge Å0
2 INPUT BaggageWeight
3 Charge ÅExcessWeight * ChargeRate
4 Is ExcessWeight>0 ?
5 INPUT TicketType
6 ExcessWeightÅBaggageWeight - BaggageAllowance
7 BaggageAllowanceÅ 16
8 ChargeRateÅ3.5
9 OUTPUT Charge
10 ChargeRateÅ 5.75
11 BaggageAllowanceÅ 20
12 Is TicketType = 'E' ?

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 128
Complete the flowchart by putting the appropriate statement number in each flowchart
symbol. Statement 5 has been done for you.
[6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 129
(b) The programmer needs data to test the flowchart.
Complete the table of test data below to show five tests. [5]
Expected
TicketType BaggageWeight Explanation
output

E 15 .................................................................
.................................................................

.................................................................
.................................................................
.................................................................

.................................................................
.................................................................
.................................................................

.................................................................
.................................................................
.................................................................

.................................................................
.................................................................
.................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 130
(c) The program design is to be amended. The value input by the user for the ticket type is to
be validated. Part of the amended flowchart is shown below.

Write pseudocode to use a pre-condition loop for this validation.


.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 131
Summer 2016 P21-22
1 (a) (i) Show what type of programming construct each statement represents.
Complete the table by putting a tick (‫ )ݱ‬in the appropriate column for each item. [6]
Item Statement Selection Iteration Assignment
1 MyScore = 65
2 FOR IndexVal = 0 TO 99
MyArray[3] =
3
MID(MyString,3,2)
4 IF MyScore>= 70 THEN
5 ENDWHILE
6 ELSE Message = "Error"

(ii) State the purpose of each statement in the table in part (a)(i).
Do not use mathematical symbols in your descriptions. [6]
Item Purpose of statement

1 ...............................................................................................................................................
...............................................................................................................................................

2 ...............................................................................................................................................
...............................................................................................................................................

3 ...............................................................................................................................................
...............................................................................................................................................

4 ...............................................................................................................................................
...............................................................................................................................................

5 ...............................................................................................................................................
...............................................................................................................................................

6 ...............................................................................................................................................
...............................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 132
(iii) Evaluate the following expressions when MyString has the value
"AdaptiveMaintenance".[2]
Expression Result
'D' & RIGHT(MyString, 4)
LEFT(RIGHT(MyString, 7), 3)

11a Summer 20 P21


1 (a) Complete this definition of the term algorithm.
An algorithm is a solution to a problem expressed as ..............................................................
...................................................................................................................................................
............................................................................................................................................. [2]
(b) A program design includes the use of subroutines (functions and procedures).
Give three advantages of using subroutines in a program.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
................................................................................................................................................... [3]
(c) Draw lines on the following diagram to connect each computing term with the appropriate description. [3]
Term Description

Checking that a program performs as


Selection
expected

A method for increasing the level of detail of


Black-box testing
an algorithm

To test a condition to determine the path of


Stepwise refinement
program execution

A method of executing certain lines of code


Iteration
more than once
10C Winter 19 P23
1 (a) (i) Programming languages can support different data types. Complete the table by naming three
different data types together with an example data value for each. [6]
Data type Example data value

(ii) Identify the type of programming statement that assigns a data type to a variable.
..................................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 133

(b) As part of the development of an algorithm, a programmer may construct an identifier table.
Describe what an identifier table contains.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.............................................................................................................................................................. [2]
(c) (i) Simple algorithms usually consist of three different stages.
Complete the table below. Write each example statement in program code.
The second stage has already been given. [5]
Stage Example statement

Process

(ii) Write a single statement in program code that contains two of the stages. Do not repeat
any of the statements from part (c)(i).
..................................................................................................................................... [1]

10c 9608 W19 P23 1(d) A software developer is writing a program and includes several
features to make it easier to read and understand. One of these features is the use of
indentation.
State three other features.
Feature 1 ..................................................................................................................................
Feature 2 ..................................................................................................................................
Feature 3 ............................................................................................................................... [3]
(e) A trace table is often used during program testing.
Identify the type of testing that includes the use of a trace table.
............................................................................................................................................. [1]

2 (a) (i) Two types of loop that may be found in an algorithm are the ‘pre-condition’ and ‘post
condition’ loop.
Identify one other type of loop. Explain when it should be used.
Type ..................................................................................................................................
Explanation .......................................................................................................................
...........................................................................................................................................
.................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 134
(ii) Part of a program flowchart is shown.

Implement the flowchart in pseudocode using a post-condition loop.


...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
........................................................................................................................................................ [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 135
10a 9608 Winter 2019 p21

(a) (i) This pseudocode lacks features that would make it easier to read and understand.
State three such features.
Feature 1 ...........................................................................................................................
Feature 2 ...........................................................................................................................
Feature 3 ........................................................................................................................... [3]
(ii) Draw a program flowchart to represent the algorithm implemented in the pseudocode.
Variable declarations are not required in program flowcharts. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 136
ͳʹǤʹ ‹ŽŽ‹‰‹”ƒ ‡ƒ„އ
9608 Summer 16 P21
4 A string-handling function has been developed. The pseudocode for this function is shown
below. For the built-in functions list, refer to the Insert.

FUNCTION SSM(String1, String2 : STRING) RETURNS INTEGER


DECLARE n, f, x, y : INTEGER
nÅ0
fÅ0
REPEAT
n Ån + 1
xÅn
yÅ1
WHILE MID(String1, x, 1) = MID(String2, y, 1)
IF y = LENGTH(String2)
THEN
fÅn
ELSE
x Åx + 1
yÅy+1
ENDIF
ENDWHILE
UNTIL (n = LENGTH(String1)) OR (f < > 0)
RETURN f
ENDFUNCTION
(a) Complete the trace table below by performing a dry run of the function when it is called as
follows: SSM("RETRACE", "RAC")
[6]
N f x y MID(String1,x,1) MID(String2,y,1)
0 0

(b) (i) Describe the purpose of function SSM.


.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 137

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 138
ͳͳǤ͵–”— –—”‡ȋ‘†—Žƒ”Ȍ”‘‰”ƒ‹‰ȋ — –‹‘•Ƭ”‘ ‡†—”‡•Ȍ
Function Interface: The first line of a function definition that contains the identifier name and
parameters; also called the “function header”
Header (procedure or function) – the first statement in the definition of a procedure or function,
which contains its name, any parameters passed to it, and, for a function, the type of the return value.
Parameter – a variable applied to a procedure or function at the time of function definition, that
allows one to pass in a value for the procedure to use.
Argument – the value passed to a procedure or function at the time of function or procedure CALL.
By reference – a method of passing a parameter to a procedure in which the value of the variable can
be changed (updated) by the procedure.
By value – a method of passing a parameter to a procedure in which the value of the variable cannot
be changed (updated) by the procedure.

Structured programming (sometimes known as modular programming) is a programming


paradigm that facilitates the creation of programs with readable code and reusable
components.
Sub-routines
A Sub-routine is a reusable set of programming instructions for a given task that forms a
subsystem, not the whole system. Sub-routines written in high-level programming languages
are called ‘procedures’ or ‘functions’ depending on how they are used.
A subroutine is a small section of a program that is part of a larger program.
What are functions and procedures for?
Extracted from https://www.bbc.co.uk/bitesize/guides/z9hykqt/revision/1
In a computer program there are often
sections of the program that we want to
re-use or repeat. Chunks of instructions
can be given a name - they are
called functions and procedures.
Algorithms can be broken down into
procedures or functions. This saves
time by only having to execute (call)
the function when it is required, instead
of having to type out the whole
instruction set.
Programming languages have a set of pre-defined (also known as built-in) functions and
procedures. If the programmer makes their own ones, they are custom-made or user-
defined.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 139
Procedures or functions?
A procedure performs a task, whereas a function produces information.
Functions differ from procedures in that functions return values, unlike procedures which do
not. However, parameters can be passed to both procedures and functions.
Procedure
A procedure is a group of instructions/block of program statements that do a specific task but
never returns a value.
Defining a procedure:
Writing code to create a procedure is known as Define a procedure
Pseudo code Python
PROCEDURE <identifier>() def <identifier>():
Statement(s) statement(s)
END PROCEDURE
PRCEDURE TestOutput() def TestOutput():
FOR Count ← 1 TO 10 for Count in range(10):
PRINT “Allah” print(“Allah”)
NEXT Count
END PROCEDURE

CALL a Procedure:
Executing a procedure is known as CALL.
Pseudo code Python
CALL <Procedure identifier>() <Procedure identifier>()
CALL TestOutput() TestOutput():

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 140
Function
A function is a group of instructions/block of program statements that always returns a value.
Defining a function:
Writing code to create a procedure is known as Define a procedure
Pseudo code Python
FUNCTION <identifier>() RETURN <data def <identifier>():
type> statement(s)
Statement(s) return <value>
RETURN <value>
END FUNCTION
FUNCTION InputPosNum() RETURN REAL def InputPosNum():
INPUT Num Num=float(input(“Enter a number “))
WHILE Num<=0 While Num<=0:
PRINT “Error! Enter positive number” Num=float(input(“Error! Enter
INPUT Num positive number”))
ENDWHILE return Num
RETURN Num
END FUNCTION

CALL a Function:
As a function always returns a value so we need to store returning value in a variable on
function CALL.

Pseudo code Python


<identifier> ← <Function Identifier> () <identifier> = InputPsNum()
Number ← InputPosNum() Number = InputPosNum()

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 141
Parameters
Parameters allow us to pass information or instructions into functions and procedures. They
are useful for numerical information such as stating the size of an object.
Parameters are the names of the information that we want to use in a function or procedure.
The values passed in are called arguments.

Difference between Argument and Parameter


ARGUMENT PARAMETER

When a function is called, the values that The values which are defined at the time of the

are passed during the call are called as function prototype or definition of the function are

arguments. called as parameters.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 142
Passing parameters to subroutines
Courtessy : Cambridge International AS and A Level Computer Science Coursebook
When a subroutine requires one or more values from the main program, we supply these as
arguments to the subroutine at call time. This is how we use built-in functions. We don't need
to know the identifiers used within the function when we call a built-in function.
When we define a subroutine that requires values to be passed to the subroutine body, we
use a parameter list in the subroutine header. When the subroutine is called, we supply the
arguments in brackets. The arguments supplied are assigned to the corresponding parameter
of the subroutine (note the order of the parameters in the parameter list must be the same as
the order in the list of arguments). This is known as the subroutine interface.

Passing Parameters
If a parameter is passed by value, at call time the argument can be an actual value. If the argument is
a variable, then a copy of the current value of the variable is passed into the subroutine. The value of
the variable in the calling program is not affected by what happens in the subroutine.
A parameter can be passed by reference. At call time, the argument must be a variable. A pointer to
the memory location of that variable is passed into the procedure. Any changes that are applied to the
variable's contents will be effective outside the procedure in the calling program/module.
By value: the actual value is passed into the procedure
By reference: the address of the variable is passed into the procedure
Note that neither of these methods of parameter passing applies to Python. In Python, the method is
called pass by object reference

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 143
The important point is to understand how to program in Python to get the desired effect. The full
procedure header is written in pseudocode, in a very similar fashion to that for function headers, as:
PROCEDURE <Procedureidentifier> (<parameterList>)
The parameter list needs more information for a procedure definition. In pseudocode, a parameter in
the list is represented in one of the following formats:
BYREF <identifierl > <dataType >
BYVAL <identifier2> : <dataType>
Passing parameters by value
By value Copy of a variable’s value is used as the argument to a procedure or function; if its value
changes within the subroutine, the change is local and the original variable’s value is not changed in
the main program.
By Value means passing a copy of a variable to Subroutine. This copy can be changed but the original
will not be altered.
For example, consider the following pseudo code (Extracted from Summer 2017 Past Paper).
PROCEDURE MyProc(BYVAL X)
X ÅX + 1
ENDPROCEDURE
Here the copy of variable X will be passed to the procedure MyProc(). The increment of X will not have
any effect in the X at main program.
The lines of pseudo code in main program are :
XÅ 4
CALL MyProc(X)
OUTPUT(X)
Parameter X is used to pass data to procedure MyProc(). The increment in value of X in MyProc has
no effect on the variable in main program and it will give output 4.
In Python all parameters are ByVal by default

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 144
Passing parameters by reference
By reference Variable is used as the argument to a procedure or function; if its value changes within
the subroutine, the changed value is available in the main program.
By reference means that copy of the original values are not handed over, but pointing to the original
variable.
For Example Consider the following pseudo code (Extracted from Summer 2017 Past Paper).
PROCEDURE MyProc(BYREF X)
X ÅX + 1
ENDPROCEDURE
Here the original variable X will be passed to the procedure MyProc(). The increment of X will also
effects in the X at main program.
The lines of pseudo code in main program are :
XÅ 4
CALL MyProc(X)
OUTPUT(X)
Parameter X is used to pass data to procedure MyProc(). The increment in value of X in MyProc() has
effect on the variable in main program and it will give output 5.
Python does not have a facility to pass parameters by reference. Instead the subroutine behaves as a
function and returns multiple values.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 145
Scope
Scope refers to where a function, procedure, variable or constant can be used. They can be
local or global.
A global variable is declared in a way that makes it available to every other part of the
program, whereas a local variable is declared in a way that makes it only available within a
specific function.
A module-scoped variable is only available with a single file or module.
For example, this program asks for a name, and then prints that name out three times.

Pseudo code Python Code


INPUT Name name = input("Please enter your name")
PROCEDURE Greet() def greet():
FOR X Å 1 TO 3 for x in range (3):
PRINT Name print (name)
NEXT X greet()
END PROCEDURE
CALL Greet()

Note that:
x name is a variable that is global in its scope
x the x variable in the loop for x in range... is local to the greet function. If you tried to
access x from outside this function, you would get an error message as it only exists
inside greet
x if the same code above was in a module file, then name would be module-scoped
Q 1) Write a modular program consisting on five user defined modules.
a. NaturalNum () is procedure that displays natural numbers from 1 to 10.
b. OddNum() is a procedure that displays odd numbers 1,3,5, … 19.
c. EvenNum() is a procedure that displays Even numbers from 2, 4, 6, … 20
d. GenerateTable () is a procedure that takes a number and displays its table upto 10
times.
e. Square() is a function that takes a number and returns its Square.
f. Cube() is a function that takes a number and returns its Cube.
g. Factorial() is a function that takes a number and returns its factorial.
h. DisplayMenu() is a procedure that displays options for all modules from a to g, asks
user to select an option and then run the selected module.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 146
Q) Write down a pseudo code for user define function MODULUS.
MOD function is used to calculate remainder after division. for example, MOD (20,6) gives 2.
This can also be obtained by continuous subtraction of 6 from 20 until result is more than 6.

FUCNTION MOD(N1, N2:ITEGER) RETURNS INTEGER


DECLARE Remainder : INTEGER
Remainder Å N1
WHILE Remainder > = N2
Remainder Å Remainder – N2
ENDWHILE
RETURN Remainder
END FUNCTION

N1 N2 Remainder Remainder > N2 Return


20 6 20 Yes
14 Yes
8 Yes
2 No 2

N1 N2 Remainder Remainder > N2 Return


25 5 25 Yes
20 Yes
15 Yes
10 Yes
5 Yes
0 No 0

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 147
Q 2) A program displays a menu with choices 1 to 4. The code to display the menu is written
as the procedure DisplayMenu.
(a) Pseudocode which uses this procedure is:
CALL DisplayMenu
REPEAT
OUTPUT "Enter choice (1..4)"
INPUT Choice
UNTIL Choice >= 1 AND Choice <= 4

(i) Describe what this pseudocode will do. [3]

(ii) State why a loop is required. [1]

(b) The following pseudo code is a revised design.


CONSTANT iÅ 3
CALL DisplayMenu
NoOfAttemptsÅ0
REPEAT
OUTPUT "Enter choice (1..4)"
INPUT Choice
NoOfAttemptsÅNoOfAttempts + 1
UNTIL (Choice >= 1 AND Choice <= 4) OR NoOfAttempts = i

(i) Give the maximum number of inputs the user could be prompted to make. [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 148
(ii) State why this algorithm is an improvement on the one given in part (a). [1]

(c) The pseudocode is in its initial stage of development.


The table below shows the action currently taken by the pseudocode following each menu
choice.
Menu
Description Program response
choice
Read data from Calls a procedure ReadFile which for testing
1
the customer file purposes outputs the message “Read file code”
2 Add a customer Outputs message “Add customer code”
Search for a
3 Outputs message “Search customer code”
customer
Terminates the
4 Ends
program

Write algorithm for the above task.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 149
0Specimen Paper 2
4 (a) Parameter x is used to pass data to procedure MyProc in the following pseudocode:
x ← 4
CALL MyProc(x)
OUTPUT x

PROCEDURE MyProc(x : INTEGER)


DECLARE z : INTEGER
x ← x + 1
z ← x + 3
ENDPROCEDURE
There are two parameter passing methods that could be used.
Complete the following table for each of the two methods. [6]
Name of parameter Value
Explanation
passing method output

................................. ......................................................................................
............
................................. ......................................................................................
......................................................................................

................................. ......................................................................................
............
................................. ......................................................................................
......................................................................................

(b) The pseudocode includes the use of parameters.


State two other features in the pseudocode that support a modular approach to programming.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
............................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 150

3 (a) Programming languages usually contain a range of built-in functions, such as a random
number generator.
State three advantages of using built-in functions.
1 ................................................................................................................................................
2 ................................................................................................................................................
3 ............................................................................................................................................[3]

Q 4) Summer 2019 P22


2 (a) (i) Procedures and functions are examples of subroutines.
State a reason for using subroutines in the construction of an algorithm.
.....................................................................................................................................................
............................................................................................................................................ [1]
(ii) Give three advantages of using subroutines in a program.
1 ........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
...........................................................................................................................................
3 ........................................................................................................................................
........................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 151
(iii) The following pseudocode uses the subroutine DoSomething().
Answer Å23 + DoSomething("Yellow")
State whether the subroutine is a function or a procedure. Justify your answer.
Type of subroutine .............................................................................................................
Justification .......................................................................................................................
........................................................................................................................................... [2]
(b) The program development cycle involves writing, translating and testing a high-level
language program.
Describe these activities with reference to each of the following:
• editor
• translator
• debugger
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................ [3]
(c) The following lines of code are taken from a high-level language program.
WHEN Result < 20
{
Call ResetSensor(3)
Result :=GetSensor(3)
}
Identify the type of control structure and describe the function of the code.
Control structure .......................................................................................................................
Function of code .......................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
..................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 152
3 The following structure chart shows the relationship between three modules.

Parameters A to E have the following data types:


A, D : STRING
C : CHAR
B, E : INTEGER
(a) (i) Write the pseudocode header for module SubA().
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [3]
(ii) Write the pseudocode header for module SubB().
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [3]
(b) Module hierarchy and parameters are two features that may be represented on a structure chart.
State two other features than can be represented.
Feature 1 ..................................................................................................................................
Feature 2 .................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 153
Q 5) Winter 2015 P22
4 The standard pack of playing cards has four suits – called Clubs, Diamonds, Hearts and
Spades.
Each card has a value shown by its number or a name: 1 (Ace), 2, 3, … 10, 11 (Jack), 12
(Queen),
13 (King). The pack of cards has one combination for each suit and value.
A program is to be written which simulates a magician dealing all 52 cards from the card
pack.
The program generates pairs of random numbers:
• the first, in the range 1 to 4, to represent the suit
• the second, in the range 1 to 13, to represent the card value
(a) Explain why the generation of 52 (4 suits x 13 card values) pairs of random numbers will
not
simulate the dealing of the complete pack.
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[2]
(b) A representation of dealing out the cards is shown below:

The table shows two cards have been dealt so far; the 3 of Hearts and the Jack of Clubs.
When each card is dealt, the appropriate cell changes from F to T.
The program will output the suit and the card value in the order in which the cards are dealt.
The program design in pseudocode is produced as follows:

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 154
01 DECLARE SuitNum : INTEGER
02 DECLARE CardValue : INTEGER
03 DECLARE DealCount : INTEGER
04 DECLARE NewCard : BOOLEAN
05 DECLARE CardPack
....................................................
06
07 CALL InitialiseCardPack
08 DealCount ← 0
09 WHILE DealCount<> 52
10 NewCard ← FALSE
11 WHILE NewCard = FALSE
12 SuitNum ← RANDOM(1,4) // generates a random number
13 CardValue ← RANDOM(1,13) // in the range given
14 IF CardPack[SuitNum, CardValue] = FALSE
15 THEN
16 CardPack[SuitNum, CardValue] ← TRUE
17 NewCard ← TRUE
18 OUTPUT SuitNum, CardValue
19 ENDIF
20 ENDWHILE
21 DealCount ← DealCount + 1
22 ENDWHILE
23
24 // end of main program
25
26 PROCEDURE InitialiseCardPack
27 DECLARE i : INTEGER
28 DECLARE j : INTEGER
29 FOR i ← 1 TO 4
30 FOR j ← 1 TO 13
31 CardPack[i, j] ← FALSE
32 NEXT i
33 NEXT i
34 ENDPROCEDURE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 155
Study the pseudocode and answer the questions below:
Give the line number for:
(i) A statement which marks the end of a count controlled loop.
....................................................................................................................................................... [1]
(ii) The declaration of a local variable.
...................................................................................................................................................... [1]
(iii) The initialisation of a variable used as a counter, but not to control a ‘count controlled’ loop.
...................................................................................... ............................................................... [1]
(iv) A statement which uses a built-in function of the programming language.
................................................................................................................................................... [1]
(c) Give the number of procedures used by the pseudocode.
...................................................................................................................................................... [1]
(d) Copy the condition which is used to control a ‘pre-condition’ loop.
...................................................................................................................................................... [1]
(e) Explain the purpose of lines 14 – 19 in the design.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
..................................................... [2]
(f) Complete the declaration of the global variable at line 05.
05 DECLARE CardPack...................................................................................................................[1]
(g) Line 18 in the design shows which new card is dealt each time.
When an Ace, Jack, Queen or King is dealt, the output displays the number for that card, not the name
of the card.
Card value Cardname
1 Ace
11 Jack
12 Queen
13 King

A new requirement is to display the name of the card, where appropriate.


Write a CASE structure using variable CardValue.

Assign to a new variable CardName either:


• the card value (2, 3, 4, 5, 6, 7, 8, 9 or 10)
• or where appropriate, the card name Ace, Jack, Queen or King [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 156

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 157
Q 6) Summer 2017 P22
4 (a) High-level programming languages have many features that support the modular
approach.
One such feature is the use of parameters.
State two other features.
1 ...............................................................................................................................................
...................................................................................................................................................
2 ...............................................................................................................................................
...............................................................................................................................................[2]
(b) Consider the following pseudocode.
PROCEDURE MyProc(x)
x Åx + 1
ENDPROCEDURE
Intermediate lines of pseudocode not shown
xÅ 4
CALL MyProc(x)
OUTPUT(x)
Parameter x is used to pass data to procedure MyProc.
There are two parameter passing methods that could be used.
Complete the following table for each of the two methods. [6]
Name of parameter Value
Explanation
passing method output

................................. ......................................................................................
.............
................................. ......................................................................................
......................................................................................

................................. ......................................................................................
.............
................................. ......................................................................................
......................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 158

Q 7) Winter 2017 P22


1 (c) Functions and procedures are subroutines.
Explain why parameters are used with subroutines.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 159
Q 8) Summer 2018 P23
2 The following is a function design in pseudocode.
Line numbers are given for reference only.

(a) This pseudocode includes features that are examples of good practice.
Explain why it is useful to include the two following features.
Comments ................................................................................................................................
...................................................................................................................................................
Indentation ................................................................................................................................
.............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 160
(b) Study the function GradeCalc(). Identify the features of the function in the following table.
[9]
Feature Answer
A line number containing an example of an integer assignment statement
A line number containing the start of a selection structure
A line number containing the end of a selection structure
The upper bound of the Mark array
The number of dimensions of the Mark array
The name for the type of loop structure used
A line number containing an unnecessary assignment statement
The number of times OUTPUT is called
The number of local variables
(c) (i) There is a mistake in the pseudocode that would produce a data type mismatch error if
a programmer were to write similar program code. Describe this mistake and how it may be
corrected.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
......................................................................................[2]
(ii) Lines 14 to 30 of the pseudocode on page 4 could be written using a CASE structure.
Write the equivalent CASE structure in pseudocode.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
..................................................................................................[4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 161
Q 9) 9608 Summer 2018 P23
7 A function, IsFactor() takes two integer parameters and checks whether the second
parameter is a factor of the first parameter. For example IsFactor(6,3) would return TRUE as
six divided by three has a remainder of zero. This function returns FALSE if there is a non-
zero remainder, or if the value of the second parameter is zero.
Write program code to implement the IsFactor() function.
(Note: in 9618 only pseudo code is required)

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................[6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 162
1ac 9618 S21 P21
2 (c) A program will:
• input 50 unique integer values
• output the largest value
• output the average of the values excluding the largest value.
Draw a program flowchart to represent the algorithm. Variable declarations are not required.
It is not necessary to check that each input value is unique. [6]
1ac 9618 S21 P21
4 Study the following pseudocode. Line numbers are for reference only.
10 FUNCTION Convert(Name : STRING) RETURNS STRING
11
12 DECLARE Flag: BOOLEAN
13 DECLARE Index : INTEGER
14 DECLARE ThisChar : CHAR
15 DECLARE NewName : STRING
16
17 CONSTANT SPACECHAR = ' '
18
19 Flag TRUE
20 Index Å 1
21 NewName Å "" // formatted name string
22
23 WHILE Index <= LENGTH(Name)
24 ThisChar Å MID(Name, Index, 1)
25 IF Flag = TRUE THEN
26 NewName Å NewName & UCASE(ThisChar)
27 IF ThisChar <> SPACECHAR THEN
28 Flag ÅFALSE
29 ENDIF
30 ELSE
31 NewName Å NewName & ThisChar
32 ENDIF
33 IF ThisChar = SPACECHAR THEN
34 Flag Å TRUE
35 ENDIF
36 Index Å Index + 1
37 ENDWHILE
38
39 RETURN NewName
40
41 ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 163
(a) Complete the trace table below by dry running the function when it is called as follows:
Result Å Convert("‫׏‬in‫׏‬a‫׏׏‬Cup")
Note: The symbol '‫ '׏‬has been used to represent a space character.
Use this symbol for any space characters in the trace table.
The first row has been completed for you. [5]
Name Flag Index NewName ThisChar
"‫׏‬in‫׏‬a‫׏׏‬Cup"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 164
(b) The pseudocode for Convert() contains a conditional loop.
State a more appropriate loop structure.
Justify your answer.
Loop structure ...........................................................................................................................
...................................................................................................................................................
Justification ...............................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]
(c) Two changes need to be made to the algorithm.
Change 1: Convert to lower case any character that is not the first character after a space.
Change 2: Replace multiple spaces with a single space.
(i) Change 1 may be implemented by modifying one line of the pseudocode.
Write the modified line.
...........................................................................................................................................
.......................................................................................................................................[1]
(ii) Change 2 may be implemented by moving one line of the pseudocode.
Write the number of the line to be moved and state its new position.
Line number ......................................................................................................................
New position ......................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 165

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 166

1b 9618 S21 P22


4 A teacher uses a paper-based system to store marks for a class test. The teacher requires
a program to assign grades based on these results.
The program will output the grades together with the average mark.
Write a detailed description of the algorithm that will be needed.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 167
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................ [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 168
Q 10) 9608 Winter 2018 P21
2 Shop customers have a discount card with a unique card number. Customers collect points
after they have bought items. The more points they have, the bigger the discount. If they shop
on a Wednesday, their discount is increased by 20%.
The function GetDiscountRate() takes a card number as a parameter and returns the discount
rate for a customer based on the number of points they have collected. A flowchart for the
function is shown. The function uses the following variables and functions.

Identifier Data type Description


DRate REAL The discount rate
CardNum STRING The unique customer card number
Points INTEGER The number of points collected
Takes the card number as a parameter and returns the number
GetPoints() FUNCTION
of points already collected
Today() FUNCTION Returns the day number: 1 for Monday, 2 for Tuesday etc.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 169

(a) Write pseudocode to implement the GetDiscountRate() function.


Your solution should follow the flowchart for the function as closely as possible. Variable
declarations should be included. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 170
(b) A programmer writes the function GetDiscountRate() in a high-level language.
(i) A run-time error could occur when the function is used.
Name and describe one other type of error that the function could contain.
Name ........................................................................................................................................
Description .................................................................................................................................
...............................................................................................................................................…..
................................................................................................................................................[2]
(ii) Function GetPoints() has not been written yet.
Name and describe a strategy that can be used to test GetDiscountRate() before the
GetPoints() function has been written.
Name .........................................................................................................................................
Description .................................................................................................................................
.....................................................................................................................................................
...............................................................................................................................................[2]
(c) There are different ways to minimise the risk of errors when writing programs, such as the
use of constants and library routines.
(i) Identify two values that could be replaced by constants in the function GetDiscountRate().
.....................................................................................................................................................
...............................................................................................................................................[1]
(ii) Write pseudocode to declare one of the constants you have given in part (c)(i).
................................................................................................................................................[2]
(iii) Explain how the use of constants helps to minimise programming errors. [2]

(iv) Give a reason why the use of library routines helps to minimise the risk of errors when
writing a program. [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 171
(v) Constants and library routines help to minimise the risk of errors.
Name another way that you can minimise the risk of errors when writing a program.
Explain how this helps.
Name .......................................................................................................................................
Explanation [2]
4 Part of a program written in pseudocode is shown.

(a) (i) Examine the pseudocode and complete the following table. [4]
Answer
The identifier name of a global integer
The identifier name of a user-defined procedure
The line number of an unnecessary statement
The scope of ArrayString

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 172
(ii) Describe in detail the purpose of lines 19 to 26 in the function ScanArray().
Do not use pseudocode in your answer. [4]
(b) The function ScanArray() needs to be amended so that the comparison is not case sensitive. For
example, comparing “Aaaa” with “AAAa” should evaluate to TRUE.
Write pseudo code to implement the amended ScanArray() function.

...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
........................................................................................................................................................[ 6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 173
(c) The function ScanArray() is one of a number of sub-tasks within a program.
Name the process that involves the splitting of a problem into sub-tasks and state two
advantages of this approach.
Name ........................................................................................................................................
Advantage 1 .............................................................................................................................
...................................................................................................................................................
Advantage 2 .............................................................................................................................
...................................................................................................................................................[3]

(d) ResultArray is a 2D array of type STRING. It represents a table containing 100 rows and2
columns.
Write program code to declare ResultArray and set all elements to the value '*'.
Program code
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
..............................................................................................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 174

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 175

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 176

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 177

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 178
Q 11) Winter 2018 9608 P22
2 Shop customers have a discount card with a unique card number. Customers collect points each
time they buy items. The number of points they collect depends on:
• the total amount they spend
• the number of points already collected.
Identifier Data type Description
CardNum STRING A numeric string representing the unique card number
OldPoints INTEGER The number of points already collected
NewPoints INTEGER The number of new points collected
Total REAL The amount spent
Takes the card number as a parameter and returns the number of
GetPoints() FUNCTION
points already collected
INT() FUNCTION Refer to the Appendix on page 16
The function CalcPoints() takes the card number and the total amount spent as parameters. It
returns the number of new points collected. A flowchart for the function is shown.
The function uses the following variables and functions.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 179
(a) (i) Write pseudocode for the CalcPoints() function.
Your solution should follow the flowchart as closely as possible [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 180
(ii) The value of the total amount spent is calculated by an Electronic Point Of Sale (EPOS) system.
This system does not have the prices of all items. For these items, a valid total amount has to be
entered manually.
A function, GetTotal(), prompts the user to input this value.
If the user enters a valid value greater than 0 and less than 10000, the function returns the value. The
function prompts the user to re-enter the value each time the user enters an invalid value.
Write pseudocode to complete the GetTotal() function.
FUNCTION GetTotal() RETURNS REAL

(b) The function CalcPoints() is written in a high-level language. It has been checked and it
does not contain any syntax or logic errors.
(i) Name and describe one other type of error that the high-level language code could contain.
Name .................................................................................................................................
Description [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 181
(ii) The function CalcPoints() is tested using white-box testing.
State two different values of Total that could be used to test different paths through the algorithm.
Justify your choices.
Value .................................................................................................................................
Justification .......................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Value .................................................................................................................................
Justification .......................................................................................................................
...........................................................................................................................................
...........................................................................................................................................[4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 182
4 Part of a program written in pseudocode is shown.
010 DECLARE NextArrayElement : INTEGER

100 FUNCTION ScanFile(SearchString: STRING) RETURNS INTEGER
101
102 DECLARE FileData : STRING
103 DECLARE FileLine : INTEGER
104
105 NextArrayElement 1
106 FileLine 1
107 FileDataReadFileLine("DataFile.txt", FileLine)
108
109 WHILE FileData<> ""
110 IF LEFT(FileData, 7) = SearchString
111 THEN
112 ResultArray[NextArrayElement] FileData
113 NextArrayElementNextArrayElement + 1
114 ENDIF
115 FileLineFileLine + 1
116 FileDataReadFileLine("DataFile.txt", FileLine)
117 ENDWHILE
118
119 CALL ScanCompleted()
120 RETURN FileLine
121
122 ENDFUNCTION
(a) (i) Examine the pseudocode. Complete the following table. [5]
Answer
The identifier name of a local variable
The identifier name of a user-defined procedure
The identifier name of a user-defined function
The number of dimensions of ResultArray
The scope of FileData

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 183
(ii) Describe in detail the purpose of lines 109 to 117 in the ScanFile() function. Do not use
pseudocode in your answer. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 184

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 185

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 186

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 187
2 (a) A structure chart is often used in modular program design. One feature shown is the
sequence of module execution.
State four other features that may be shown.
Feature 1 ..................................................................................................................................
...................................................................................................................................................
Feature 2 ..................................................................................................................................
...................................................................................................................................................
Feature 3 ..................................................................................................................................
...................................................................................................................................................
Feature 4 ..................................................................................................................................
...................................................................................................................................................
[4]
(b) Identify and describe one feature of an Integrated Development Environment (IDE) that
can help with program presentation.
Feature .....................................................................................................................................
Description ................................................................................................................................
............................................................................................................................................... [2]

(c) By value is one method of passing a parameter to a subroutine.


Identify and describe the other method.
Method ......................................................................................................................................
Description ................................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]
(d) Explain the term adaptive maintenance.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 188
3 The following is a function design in pseudocode.
Line numbers are given for reference only.
10 FUNCTION Check(InString : STRING) RETURNS BOOLEAN
11
12 DECLARE NumDots : INTEGER
13 DECLARE Index : INTEGER
14 DECLARE NumOthers : INTEGER
15
16 NumDots ← 0
17 NumOthers ← 0
18 Index ← 1
19
20 WHILE NumDots < 3 AND Index <= LENGTH(InString)
21
22 IF MID(InString, Index, 1) = '.'
23 THEN
24 NumDots ← NumDots + 1
25 ELSE
26 NumOthers ← NumOthers + 1
27 ENDIF
28 Index ← Index + 1
29
30 ENDWHILE
31
32 IF NumDots = NumOthers
33 THEN
34 RETURN TRUE
35 ELSE
36 RETURN FALSE
37 ENDIF
38
39 ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 189
Study the pseudocode. Identify the relevant features in the following table.
Refer to the Appendix for the list of built-in functions and operators. [7]
Feature Answer
The number of the line containing a variable being incremented
The range of line numbers containing a pre-condition loop
The number of initialisation statements
The number of the line containing a logical operator
The range of line numbers containing a selection statement
The name of a built-in function
The name of a parameter

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 190

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 191

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 192
10b Winter 19 9608 P22
1 Study the following pseudocode.
PROCEDURE FillTank()
DECLARE Tries : INTEGER
DECLARE Full : BOOLEAN

Tries ← 1

Full ← ReadSensor("F1")

IF NOT Full
THEN
WHILE NOT Full AND Tries < 4
CALL TopUp()
Full ← ReadSensor("F1")
Tries ← Tries + 1
ENDWHILE
IF Tries > 3
THEN
OUTPUT "Too many attempts"
ELSE
OUTPUT "Tank now full"
ENDIF
ELSE
OUTPUT "Already full"
ENDIF
ENDPROCEDURE

(a) (i) The pseudocode includes features that make it easier to read and understand.
State three such features.
Feature 1 ...........................................................................................................................
Feature 2 ...........................................................................................................................
Feature 3 ........................................................................................................................... [3]

(ii) Draw a program flowchart to represent the algorithm implemented in the pseudocode.
Variable declarations are not required in program flowcharts. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 193
4 A program is being written to control the operation of a portable music player. One part of
the program controls the output volume.
The player has two buttons, one to increase the volume and one to decrease it. Whenever a
button is pressed, a procedure Button() is called with a parameter value representing the
button as follows:
Button Parameter value
Volume increase 10
Volume decrease 20

For example, pressing the volume increase button three times followed by pressing the
volume decrease button once would result in the calls:
CALL Button(10) // VolLevel increased by 1
CALL Button(10) // VolLevel increased by 1
CALL Button(10) // VolLevel increased by 1
CALL Button(20) // VolLevel decreased by 1
The program makes use of two global variables of type INTEGER as follows:

Variable Description
VolLevel The current volume setting. This must be in the range 0 to 49.
A value that can be set to limit the maximum value of VolLevel,
in order to protect the user’s hearing.
MaxVol
A value in the range 1 to 49 indicates the volume limit.
A value of zero indicates that no volume limit has been set.

The procedure Button() will modify the value of VolLevel depending on which button has been pressed
and whether a maximum value has been set.

(a) Write pseudocode for the procedure Button(). Declare any additional variables you use.
The value of MaxVol should not be changed within the procedure.
Parameter validation is not necessary. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 194
(b) The procedure Button() is to be tested using black-box testing.
Fill in the gaps below to define three tests that could be carried out. [6]

TEST 1 – VolLevel is changed


Parameter value: 10
MaxVol: ..................
VolLevel value before call to Button(): 48
VolLevel expected value after call to Button(): ..................

TEST 2 – VolLevel is not changed


Parameter value: 10
MaxVol: 34
VolLevel value before call to Button(): ..................
VolLevel expected value after call to Button(): ..................

TEST 3 – VolLevel is not changed


Parameter value: ..................
MaxVol: 40
VolLevel value before call to Button(): 0
VolLevel expected value after call to Button(): ..................

(c) The testing stage is part of the program development cycle.


(i) The program for the music player has been completed. The program does not contain any syntax
errors, but testing could reveal further errors.
Identify and describe one different type of error that testing could reveal.
Type ..................................................................................................................................
Description ........................................................................................................................[2]

(ii) Stub testing is a technique often used in the development of modular programs.
Describe the technique. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 195

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 196

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 197

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 198
10C 9608 Winter 19 P23
4 The following pseudocode algorithm checks whether a string is a valid email address.
FUNCTION Check(InString : STRING) RETURNS BOOLEAN
DECLARE Index : INTEGER
DECLARE NumDots : INTEGER
DECLARE NumAts : INTEGER
DECLARE NextChar : CHAR
DECLARE NumOthers : INTEGER
NumDots ← 0
NumAts ← 0
NumOthers ← 0
FOR Index ← 1 TO LENGTH(InString)
NextChar ← MID(InString, Index, 1)
CASE OF NextChar
'.’ : NumDots ← NumDots + 1
'@': NumAts ← NumAts + 1
OTHERWISE NumOthers ← NumOthers + 1
ENDCASE
NEXT Index
IF (NumDots >= 1 AND NumAts = 1 AND NumOthers > 5)
THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION
(a) Describe the validation rules that are implemented by this pseudocode. Refer only to the contents
of the string and not to features of the pseudocode. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 199
(b) (i) Complete the trace table by dry running the function when it is called as follows: [5]
Result Å Check("[email protected]")
Index NextChar NumDots NumAts NumOthers
0 0 0
1 ‘J’

(ii) State the value returned when function Check is called as shown in part (b)(i).
..................................................................................................................................... [1]
(c) The function Check() is to be tested.
State two different invalid string values that could be used to test the algorithm. Each string should
test a different rule.
Justify your choices.
Value .........................................................................................................................................
Justification ...............................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
Value .........................................................................................................................................
Justification ...............................................................................................................................
...................................................................................................................................................
................................................................................................................................................... [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 200

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 201

Examiner Report Question 4


(a) This question required an explanation of the line of code:
IF (NumDots != 1 AND NumAts = 1 AND NumOthers !5).
Many candidates gave clear and correct explanations and gained full credit. Candidates needed to recognise
what the three variables in the expression represented in order to gain full credit. Some responses were vague,
simply describing the term validation or stating that the rules check that the data is valid.
(b) (i) Many candidates correctly traced the code. Many of these candidates did not include the quotes around
NextChar to indicate that it is a character (not a variable). Some candidates missed out the first three
statements, which initialise the three variables to zero.
(b) (ii)Most candidates recognised that the return value was TRUE.
(c) Most candidates recognised that the strings being tested must be correct for two of the validation rules and
must only fail on one of them. These candidates’ explanations were mostly very clear. A common error was to
provide test strings that failed more than one rule.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 202
5 Abbreviations are often used in place of a full name. Concatenating the first letter of each word in
the name makes an abbreviation.
For example:
Name Abbreviation
United Nations UN
World Wide Web WWW
British Computer Society BCS

A function, Abbreviate(), will take a string representing the full name and return a string containing the
abbreviated form.
You should assume that:
• names only contain alphabetic characters and space characters
• names always start with an alphabetic character
• each word in the name always starts with an uppercase character
• only a single space separates words in the name.
Write pseudocode to implement the function Abbreviate().
Refer to the Appendix on page for the list of built-in functions and operators. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 203

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 204
11a Summer 20 P21
3 (a) A mobile phone provider has developed an account management program. The program includes a
procedure, AddCredit(). The procedure is called with two parameters, TopUp and PhoneNum.
The relevant part of the identifier table and the program flowchart for the procedure are as shown:

Identifier Type Description


TopUp REAL The amount of credit to be added
PhoneNum STRING The unique customer phone number
Balance REAL The current amount of credit
Multiple REAL The amount of credit bonus
Takes the phone number as a parameter and returns the current
GetBalance() FUNCTION
balance
Takes the phone number and the new balance as parameters and
SetBalance() PROCEDURE
updates the account with the new balance

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 205
Write pseudocode to implement the procedure AddCredit(). The pseudocode must follow the algorithm
represented by the flowchart. Declare any local variables used. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 206
6 A company hires out rowing boats on a lake. The company has ten boats, numbered from 1 to 10.
The company is developing a program to help manage and record the hiring out process.
Hire information is stored in three global 1D arrays when a boat is hired out. Each array contains 10 elements
representing each of the ten boats.
The three 1D arrays are summarised as follows:
Example data
Array Data type Description
value
HireTime STRING The time the boat was hired out "10:15"
Duration INTEGER The number of minutes of the hire 30
Cost REAL The cost of the hire 5.75

If an individual boat is not currently on hire, the corresponding element of the HireTime array will be set to
"Available".
The programmer has started to define program modules as follows:

Module Description
• Called with two parameters:
o a STRING value representing a time
AddTime() o an INTEGER value representing a duration in minutes
• Adds the duration to the time to give a new time
• Returns the new time as a STRING
• Called with a STRING value representing the time the hire will start
• Outputs the boat numbers that will be available for hire at
the given start time. A boat will be available for hire if it is either:
ListAvailable() o currently not on hire, or
o due back before the given hire start time
• Outputs the number of each boat available
• Outputs the total number of boats available or a suitable message if there are none
• Called with four parameters:
o an INTEGER value representing the boat number
o a STRING value representing the hire start time
o an INTEGER value representing the hire duration in minutes
RecordHire() o a REAL value representing the cost of hire
• Updates the appropriate element in each array
• Adds the cost of hire to the global variable DailyTakings
• Converts the four input parameters to strings, concatenated using commas as separators,
and writes the resulting string to the end of the existing text file HireLog.txt

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 207
(a) Write pseudocode for the module ListAvailable(). [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 208
(b) Write pseudo code for the module RecordHire(). [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 209
(c) The module description of AddTime()is repeated here for reference.
Module Description
• Called with two parameters:
o a STRING value representing a time
AddTime() o an INTEGER value representing a duration in minutes
• Adds the duration to the time to give a new time
• Returns the new time as a STRING
(i) Write program code for a statement that uses the AddTime() function to add a duration of 60 minutes to a
start time contained in variable BeginTime and to assign the new time to variable EndTime.
Programming language .....................................................................................................
Program code [2]

(ii) The function AddTime() is to be tested using black-box testing.


Complete the following two tests that can be performed to check the operation of the function. Note that test 1
and test 2 are different.
Test 1 – Boat is returned during the same hour as rental starts
Start time value ....................................... Duration value .......................................
Expected new time value .......................................

Test 2 – Boat is returned during the hour after the rental starts
Start time value ....................................... Duration value .......................................
Expected new time value ....................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 210

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 211

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 212

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 213

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 214

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 215

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 216
Summer 2016 P21-22
3 A string encryption function is needed. The encryption uses a simple character-substitution
method.
In this method, a new character substitutes for each character in the original string. This will
create the encrypted string.
The substitution uses the 7-bit ASCII value for each character. This value is used as an index
for a1D array, Lookup, which contains the substitute characters.
Lookup contains an entry for each of the ASCII characters. It may be assumed that the
original string and the substitute characters are all printable.
For example:
• ‘A’ has ASCII value 65
• Array element with index 65 contains the character ‘Y’ (the substitute character)
• Therefore, ‘Y’ substitutes for ‘A’
• There is a different substitute character for every ASCII value
The programmer writes a function, EncryptString, to return the encrypted string. This function
will receive two parameters, the original, PlainText string and the 1D array.
(a) The first attempt at writing the pseudocode for this function is shown below.
Complete the pseudocode.
For the built-in functions list, refer to the Appendix on page 18.
FUNCTION EncryptString(.............................) RETURNS STRING
DECLARE .................... , ...................... : CHAR
DECLARE OldCharValue : ......................................
DECLARE n : INTEGER
DECLARE OutString : STRING
.............................. //initialise the return string
//loop through PlainText to produce OutString
FOR n Å1 TO ................. //from first to last character
OldCharÅ ...................//get next character
OldCharValueÅ ..............//find the ASCII value
NewCharÅ ...................//look up substitute character
.............................//concatenate to OutString
NEXT n
.............................................................
ENDFUNCTION [10[

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 217

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 218
Winter 2016 P22
A typical input character sequence, stored as InputString is:
13*156*9*86*1463*18*#
Study this pseudocode.
01 DECLARE Numbers ARRAY [1:100] OF INTEGER
02 DECLARE InputString : STRING
03 DECLARE NextChar : CHAR
04 DECLARE NextNumberString : STRING
05 DECLARE i : INTEGER // Numbers array index
06 DECLARE j : INTEGER // InputString index
07
08 OUTPUT "String ... "
09 INPUT InputString
10 j Å1
11 NextCharÅONECHAR(InputString, j)
12
13 i Å1
14 WHILE NextChar<> '#'
15 NextNumberString = ""
16 WHILE NextChar<> '*'
17 NextNumberStringÅNextNumberString&NextChar
18 j Åj + 1
19 NextCharÅONECHAR(InputString, j)
20 ENDWHILE
21
22 // store the next integer to the array
23 Numbers[i]Å TONUM(NextNumberString)
24 iÅi + 1
25 jÅj + 1
26 NextCharÅ ONECHAR(InputString, j)
27 ENDWHILE
28
29 CALL DisplayArray()

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 219
(b) Write the line number for:
(i) A statement which declares a global variable used to store a single character. ........... [1]
(ii) A statement which runs code written as a procedure. ........... [1]
(iii) A statement which indicates the start of a ‘pre-condition’ loop. ........... [1]
(iv) A statement which increments a variable. ........... [1]
(c) Copy the condition which is used to control the inner loop.
.............................................................................................................................................. [1]
(d) (i) Complete the trace table below for the given pseudocode as far as line 27.
The input string is: 23*731*5*# [5]
Numbers
i j NextChar NextNumberString
1 2 3
1 1 '2'
""
"2"
2 '3' "23"
3 '*' 23

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 220

(ii) Explain what this algorithm does.


...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 221

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 222
Summer 2017 P22
3 A string conversion function, ExCamel, needs to be written.
This function forms a return string, OutString, from a given string, InString, by:
1 separating the original words (a word is assumed to start with a capital letter)
2 converting all characters to lower case.
The following shows a pair of example values for the string values InString and OutString.
InString : "MyUserInput"
OutString : "my user input"
You may assume that InString always starts with a capital letter.
The following is a first attempt at writing the pseudocode for this function.
Complete the pseudocode using appropriate built-in functions.
For the built-in functions list, refer to the Appendix.
FUNCTION ExCamel (………………............................) RETURNS ................................
DECLARE NextChar : .......................................................
DECLARE .............................................................. : STRING
DECLARE n: INTEGER
............................................................ // initialise the return string
// loop through InString to produce OutString
FOR nÅ1 TO ............................................... // from first to last
NextChar .......................................... // get next character
IF ..................................................... // check if upper case
THEN
IF n > 1 // if not first character
THEN
……………..................................... // add space to OutString
ENDIF
……….......................................................... // make NextChar lower
case
ENDIF
................................................. // add NextChar to OutString
NEXT n
............................................ // return value
ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 223

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 224
Summer 2019 P21
4 The following pseudocode is a string handling function.
FUNCTION Clean(InString : STRING) RETURNS STRING
DECLARE NewString : STRING
DECLARE Index : INTEGER
DECLARE AfterSpace : BOOLEAN
DECLARE NextChar : CHAR
CONSTANT Space = ' '
AfterSpaceÅFALSE
NewStringÅ""
FOR Index Å1 TO LENGTH(InString)
NextCharÅMID(InString, Index, 1)
IF AfterSpace = TRUE
THEN
IF NextChar<> Space
THEN
NewStringÅNewString&NextChar
AfterSpaceÅFALSE
ENDIF
ELSE
NewStringÅNewString&NextChar
IF NextChar = Space
THEN
AfterSpaceÅTRUE
ENDIF
ENDIF
NEXT
RETURN NewString
ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 225
(a) (i) Complete the trace table by performing a dry run of the function when it is called as
follows:
Result ÅClean("X‫׏׏׏‬Y‫׏‬and‫׏׏‬Z")
The symbol '‫ '׏‬represents a space character. Use this symbol to represent a space character
in the trace table. [6]
Index AfterSpace NextChar NewString

(ii) State the effect of the function Clean().


...........................................................................................................................................
..................................................................................................................................... [1]
(iii) The pseudocode is changed so that the variable AfterSpace is initialised to TRUE.
Explain what will happen if the function is called as follows:
ResultÅ Clean("‫׏׏‬X‫׏׏׏‬Y‫׏‬and‫׏׏‬Z")
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 226
Summer 2019 P22
4 The following is pseudocode for a string handling function.
For the built-in functions list, refer to the Appendix.
FUNCTION Search(InString : STRING) RETURNS INTEGER
DECLARE NewString : STRING
DECLARE Index : INTEGER
DECLARE NextChar : CHAR
DECLARE Selected : INTEGER
DECLARE NewValue : INTEGER
NewStringÅ'0'
Selected Å 0
FOR Index Å1 TO LENGTH(InString)
NextCharMID(InString, Index, 1)
IF NextChar< '0' OR NextChar> '9'
THEN
NewValueÅSTRING_TO_NUM(NewString)
IF NewValue> Selected
THEN
Selected ÅNewValue
ENDIF
NewStringÅ'0'
ELSE
NewStringÅNewString&NextChar
ENDIF
NEXT
RETURN Selected
ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 227
(a) (i) The following assignment calls the Search() function:
ResultÅSearch("12‫׏‬34‫׏‬5‫׏׏‬39")
Complete the following trace table by performing a dry run of this function call.
The symbol '‫ '׏‬represents a space character. Use this symbol to represent a space character
in the trace table.
[5]
Index NextChar Selected NewValue NewString

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 228

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 229
11a Summer 20 P21
2 (a) Three modules form part of a program for a car rental company. A description of the relationship between
the modules is summarised as follows:
Module name Description
A customer will pay for each car rental either by bank card or by using their account with the
RentCar()
rental company.
Called with parameter HireCost, representing the cost of the rental.
PayByCard()
Returns a BOOLEAN value to indicate whether or not the card payment was successful.
Called with parameters HireCost, AccountNumber, CurrentBalance and ccountLimit.
• Checks whether HireCost plus the CurrentBalance would exceed the AccountLimit. If so,
PayByAccount() then the rental is not authorised.
• If the rental is authorised, then the CurrentBalance is updated.
• Returns a BOOLEAN value to indicate whether or not the rental was authorised.
Draw a structure chart to show the relationship between the three modules and the parameters passed between
them.[5]
(b) The following pseudocode algorithm has been developed to check whether a string contains a valid
password.
To be a valid password, a string must:
• be longer than 6 characters
• contain at least one lower case letter
• contain at least one upper case letter
• contain at least one non-alphabetic character.
10 FUNCTION Check(InString : STRING) RETURNS BOOLEAN
11
12 DECLARE Index : INTEGER
13 DECLARE StrLen : INTEGER
14 DECLARE NumUpper, NumLower : INTEGER
15 DECLARE NumNonAlpha : INTEGER
16 DECLARE NextChar : CHAR
17
18 NumUpper ← 0
19 NumLower ← 0
20 NumNonAlpha ← 0
21
22 StrLen ← LENGTH(InString)
23 IF StrLen < 7
24 THEN
25 RETURN FALSE
26 ELSE
27 FOR Index← 1 TO StrLen
28 NextChar ← MID(InString, Index, 1)
29 IF NextChar >= 'a' AND NextChar <= 'z'
30 THEN
31 NumLower ← NumLower + 1
32 ELSE
33 IF NextChar > 'A' AND NextChar <= 'Z'
34 THEN
35 NumUpper ← NumUpper + 1

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 230
36 ELSE
37 NumNonAlpha ← NumNonAlpha + 1
38 ENDIF
39 ENDIF
40 NEXT Index
41 ENDIF
42
43 IF (NumUpper >= 1) AND (NumLower >= 1) AND (NumNonAlpha >= 1)
44 THEN
45 RETURN TRUE
46 ELSE
47 RETURN FALSE
48 ENDIF
49
50 ENDFUNCTION
The pseudocode does not work under all circumstances.
A dry run performed on the function Check(), with the string "crAsh99", produced the following trace table.
The string is a valid password, but the pseudocode would return the value FALSE.

Trace
StrLen Index NextChar NumUpper NumLower NumNonAlpha
table row
1 7 0 0 0
2 1 'c'
3 1
4 2 'r'
5 2
6 3 'A'
7 1
8 4 's'
9 3
10 5 'h'
11 4
12 6 '9'
13 2
14 7 '9'
15 3

(i) Describe how the completed trace table may be used to identify the error in the pseudocode. In your answer,
refer to the trace table row number(s).
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 231
(ii) State the pseudocode line number that has to be changed to correct the error and write the correct
pseudocode for the complete line.
Line number ......................................................................................................................
Correct pseudocode ..........................................................................................................
........................................................................................................................................... [2]
(iii) Rewrite lines 29 to 39 of the original pseudocode using a CASE structure.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 232
..................................................................................................................................... [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 233

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 234
10 Data Types and Structures
ͳͲǤͳ‡ ‘”†ƒ–ƒ›’‡
Candidates should be able to: Notes and guidance
Show understanding of the purpose of a record Write pseudocode to define a record structure.
structure to hold a set of data of different data Write pseudocode to read data from a record
types under one identifier structure and save data to a record structure
Data types:
A data type is a classification that specifies which type of data a variable has and what type
of operations can be applied to it.
Most programming languages support various types of data, including integer, real, character
or string, and Boolean.
Before a variable can be used in a program, the variable’s data type has to be identified.
Built-in data types
Remember, for each built-in data type:
• The programming language defines the range of possible values that can be assigned to a
variable when its type has been chosen.
• The programming language defines the operations that are available for manipulating
values assigned to the variable.
User-defined data types
The term ‘user’ is regularly applied to someone who is provided with a ‘user interface’ by an
operating system – the ‘user’ is the person supplying input to a running program and receiving
output from it.
However, when writing a program, a programmer becomes a ‘user’ of a programming
language. The term user-defined data type applies to this latter type of user.
A user-defined data type is a data type for which the programmer has included the definition
in the program. Once the data type has been defined, variables can be created and
associated with the user-defined data type. Note that, although the user-defined data type is
not a built-in data type, using the user-defined data type is only possible if a programming
language offers support for the construct.
There are two types of user defined data types:
1. Composite Data Type
2. Non-Composite Data Type

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 235
1. Composite user-defined data types
A composite user-defined data type has a definition with reference to at least one other type.
There are two very important examples of composite user-defined data type.
i. Record
ii. Class
i. The record data type.
Although there could be built-in record data types the expectation is for a record data type to
be user-defined. This allows the programmer to create record data types with components
that precisely match the data requirements of the particular program. Note that Python is a
language that does not support the use of a record data type.
Definition of Record Data Type:
Syntax:
TYPE <Record Data Type Identifier>
DECLARE <Identifier> : <Data Type>
DECLARE <Identifier> : <Data Type>
….
END TYPE
Example: to create a record data type Student
TYPE TStudent
DECLARE RollNo : STRING
DECLARE Name : STRING
DECLARE Class : STRING
DECLARE Marks : ARRAY[1:6] OF REAL
END TYPE
Declaring variable of Record Data Type:
Syntax of creating record data type variable:
DECLARE <Identifier > : <Record Data Type>
Example:
DECLARE ALevel : TStudents
Assigning values:
ALevel.RollNo Å “1012”
ALevel.Name Å “Ahmed”

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 236
Input from user:
INPUT ALevel.RollNo
INPUT ALevel.Name
INPUT ALevel.Class
FOR Count Å 1 TO 6
INPUT ALevel.Marks[Count]
NEXT Count
Output on screen
OUTPUT ALevel.RollNo
OUTPUT ALevel.Name
OUTPUT ALevel.Class
FOR Count Å 1 TO 6
OUTPUT ALevel.Marks[Count]
NEXT Count
Arrays of User Defined data type:
Arrays can also be declared from user defined data types. Here is an example of arrays of
100, including declaration, input and output.
TYPE TStaff
DECLARE StaffID: STRING
DECLARE Name : STRING
DECLARE BasicPay : REAL
END TYPE
DECLARE AdminStaff : ARRAY[1:100] OF TStaff
FOR Count Å 1 TO 100
INPUT AdminStaff[Count].StaffID
INPUT AdminStaff[Count].Name
INPUT AdminStaff[Count].BasicPay
NEXT Count
FOR Count Å 1 TO 100
PRINT AdminStaff[Count].StaffID
PRINT AdminStaff[Count].Name
PRINT AdminStaff[Count].BasicPay
NEXT Count

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 237
Q 1) Specimen Paper
5 A company keeps details of its product items in a 1D array, Stock. The array consists of
1000 elements of type StockItem.
The record fields of StockItem are:
Field Typical value
ProductCode "BGR24-C"
Price 102.76
NumberInStock 15
(a) Write pseudocode to declare the record structure StockItem.
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [3]
(b) Write pseudocode to declare the Stock array.
...................................................................................................................................................
.............................................................................................................................................. [3]
(c) Write pseudocode to modify the values to element 20 as follows:
• set the price to 105.99
• increase the number in stock by 12
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [2]
(d) A stock report program is developed.
Write pseudocode to output the information for each stock item that has a price of at least
100. Output the information as follows:
Product Code: BGR24-C Number in Stock: 15
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 238

S15 Paper 33
4 (a) A particular programming language allows the programmer to define their own data
types.
An example of a user-defined data type for an address is:
TYPE ThisAddress
DECLARE ThisHouseNo : INTEGER
DECLARE ThisStreet : STRING
DECLARE ThisTown : STRING
ENDTYPE
A variable of this new type is declared as follows:
DECLARE HomeAddress : ThisAddress
Write the statement that assigns the house number 34 to HomeAddress.
.......................................................................................................................................[1]
Write the statement that input street and town and stores in HomeAddress.
.......................................................................................................................................[1]
(b) Temperature data from a number of weather stations are to be processed by a program.
The following data are to be stored:
• weather station ID (a unique four-letter code)
• latitude (to 2 decimal places)
• average temperature (to the nearest whole number) for each year from 2001 to 2015
inclusive

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 239
A programmer designs a composite data type WeatherStation. A variable of this type can be
used to store all the data for one particular station.
(i) Write the definition for the user-defined data type WeatherStation.

...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[5]

Q 2) S17 Paper 32
1 (a) Consider the following pseudocode user-defined data type:
TYPE MyContactDetail
DECLARE Name : STRING
DECLARE HouseNumber : INTEGER
ENDTYPE
(i) Write a pseudocode statement to declare a variable, NewFriend, of type MyContactDetail.
.......................................................................................................................................[1]
(ii) Write a pseudocode statement that assigns 129 to the HouseNumber of NewFriend.
.......................................................................................................................................[1]
9618 S21 P21
1 (c) The following data items need to be stored for each student in a group:
• student name (a string)
• test score (an integer).
State a suitable data structure and justify your answer.
Structure ...................................................................................................................................
Justification ...............................................................................................................................
...................................................................................................................................................
................................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 240
Q 4) 9618 W21 P21
3 A programmer is writing a program to help manage clubs in a school.
Data will be stored about each student in the school and each student may join up to three
clubs.
The data will be held in a record structure of type Student.
The programmer has started to define the fields that will be needed as shown in the following
table.
Field Typical value Comment
StudentID "CF1234" Unique to each student
Email "[email protected]" Contains letters, numbers and certain symbols
Club_1 1 Any value in the range 1 to 99 inclusive
Club_2 14 Any value in the range 1 to 99 inclusive
Club_3 27 Any value in the range 1 to 99 inclusive
(a) (i) Write pseudocode to declare the record structure for type Student.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [3]
(ii) A 1D array Membership containing 3000 elements will be used to store the student data.
Write pseudocode to declare the Membership array.
...........................................................................................................................................
..................................................................................................................................... [2]
(iii) Some of the elements of the array will be unused.
Give an appropriate way of indicating an unused array element.
...........................................................................................................................................
..................................................................................................................................... [1]
(iv) Some students are members of less than three clubs.
State one way of indicating an unused club field.
...........................................................................................................................................
..................................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 241
(b) A procedure GetIDs() will:
• prompt and input the number of a club.
• output the StudentID of all the students who are members of that club.
• output a count of all students in the given club.
Write pseudocode for the procedure GetIDs().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 242

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 243

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 244
3c 9618 S22 P23
5 A program will store attendance data about each employee of a company.
The data will be held in a record structure of type Employee. The fields that will be needed
are as shown:
Field Typical value Comment
EmployeeNumber 123 A numeric value starting from 1
Name "Smith,Eric" Format: <last name>','<first name>
Department "1B" May contain letters and numbers
Born 13/02/2006 Must not be before 04/02/1957
Attendance 97.40 Represents a percentage
(a) (i) Write pseudocode to declare the record structure for type Employee.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
......................................................................... [4]

(ii) A 1D array Staff containing 500 elements will be used to store the employee records.
Write pseudocode to declare the Staff array.
.....................................................................................................................................................
........................................................................................................................... [2]
(b) There may be more records in the array than there are employees in the company. In this
case, some records of the array will be unused.
(i) State why it is good practice to have a standard way to indicate unused array elements.
.....................................................................................................................................................
........................................................................................................................... [1]
(ii) Give one way of indicating an unused record in the Staff array.
.....................................................................................................................................................
........................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 245
(c) A procedure Absentees() will output the EmployeeNumber and the Name of all employees
who have an Attendance value of 90.00 or less.
Write pseudocode for the procedure Absentees().
Assume that the Staff array is global.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 246

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 247
10.2 Arrays: Data Structure 
Syllabus requirements
The Cambridge International AS & A Level syllabus (9618) requires candidates to understand
and use both one-dimensional and two-dimensional arrays.
Activity: Fill in given data in following data structures:

1st student name is Abdullah and he has obtained 90, 80 and 95 marks, calculate and store total and
average in appropriate locations.
2nd student name is Rumaisa and she has obtained 90, 90, and 80 marks, calculate and store total
and average in appropriate locations.
Enter your name as 3rd student and your marks, calculate and store total and average in appropriate
locations.
Enter name and marks of your friends, calculate and store total and average in appropriate locations.
Calculate and store ClassAverage, ClassHeight and ClassLowest

Write down locations for following data items


Name of your 1st friend: ……………………………………………………….
All exam marks of your 1st friend: …………………………….…………………………
Total and average marks of your 1st friend: ……..………………………………………………..
Write pseudo code statements to output
Your name: ……………………..……………………………………………………….
Your all exam marks: ……………………..…………………………….…………………………
……………………..…………………………….…………………………
……………………..…………………………….…………………………

Your total and average marks: ……..……………………………………………………………….


……..……………………………………………………………….
……..……………………………………………………………….
……..……………………………………………………………….

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 248
Arrays
Arrays are data structure used to store multiple data items of same data type under one identifier
name.
Arrays are considered to be fixed-length structures of elements of identical data type, accessible by
consecutive index (subscript) numbers. It is good practice to explicitly state what the lower bound of
the array (i.e. the index of the first element) is because this defaults to either 0 or 1 in different
systems. Generally, a lower bound of 1 will be used.
Square brackets are used to indicate the array indices.
Each element in the array is identified using its subscript or index number. The largest and smallest
index numbers are called the upper bound and lower bound of the array.
Example
StudentName[30] StudentName[1:30] StudentName[0:29]

For illustration, let's take array declaration to store marks of 10 students.


Marks[10] Marks[1:10] Marks[0:9]
After storing values in array

As per the above illustration, following are the important points to be considered.
x Index starts with 1.
x Array length is 10 which means it can store 10 elements.
x Each element can be accessed via its index. For example, we can fetch an element at index 6
as 19.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 249
Declaring arrays
Arrays are considered to be fixed-length structures of elements of identical data type, accessible by
consecutive index (subscript) numbers. It is good practice to explicitly state what the lower bound of
the array (i.e. the index of the first element) is because this defaults to either 0 or 1 in different
systems.
Generally, a lower bound of 1 will be used.
Square brackets are used to indicate the array indices.
A One-dimensional array is declared as follows:
DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>
A two-dimensional array is declared as follows:
DECLARE <identifier> : ARRAY[<lower1>:<upper1>,<lower2>:<upper2>] OF
<data type>

Example – array declaration


DECLARE StudentNames : ARRAY[1:30] OF STRING
DECLARE NoughtsAndCrosses : ARRAY[1:3,1:3] OF CHAR
Using arrays
Array index values may be literal values or expressions that evaluate to a valid integer value.
Example – Accessing individual array elements
StudentNames[1] ← "Ali"
NoughtsAndCrosses[2,3] ← ꞌXꞌ
StudentNames[n+1] ← StudentNames[n]
Arrays can be used in assignment statements (provided they have same size and data type). The
following is therefore allowed:

Example – Accessing a complete array


SavedGame ← NoughtsAndCrosses
A statement should not refer to a group of array elements individually. For example, the following
construction should not be used.
StudentNames [1 TO 30] ← ""

Instead, an appropriate loop structure is used to assign the elements individually. For example:
The terms associated with Arrays
Name: The identifier of the array is called Array Name. E.g. StudentName[]
Element: Each data item stored in arrayis called element. Array can store only single types of
elements.
Size: The number elements the array can store. E.g. StudentName[1:30] can store 30 names while
StudentName[30] can store 31 names as by default it is 0 to 30.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 250
Index: The position of each element is referred as Index Number. Index of Abdullah in array example
is 1.
Type: Data type of all elements in a single array have same data types.
Dimension: Dimension is the organisational structure of array. It may be 1D that has single index or
2D that has two indices.
Traversing an Array: To traverse an array means to access each element (item) stored in the array
so that the data can be checked or used as part of a process.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 251
1D Array:
An array with single index is referred as 1D Array. It may consist of a single row or a single column.
To Declare 1D Array only upper and lower bound of rows or columns are mentioned.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 252
A One-dimensional array is declared as follows:
DECLARE <identifier> : ARRAY[<lower>:<upper>] OF <data type>
Example - To declare 1D Array to store 30 name of type string
DECLARE StudentName[1:30] : STRING

Using arrays
Array index values may be literal values or expressions that evaluate to a valid integer value.
Example – Accessing individual array elements
StudentNames[1] ← "Ali"
StudentNames[n+1] ← StudentNames[n]

Example - To input and store data in specific location in arrays like at 20:
INPUT Name[20]
Example – assigning a group of array elements
FOR Index ← 1 TO 30
StudentNames[Index] ← ""
NEXT Index
Example - To input and store values in whole arrays
FOR Index Å 1 TO 30
INPUT Name[Index]
NEXT Index
Example -To output content of specific location line 20
OUTPUT Name[20]
Example - To output all contents of arrays
FOR Index Å 1 TO 30
OUTPUT Name[Index]
NEXT Index

Arrays can be used in assignment statements (provided they have same size and data type). The
following is therefore allowed:
Example – Accessing a complete array
SavedGame ← NoughtsAndCrosses
A statement should not refer to a group of array elements individually. For example, the following
construction should not be used.
StudentNames [1 TO 30] ← ""
Instead, an appropriate loop structure is used to assign the elements individually. For example:

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 253
Example – assigning a group of array elements
FOR Index ← 1 TO 30
StudentNames[Index] ← ""
NEXT Index
Arrays in Python
Different programming languages have different statements for initialising the array but they
all do the same thing. In Python List is used as Arrays and declaration statement is:
Name = [“ “] * 30
This statement declares:
● the identifier name is Name
● the lower bound is 0 while upper bound is 29, means 30 is not inclusive
● the data type is String. [“”] for string, [0] for int, [0.0] for float(real), [True] or [False]
for boolean
The upper bound of 29 specifies that there can be a maximum of 30 data items, since
Python starts with a subscript of zero. We do not have to fill the array; the upper bound
of 30 indicates the maximum size.
The array that has been described is one-dimension array so far is really only a list of single
data items. It is possible to have an array which can be visualised as a two-dimensional table
with rows and columns and a data value in each cell.
Reading data into an array
To assign data values to the elements of the array, we do this with assignment statements
such as:
Name[6] = “Patel”
This places the string “Patel” at index position 6 in the array.
Similarly, the following statement places the string “Rashid” at index position 3 in the array.
Name[3] = “Rashid”


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 254
Linear Search
Linear Search - is a method in which each element of the array is checked in
order, from the lower bound to the upper bound, until the item is found or the
upper bound is reached.
For example, to search marks in an 1D array Marks[1:30], user has to input data to be
searched. Algorithm compares this search data with all elements of the array, starting from
lower bound. If search data matches with the element then it displays the location of data first
found and if data is not found, it is searched at next location in the conditional loop until the
data is found or it reaches at the upper bound.
Example Code for Single Searching using Linear Search
DECLARE SearchData: REAL
DECLARE Found: BOOLEAN
DECLARE MaxIndex : INTEGER
INPUT SearchData
Found Å FALSE
MaxIndex Å 30
Index Å 1
WHILE Index <=30 AND Found = FALSE
IF SearchData = Marks[Index]
THEN
Found Å TRUE
ELSE
Index Å Index + 1
ENDIF
ENDWHILE
IF Found = TRUE
THEN
OUTPUT “Found at”, Index
ELSE
OUTPUT “Not found”
ENDIF

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 255
Example Code for Multiple Searching, using Linear Search
To search and output all locations where the search data is found, a count controlled
loop is used instead of conditional loop.
DECLARE SearchData: REAL
DECLARE Found: BOOLEAN
DECLARE MaxIndex : INTEGER
INPUT SearchData
Found Å FALSE
FOR Index Å 1 TO 30
IF SearchData = Marks[Index]
THEN
Found Å TRUE
OUTPUT Index
ENDIF
NEXT Index
IF Found = FALSE
THEN
OUTPUT “not found.”
ENDIF

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 256
Bubble sort – is a method of sorting data in an array into alphabetical or
numerical order by comparing adjacent items and swapping them if they are in
the wrong order.
Each element of the array is compared with the next element and swapped if the elements
are in the
wrong order, starting from the lower bound and finishing with the element next to the upper
bound. The element at the upper bound is now in the correct position. This comparison is
repeated with one less element in the list, until there is only one element left or no swaps are
made.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 257

DELCARE Swapped: BOOLEAN


DECLARE MaxIndex, UpperBound: INTEGER
DELCARE Temp: INTEGER
Swapped Å TRUE
UpperBound Å 5
MaxIndex Å UpperBound - 1
WHILE Swapped = TRUE
Swapped Å FALSE
FOR Index Å 1 TO MaxIndex
IF Marks[Index] > Marks[Index + 1]
THEN
Temp Å Marks[Index]
Marks[Index] Å Marks[Index + 1]
Marks[Index + 1] Å Temp
Swapped Å TRUE
ENDIF
NEXT Index
MaxIndex Å MaxIndex – 1
ENDWHILE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 258
2D Arrays
An array that has two indices is known as 2D arrays.
In 2D arrays data is stored in many rows and columns. There is need of two indices, one for
row and other for columns. Like:

TestMarks[] is an 1D Array, as it has only one index (i.e. for rows)


ExamMarks[] is a 2D Array, as it has two indices, one index for rows, and the second one for
column.
2D arrays are accessed using two nested loops.
The outer loop is for rows. The loop counter is mostly ‘J’ or Row.
The inner loop is for columns. The loop counter is mostly ‘K’ or Column.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 259
Work Example:
Write down pseudo code that:
Declare a 2D arrays ExamMarks to store marks of 5 students in 3 subjects.
Input and store marks in the arrays
Output the marks.
DECLARE ExamMarks : ARRAYS[1:5, 1:3] OF REAL
DECLARE Row, Column : INTEGER

FOR Row Å 1 TO 5
FOR Column Å 1 TO 3
INPUT ExamMarks[Row, Column]
NEXT Column
NEXT Row

FOR Row Å 1 TO 5
FOR Column Å 1 TO 3
PRINT ExamMarks[Row,Column]
NEXT Column
NEXT Row

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 260
Assignment
Q 1a) Declare an array called Marks whose index values ranges from 0 to 999 and whose
element type is integer

..........................................................................................................................................[1]

DECLARATION means assign memory location for variable, array or identifier


INITIALISATION means storing 1st value in them before they are being manipulated

b) Initialise the array declared in part a, all values in the array should be equals to 0.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
......................................................................................................................................... [2]
Q 2) Consider the following code:
DECLARE NextChar : ARRAY[1:30] OF CHAR

Write a code to store the letter ‘A’ at 1st and ‘Z’ at 26th location of the Array.

.....................................................................................................................................................
.................................................................................................................................... [2]
Q3a) Write a pseudo code that uses an array to store marks of 10 students of a class. Enter
marks of each student. After input all the marks output the list of marks.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
..........................................................................................................................................[4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 261
b) Calculate the average marks of the class by traversing the array.

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.................................................................. [3]
c) Output the smallest and the greatest marks of the class by traversing the array.

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.......................................................................................... [3]
d) Create a second array to input and store name of students of the class. Output the list of
name of students and their marks by traversing the two arrays. At the end of list print average
marks of the class.

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................... [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 262
Q 4a) Write a program to input name and telephone of your friends in two one dimension
arrays. Each array can store up to 5 elements.

................................................................................................................
.............................................................................................................. Name[1:5] Tel[1:5]
1 1
.................................................................................................................
2 2
................................................................................................................ 3 3
............................................................................................................... 4 4
5 5
...............................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.........................................[3]

b) Write a program to display 1st and 3rd telephone number stored in array.
.....................................................................................................................................................
....................……….............................................................................................................. [2]

c) Write a program to print list of all telephone numbers stored in array.


.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...................................................... [3]
d) Write a program that inputs the name of your friend search in the array and output
telephone number.

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 263
e) After the user selects a name, give him option to display and change the telephone number
in the array. After change of telephone number, output the entire list.

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
......................................................................................................[4]
Q 5a ) Declare an array to input and store 5 integers from user. Then Num1[1:5] Num2[1:5]
declare another array and copy data items from 1st array into 2nd 1 75 1 75
array. 2 89 2 89
............................................................................................................ 3 45 3 45
............................................................................................................ 4 67 4 67
5 88 5 88
............................................................................................................
.................. .........................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.......................................................[3]
Q 5b ) Declare 3rd array and copy data items from 1st array into 3rd array in reverse order.
............................................................................................................. Num1[1:5] Num3[1:5]
.............................................................................................................. 1 75 1 88
............................................................................................................... 2 89 2 67
3 45 3 45
..............................................................................................................
4 67 4 89
............................................................................................................... 5 88 5 75
...............................................................................................................
......................……………………………………………………………………………………………
………………………….................................................................................................................
................................................................................................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 264
Q 6) An array has 10 integers. Create two new arrays and copy 1st 5 integers from 1st array
into 2nd array and last integers in 3rd array.
Num1[1:10] Num2[1:5]
..........................................................................................................
1 75 1 75
......................................................................................................... 2 89 2 89
......................................................................................................... 3 45 3 45
4 67 4 67
........................................................................................................
5 88 5 88
.......................................................................................................... 6 90 Num3[1:5]
.......................................................................................................... 7 50 1 90
8 80 2 50
..........................................................................................................
9 20 3 80
......................................................................................................... 10 30 4 20
......................................................................................................... 5 30
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
....... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 265
Random Number Generator
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 (any number between 0 and 86.9999)
To create generate a number between 1 to 10
RAND (10) generates a number between 0 to 9.999999 for example 7.6754
1 will be added in this generated value to obtain numbers between 1 and 10.99999
(RAND(10)+1)
Then this number is converted into integer using INT Functions, so the range become between 1
and 10.
INT(RAND(10) + 1)

Q 7a) Write pseudocode to show how the RAND() function can be used to generate a single
integer in the range 1 to 150.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...................................................... [3]
b) Write an algorithm to generate and store 10 random integers between 1 to 50 in a 1D array
MyNum[ ].
...................................................................................................................................................................
.....................................................................
....................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.................................................................[4]
c) Declare another array NewNum[] to store 10 integers then store random numbers between
1 to 50 in the array using RAND() functions. All random numbers must be unique.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 266
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................... [4]
d) Generate 200 number between 1 and 10 inclusive. Count and output how many times each number
has occurred. Use Array Frequency[1:10] to keep track of occurrence of each number.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
..............................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.........................................................................[4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 267
6b 9608 W17 P22
4 Programming languages provide built-in functions to generate random numbers.
To be truly random, the frequency of each number generated should be the same.
You are required to write program code to test the random number generator of your chosen
language.
The test should:
o generate a given number of random numbers between 1 and 10 inclusive
o keep a count of the number of times each number is generated
o calculate the expected frequency of each number 1 to 10
o output the actual frequency of each number 1 to 10
o output the difference between the actual frequency and the expected frequency.
The program code should be written as a procedure. In pseudocode, the procedure heading will be:
PROCEDURE TestRandom(Repetitions AS INTEGER)
The parameter, Repetitions, contains a value representing the total number of random numbers that
should be generated.
The following example shows the expected output for the procedure call, TestRandom(200).
The expected frequency is 20.
Number Frequency Difference
1 17 -3
2 21 1
3 12 -8
4 28 8
5 20 0
6 19 -1
7 21 1
8 16 -4
9 24 4
10 22 2

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 268
(a) Write program code for the procedure, TestRandom.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
......................................................................................................................................................... [16]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 269
Assignment Answer Key
Q 1a) Declare an array called Marks whose index values ranges from 0 to 999 and whose element type
is integer
DECLARE Marks: ARRAY[0:999] OF INTEGER [1]
b) Initialise the array declared in part a, all values in the array should be equals to 0. [2]
DECLARE Index : INTEGER
FOR Index Å 0 TO 999
Marks[Index] Å 0
NEXT Index
Q 2) Consider the following code:
DECLARE NextChar : ARRAY[1:30] OF CHAR
Write a code to store the letter ‘A’ at 1st and ‘Z’ at 26th location of the Array.
NextChar[1] Å ‘A’
NextChar[26] Å ‘Z’ [2]
Q3a) Write a pseudo code that uses an array to store marks of 10 students of a class. Enter marks of
each student. After input all the marks output the list of marks.
DECLARE Index : INTEGER
FOR Index Å 1 TO 30
INPUT Marks[Index]
NEXT Index
FOR Index Å 1 TO 30
OUTPUT Marks[Index]
NEXT Index [4]
b) Calculate the average marks of the class by traversing the array.

DECLARE Sum, Average : REAL


Sum Å 0
FOR Index Å 1 TO 30
Sum Å Sum + Marks[Index]
NEXT Index
Average Å Sum / 30
PRINT Sum, Average [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 270
c) Output the smallest and the greatest marks of the class by traversing the array. [3]
DECLARE Smallest, Greatest: INTEGER
Smallest Å 9999
Greatest Å 0
FOR Index Å 1 TO 30
IF Marks[Index]> Greatest THEN Greatest Å Marks[Index]
IF Marks[Index] < Smallest THEN Smallest Å Marks[Index]
NEXT Index
OUTPUT Greatest, Smallest
d) Create a second array to input and store name of students of the class. Output the list of
name of students and their marks by traversing the two arrays. At the end of list print average
marks of the class. [4]
DECLARE Name: ARRAY[1:30] OF STRING
FOR Index Å 1 TO 30
INPUT Name[Index]
NEXT Index
FOR Index Å 1 TO 30
PRINT Name[Index], Marks[Index]
NEXT Index
Q 4a) Write a program to input name and telephone of your friends Name[1:5] Tel[1:5]
in two one dimension arrays. Each array can store up to 5
1 Abc 1 123
elements. [3]
2 Pqr 2 124
DECLARE Name : ARRAY[1:5] OF STRING 3 Lmn 3 125
DECLARE Tel : ARRAY[1:5] OF STRING 4 Asd 4 432
DECLARE Count : INTEGER 5 Jkl 5 433

FOR Count Å 1 TO 5
INPUT Name[Count], Tel[Count]
NEXT Count

b) Write a program to display 1st and 3rd telephone number stored in array. [2]
OUTPUT Tel[1], Tel[3]

c) Write a program to print list of all telephone numbers stored in array. [3]
FOR Count Å 1 TO 5
OUTPUT Tel[Count]
NEXT Count


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 271
d) Write a program that inputs the name of your friend search in the array and output telephone
number. [3]

DECLARE Found: BOOLEAN


DECLARE SearchName: STRING
INPUT SearchName
FOR Count Å 1 TO 5
IF SearchName=Name[Count]
THEN
OUTPUT Tel[Count]
Found Å True
ENDIF
NEXT Count
IF Found = False
THEN
PRINT “Not Found”
ENDIF

e) After the user selects a name, give him option to display and change the telephone number in the
array. After change of telephone number, output the entire list.

DECLARE Choice : STRING


INPUT SearchName
FOR Count Å 1 TO 5
IF SearchName=Name[Count]
THEN
OUTPUT Tel[Count]
PRINT “Do you want to change it (Yes/No)”
INPUT Choice
IF Choice=TRUE
THEN
PRINT “Enter new telephone number”
INPUT Tel[Count]
ENDIF
Found Å True
ENDIF
NEXT Count
IF Found = False
THEN
PRINT “Not Found”
ENDIF
FOR Count Å 1 TO 5
PRINT Name[Count], Tel[Count]
NEXT Count [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 272
Q 5a ) Declare an array to input and store 5 integers from user. Then declare Num1[1:5] Num2[1:5]
another array and copy data items from 1st array into 2nd array. 1 75 1
2 89 2
DECLARE Num1 : ARRAY[1:5] OF INTEGER
3 45 3
DECLARE Num2 : ARRAY[1:5] OF INTEGER
4 67 4
DECLARE Count : INTEGER
5 88 5

FOR Count Å 1 TO 5
INPUT Num1[Count]
NEXT Count
FOR Count Å 1 TO 5
Num2[Count] Å Num1[Count]
NEXT Count [3]
st rd
Q 5b ) Declare 3rd array and copy data items from 1 array into 3 array in reverse order.
DECLARE Num3 : ARRAY[1:5] OF INTEGER
Num1[1:5] Num3[1:5]
Count3 Å 5 1 75 1 88
FOR Count Å 1 TO 5 2 89 2 67
3 45 3 45
Num3[Count3] Å Num1[Count]
4 67 4 89
Count3=Count3-1 5 88 5 75
NEXT Count
Q 6) An array has 10 integers. Create two new arrays and copy 1st 5 integers from 1st array into 2nd
array and last 5 integers in 3rd array. Num1[1:10] Num2[1:5]
DECLARE Num2 : ARRAY[1:5] OF INTEGER 1 75 1 75
DECLARE Num3 : ARRAY[1:5] OF INTEGER 2 89 2 89
3 45 3 45
FOR CountÅ 1 TO 5
4 67 4 67
Num2[Count] Å Num1[Count] 5 88 5 88
Num3[Count] Å Num1[Count+5] 6 90 Num3[1:5]
7 50 1 90
NEXT Count [3]
8 80 2 50
9 20 3 80
10 30 4 20
5 30
Q 7a) Write pseudocode to show how the RAND() function can be
used to generate a single integer in the range 1 to 150. [3]
INT(RAND(150)+1)

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 273
b) Declare an array to store 10 integers then store random numbers between 1 to 50 in the
array using RAND() functions. [4]
DECLARE Num : ARRAY[1:10] OF INTEGER
DECLARE Count : INTEGER
FOR Count Å 1 TO 10
Num[Count] Å INT(RAND(50)+1)
NEXT Count
c) Write a program to declare another array to store 10 integers then store random numbers
between 1 to 50 in the array using RAND() functions. All random numbers must be unique.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
.............................................................................................................................................................[4]
Q 8) John works in a supermarket, where he is given a task to find which item has the highest
price and which item has the lowest price. There are 900 items in the supermarket.
Declare suitable arrays to store name and price of each product.
Input price of each product with its name.
Output the number of items which have a price greater than 100and number of items which
have price less than 50. Output the highest and the lowest price.
…………………………….............................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.............................................................................................................................................. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 274
2b 9618 W21 P22
(b) The following pseudocode assigns a value to an element of an array:
ThisArray[n] ← 42
Complete the following table by writing the answer for each row. [3]
Answer
The number of dimensions of ThisArray
The technical terms for minimum and maximum values that the
variable n may take
The technical term for the variable n in the pseudocode statement
1a 9618 S21 P21
5 A global 2D array Result of type INTEGER is used to store a list of exam candidate
numbers together with their marks. The array contains 2000 elements, organised as 1000
rows and 2 columns. Column 1 contains the candidate number and column 2 contains the
mark for the corresponding candidate. All elements contain valid exam result data.
A procedure Sort() is needed to sort Result into ascending order of mark using an efficient
bubble sort algorithm. Write pseudocode for the procedure Sort().
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 275
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
........................................................................................................................... [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 276
9618 S 21 P22
5 (a) A student is learning about arrays.
She wants to write a program to:
• declare a 1D array RNum of 100 elements of type INTEGER
• assign each element a random value in the range 1 to 200 inclusive
• count and output how many numbers generated were between 66 and 173 inclusive.
(i) Write pseudocode to represent the algorithm.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.............................................................................................................................................. [6]
(ii) The student decides to modify the algorithm so that each element of the array will contain
a unique value.
Describe the changes that the student needs to make to the algorithm.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
........................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 277
(b) The following is a pseudocode function.
Line numbers are given for reference only.
01 FUNCTION StringClean(InString : STRING) RETURNS STRING
02
03 DECLARE NextChar : CHAR
04 DECLARE OutString : STRING
05 DECLARE Counter : INTEGER
06
07 OutString Å “ “
08
09 FOR Counter 1 TO LENGTH(InString)
10 NextChar Å MID(InString, Counter, 1)
11 NextChar Å LCASE(NextChar)
12 IF NOT((NextChar < 'a') OR (NextChar > 'z')) THEN
13 OutString Å OutString & NextChar
14 ENDIF
15 NEXT Counter
16
17 RETURN OutString
18
19 ENDFUNCTION
(i) Examine the pseudocode and complete the following table. [4]
Answer
Give a line number containing an example of an initialisation statement.
Give a line number containing the start of a repeating block of code.
Give a line number containing a logic operation.
Give the number of parameters to the function MID().

(ii) Write a simplified version of the statement in line 12.


...........................................................................................................................................
..................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 278
9618 W21 P23
2 (a) An algorithm to sort a 1D array into ascending order is described as follows:
• move the largest value to the end
• keep repeating until the array is sorted.
Apply the process of stepwise refinement to this algorithm in order to produce a more detailed
description. Write the more detailed description using structured English. Your explanation of
the algorithm should not include pseudocode statements.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 279
(b) The program flowchart shown describes a simple algorithm.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 280
Write pseudocode for the simple algorithm shown on previous page.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................. [6]

Summer 2019 P21

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 281
5 (a) Programming languages usually contain a range of built-in functions, such as a random
number generator.
State three advantages of using built-in functions.
1 ................................................................................................................................................
2 ................................................................................................................................................
3 ............................................................................................................................................. [3]
(b) A student is learning about random number generation.
She is investigating how many times the random function needs to be called before every
number in a given series is generated.
She is using pseudocode to develop a procedure, TestRand(), which will:
• use the random number function to generate an integer value in the range 1 to 50 inclusive
• count how many times the random function needs to be called before all 50 values have
been generated
• output a message giving the number of times the random function was called.
Write pseudocode for the procedure TestRand(). [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 282

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 283
Q 8) John works in a supermarket, where he is given a task to find which item has the highest
price and which item has the lowest price. There are 900 items in the supermarket.
Declare suitable arrays to store name and price of each product.
Input price of each product with its name.
Output the number of items which have a price greater than 100 and number of items which
have price less than 50.
Output the highest and the lowest price.
…………………………………………………….............................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................ [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 284
Q 1) Summer 2015 P21, 22
5 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 (using variable SalesX) and
Site Y (using variable SalesY).
Data for the first 28 days is shown below.

(a) Name the data structure to be used in a program for SalesX.


...............................................................................................................................................[2]
(b) The programmer writes a program from the following pseudocode design.
x Å 0
FOR DayNumberÅ1 TO 7
IF SalesX[DayNumber] + SalesY[DayNumber] >= 10
THEN
X ÅX + 1
OUTPUT SalesDate[DayNumber]
ENDIF
NEXT dayNumber
OUTPUT x

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 285
Trace the execution of this pseudocode by completing the trace table below. [4]
x DayNumber OUTPUT
0

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 286
5 A program is to process a set of integers.
The integers are stored in an array, Num. The first N elements are to be processed.
The pseudocode for this program is shown below:
FOR i ← 1 TO (N - 1)
j ← 1
REPEAT
IF Num[j] >Num[j + 1]
THEN
Temp ← Num[j]
Num[j] ← Num[j + 1]
Num[j + 1] ← Temp
ENDIF
j ← j + 1
UNTIL j = (N – i + 1)
NEXT i
(a) (i) Trace the execution of the pseudocode for the value N = 5 and the given array of
integers.[8]
Num
N i J Temp 1 2 3 4 5
5 11 16 13 7 8
1 1

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 287
(ii) State the purpose of the algorithm.
.............................................................................................................................................[1]
(iii) Describe what evidence from the trace table suggests that the given pseudocode is
inefficient.
..............................................................................................................................................[1]
(b) Complete the identifier table documenting the use of each of the variables. [5]
Identifier Data type Description
Num ARRAY[1:100] OF INTEGER The array of numbers.
N
i
J
Temp

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 288
Q 2) 9608 S 15 P23
5 A firm employs workers who assemble amplifiers. Each member of staff works an agreed
number of hours each day.
The firm records the number of completed amplifiers made by each employee each day.
Management monitor the performance of all its workers.
Production data was collected for 3 workers over 4 days.
Daily Hours Production data
Worked Worker 1 Worker 2 Worker 3
Worker 1 5 Day 1 10 20 9
Worker 2 10 Day 2 11 16 11
Worker 3 10 Day 3 10 24 13
Day 4 14 20 17

A program is to be written to process the production data.


(a) The production data is to be stored in a 2-dimensional array ProductionData, declared as
follows:
DECLARE ProductionDataARRAY[1:4, 1:3] : INTEGER
(i) Describe two features of an array.
1 ........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
.......................................................................................................................................[2]
(ii) Give the value of ProductionData[3, 2].
.......................................................................................................................................[1]
(iii) Describe the information produced by the expression:
ProductionData[2, 1] + ProductionData[2, 2] + ProductionData[2, 3]
...........................................................................................................................................
.......................................................................................................................................[2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 289
(b) Complete the trace table for the pseudocode algorithm below.
FOR WorkerNumÅ 1 TO 3
WorkerTotal[WorkerNum] Å 0
NEXT WorkerNum
FOR WorkerNumÅ1 TO 3
FOR DayNumÅ1 TO 4
WorkerTotal[WorkerNum]ÅWorkerTotal[WorkerNum] +ProductionData[DayNum, WorkerNum]
NEXT DayNum
NEXT WorkerNum
FOR WorkerNumÅ 1 TO 3
WorkerAverageÅWorkerTotal[WorkerNum]/(4 * DailyHoursWorked[WorkerNum])
IF WorkerAverage< 2 THEN
OUTPUT “Investigate“, WorkerNum
ENDIF
NEXT WorkerNum [8]
WorkerTotal
1 2 3
WorkerNum DayNum WorkerAverage OUTPUT

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 290

(c) An experienced programmer suggests that the pseudocode would be best implemented
as a procedure AnalyseProductionData.
Assume that both arrays, DailyHoursWorked and ProductionData, are available to the
procedure from the main program and they are of the appropriate size.
PROCEDURE AnalyseProductionData(NumDays : INTEGER, NumWorkers : INTEGER)
DECLARE .............................................
DECLARE .............................................
DECLARE .............................................
DECLARE .............................................
FOR WorkerNumÅ1 TO 3
WorkerTotal[WorkerNum] Å0
NEXT WorkerNum
FOR WorkerNumÅ 1 TO 3
FOR DayNumÅ1 TO 4
WorkerTotal[WorkerNum]ÅWorkerTotal[WorkerNum]+ProductionData[DayN
um, WorkerNum]
NEXT DayNum
NEXT WorkerNum
FOR WorkerNumÅ1 TO 3
WorkerAverageÅWorkerTotal[WorkerNum]/(4 * DailyHoursWorked[WorkerNum])
IF WorkerAverage< 2
THEN
OUTPUT "Investigate", WorkerNum
ENDIF
NEXT WorkerNum
ENDPROCEDURE
(i) Complete the declaration statements showing the local variables.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 291
(ii) The original pseudocode has been ‘pasted’ under the procedure header.
Circle all the places in the original pseudocode where changes will need to be made.
Write the changes which need to be made next to each circle. [3]
(iii) Write the statement for a procedure call which processes data for 7 days for 13 workers.
.......................................................................................................................................[1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 292

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 293
Summer 2016 P21-22
3 A string encryption function is needed. The encryption uses a simple character-substitution
method.
In this method, a new character substitutes for each character in the original string. This will
create the encrypted string.
The substitution uses the 7-bit ASCII value for each character. This value is used as an index
for a1D array, Lookup, which contains the substitute characters.
Lookup contains an entry for each of the ASCII characters. It may be assumed that the
original string and the substitute characters are all printable.
For example:
• ‘A’ has ASCII value 65
• Array element with index 65 contains the character ‘Y’ (the substitute character)
• Therefore, ‘Y’ substitutes for ‘A’
• There is a different substitute character for every ASCII value
The programmer writes a function, EncryptString, to return the encrypted string. This function
will receive two parameters, the original, PlainText string and the 1D array.
(a) The first attempt at writing the pseudocode for this function is shown below.
Complete the pseudocode.
FUNCTION EncryptString(.............................) RETURNS STRING
DECLARE .................... , ............... : CHAR
DECLARE OldCharValue : ..........................
DECLARE n : INTEGER
DECLARE OutString : STRING
........................ //initialise the return string
//loop through PlainText to produce OutString
FOR n Å1 TO ................. //from first to last character
OldCharÅ ...................//get next character
OldCharValueÅ ..............//find the ASCII value
NewCharÅ ...................//look up substitute character
.............................//concatenate to OutString
NEXT n
.............................................................
ENDFUNCTION [10]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 294
(b) Additional code needs to be written to allow the user to change some of the characters in
the array Lookup.
The user will input:
• the array start position
• the number of elements to change
• each new substitute character
At the end, the program will finally output a confirmation message.
The first version of the algorithm is represented by the flowchart on the following page.
(i) Write pseudo code to declare the array Lookup.
(ii) Write program code to implement the flowchart design.
In addition to the Lookup array, assume that the following variables have been declared:
StartPos, NumToChange, n, NewChar [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 295

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 296

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 297

Winter 2017 P22


2 A 1D array, ClassName, of type STRING contains 100 elements.
The following pseudocode represents a simple algorithm to process the array.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 298
DECLARE SearchValue : STRING
DECLARE FoundFlag : BOOLEAN
DECLARE Index : INTEGER
INPUT SearchValue
FoundFlagÅ FALSE
Index Å1
WHILE Index < 101 AND FoundFlag = False
IF ClassName[Index] = SearchValue
THEN
OUTPUT Index
FoundFlagÅ TRUE
ENDIF
Index ÅIndex + 1
ENDWHILE
IF FoundFlag = FALSE
THEN
OUTPUT "Not found"
ENDIF
(a) Describe the purpose of the algorithm.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 299
(b) Draw a program flowchart to represent this algorithm.
Note that variable declarations are not required in program flowcharts. [9]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 300
Winter 2017 P22
3 A 1D array, Product, of type STRING is used to store information about a range of products
in a shop. There are 100 elements in the array. Each element stores one data item.
The format of each data item is as follows:
<ProductID><ProductName>
• ProductID is a four-character string of numerals
• ProductName is a variable-length string
The following pseudocode is an initial attempt at defining a procedure, ArraySort, which will
perform a bubble sort on Product. The array is to be sorted in ascending order of ProductID.
Line numbers have been added for identification purposes only.
01 PROCEDURE SortArray
02 DECLARE Temp : CHAR
03 DECLARE FirstID, SecondID : INTEGER
04 FOR I Å 1 TO 100
05 FOR JÅ 2 TO 99
06 FirstIDÅMODULUS(LEFT(Product[J], 6))
07 SecondIDÅMODULUS(LEFT(Product[J + 1], 6))
08 IF FirstID>SecondID
09 THEN
10 Temp ÅProduct[I]
11 Product[I] ÅProduct[J + 1]
12 Product[J + 1] ÅTemp
13 NEXT
14 ENDIF
15 NEXT
16 ENDPROCEDURE

The pseudocode on page 8 contains a number of errors. Complete the following table
to show:
• the line number of the error
• the error itself
• the correction that is required.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 301
Note:
• If the same error occurs on more than one line, you should only refer to it ONCE.
• Lack of optimisation should not be regarded as an error. [8]
Line
Error Correction
number
01 Wrong procedure name – “SortArray” PROCEDURE ArraySort

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 302

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 303
Summer 2018 P23
4 A program controls a chemical process in a factory.
The temperature is monitored as part of the control process. The temperature is measured at
fixed time intervals and the value is stored in an array, PTemp. The array contains 100
elements, representing 100 temperature values. The first element is PTemp[1].
The program will check whether the temperature is outside the acceptable range more than
20times. This task is performed by a function, IsTempOK().
The algorithm for the function IsTempOK() is expressed in structured English as follows:
1. Examine each array element and count the number of times that a temperature is less
than
MinTemp or more than MaxTemp.
2. If the count in step 1 exceeds 20, return FALSE, otherwise return TRUE.
Draw a program flowchart, on the next page, to represent the algorithm for the
functionIsTempOK().
Assume:
x the array contains 100 valid temperature values
x PTemp, MinTemp and MaxTemp are global variables.
Note that variable declarations are not required in program flowcharts.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 304
8b 9608 Winter 2018 P22
3 (c) A program needs to search through 1000 elements of an unsorted array to find a given
value.
The program will output:
• either the position in the array of the value
• or the message “Not Found”
Outline the steps the program needs to follow. Do not write pseudocode or program code.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...................................................................................................[4]
Key points:
A loop / repetition / iteration to check every element
3(c) Compare the array element with the value being searched 4
Exit loop / stop search when value found or end of array reached
If value is found then output the index position, otherwise output “Not found”

(d) ResultArray is a 1D array of type STRING. It contains 100 elements.


Write pseudo code to declare ResultArray and set all elements to the value "NO DATA".
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 305
Summer 2019 P21
3 (a) A student is developing an algorithm to search through a 1D array of 100 elements.
Each element of the array, Result, contains a REAL value.
The algorithm will output:
• the average value of all the elements
• the number of elements with a value of zero.
The structured English description of the algorithm is:
1. SET Total value to 0
2. SET Zero count to 0
3. SELECT the first element
4. ADD value of element to Total value
5. IF element value is 0 then INCREMENT Zero count
6. REPEAT from step 4 for next element, until element is last element
7. SET Average to Total / 100
8. OUTPUT a suitable message and Average
9. OUTPUT a suitable message and Zero count
Write pseudocode for this algorithm.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]
(b) The student decides to change the algorithm and implement it as a procedure,
ScanArray(), which will be called with three parameters.
ScanArray(AverageValue, ZeroCount, ArrayName)
ScanArray() will modify the first two parameters so that the new values are available to the
calling program or module. Write the pseudocode procedure header for ScanArray().
............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 306
4 The following pseudocode is a string handling function.
FUNCTION Clean(InString : STRING) RETURNS STRING
DECLARE NewString : STRING
DECLARE Index : INTEGER
DECLARE AfterSpace : BOOLEAN
DECLARE NextChar : CHAR
CONSTANT Space = ' '
AfterSpaceÅFALSE
NewStringÅ""
FOR Index Å1 TO LENGTH(InString)
NextCharÅMID(InString, Index, 1)
IF AfterSpace = TRUE
THEN
IF NextChar<> Space
THEN
NewStringÅNewString&NextChar
AfterSpaceÅFALSE
ENDIF
ELSE
NewStringÅNewString&NextChar
IF NextChar = Space
THEN
AfterSpaceÅTRUE
ENDIF
ENDIF
NEXT Index
RETURN NewString
ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 307
(a) (i) Complete the trace table by performing a dry run of the function when it is called as
follows:
Result ÅClean("X‫׏׏׏‬Y‫׏‬and‫׏׏‬Z")
The symbol '‫ '׏‬represents a space character. Use this symbol to represent a space character
in the trace table. [6]
Index AfterSpace NextChar NewString

(ii) State the effect of the function Clean().


.....................................................................................................................................................
.............................................................................................................................................. [1]
(iii) The pseudocode is changed so that the variable AfterSpace is initialised to TRUE.
Explain what will happen if the function is called as follows:
ResultÅ Clean("‫׏׏‬X‫׏׏׏‬Y‫׏‬and‫׏׏‬Z")
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................................................ [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 308

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 309

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 310
10a Winter 2019 p21
4 (b) Write pseudocode to implement the program.
You should note the following:
• InString contains the string to be checked. It has been assigned a value.
• The elements of the array Result have all been initialised to zero.
• The ASCII value of letter ‘A’ is 65.
You should assume the following lines of pseudocode have been written:
DECLARE InString : STRING
DECLARE Result : ARRAY [1:26] OF INTEGER
Declare any further variables you use. Do not implement the code as a subroutine.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.............................................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 311

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 312
5 The following pseudocode checks whether a string is a valid password.
FUNCTION CheckPassword (InString : STRING) RETURNS BOOLEAN
DECLARE Index, Upper, Lower, Digit, Other : INTEGER
DECLARE NextChar : CHAR
Upper ← 0
Lower ← 0
Digit ← 0
Other ← 0
FOR Index ← 1 TO LENGTH(InString)
NextChar ← MID(InString, Index, 1)
IF NextChar >= 'A' AND NextChar <= 'Z'
THEN
Upper ← Upper + 1
ELSE
IF NextChar >= 'a' AND NextChar <= 'z'
THEN
Lower ← Lower + 1
ELSE
IF NextChar >= '0' AND NextChar <= '9'
THEN
Digit ← Digit + 1
ELSE
Other ← Other + 1
ENDIF
ENDIF
ENDIF
NEXT Index
Ԝ ԜԜԜ IF Upper>1AND Lower>=5 AND (Digit-Other)>0
THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION
(a) Describe the validation rules that are implemented by this pseudocode. Refer only to the
contents of the string and not to features of the pseudocode.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 313
(b) (i) Complete the trace table by dry running the function when it is called as follows: [5]
Result ← CheckPassword("Jim+Smith*99")

Index NextChar Upper Lower Digit Other

(ii) State the value returned when the function is called using the expression shown. Justify
your answer.
Value .................................................................................................................................
Justification .......................................................................................................................
...........................................................................................................................................
........................................................................................................................................... [2]

11a Summer 20 P21

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 314
5 (a) A 1D array, Directory, of type STRING is used to store a list of school internal telephone numbers. There
are 1000 elements in the array. Each element stores a single data item. The format of each data item is as
follows:
<Number><Name>
Number is a four-digit numeric string.
Name is a variable-length string.
For example:
"1024Collins Robbie"
The following pseudocode is an initial attempt at defining a procedure SortContacts() that will perform a bubble
sort on Directory. The array is to be sorted in ascending order of Name.
Fill in the gaps to complete the pseudocode.
PROCEDURE SortContacts ()
DECLARE Temp : STRING
DECLARE FirstName, SecondName : STRING
DECLARE NoSwaps : ……………………………………
DECLARE Boundary, J : INTEGER
Boundary ← ……………………
REPEAT
NoSwaps ← TRUE
FOR J ← 1 TO Boundary
FirstName ← …………………………(Directory[J], LENGTH(Directory[J]) –
…………… )
SecondName ← RIGHT(Directory[J + 1], LENGTH(Directory[J + 1])
– 4)
IF FirstName ………………………………
THEN
Temp ← Directory[J]
Directory[J] ← Directory ……………………………
Directory[J + 1] ← Temp
NoSwaps ← ……………………………
ENDIF
NEXT J
Boundary ← ……………………………
UNTIL NoSwaps = TRUE
ENDPROCEDURE [8]
(b) The pseudocode contains a mechanism designed to make this an efficient bubble sort.
Describe the mechanism and explain why it may be considered to be efficient.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 315
6 A company hires out rowing boats on a lake. The company has ten boats, numbered from 1
to 10.
The company is developing a program to help manage and record the hiring out process.
Hire information is stored in three global 1D arrays when a boat is hired out. Each array
contains 10 elements representing each of the ten boats.
The three 1D arrays are summarised as follows:
Array Data type Description Example data value
HireTime STRING The time the boat was hired out "10:15"
Duration INTEGER The number of minutes of the hire 30
Cost REAL The cost of the hire 5.75
If an individual boat is not currently on hire, the corresponding element of the HireTime array
will be set to "Available".
The programmer has started to define program modules as follows:

Module Description
• Called with two parameters:
o a STRING value representing a time
AddTime() o an INTEGER value representing a duration in minutes
• Adds the duration to the time to give a new time
• Returns the new time as a STRING
• Called with a STRING value representing the time the hire will start
• Outputs the boat numbers that will be available for hire at
the given start time. A boat will be available for hire if it is either:
o currently not on hire, or
ListAvailable()
o due back before the given hire start time
• Outputs the number of each boat available
• Outputs the total number of boats available or a suitable message if there are
none
• Called with four parameters:
o an INTEGER value representing the boat number
o a STRING value representing the hire start time
o an INTEGER value representing the hire duration in minutes
o a REAL value representing the cost of hire
RecordHire()
• Updates the appropriate element in each array
• Adds the cost of hire to the global variable DailyTakings
• Converts the four input parameters to strings, concatenated using commas as
separators, and writes the resulting string to the end of the existing text file
HireLog.txt

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 316
(a) Write pseudocode for the module ListAvailable().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 317
(b) Write pseudo code for the module RecordHire().

...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................
[7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 318
(c) The module description of AddTime()is repeated here for reference.
Module Description
• Called with two parameters:
o a STRING value representing a time
AddTime() o an INTEGER value representing a duration in minutes
• Adds the duration to the time to give a new time
• Returns the new time as a STRING
(i) Write program code for a statement that uses the AddTime() function to add a duration of
60 minutes to a start time contained in variable BeginTime and to assign the new time to
variable EndTime.
...........................................................................................................................................
.....................................................................................................................................
[2]
(ii) The function AddTime() is to be tested using black-box testing.
Complete the following two tests that can be performed to check the operation of the function.
Note that test 1 and test 2 are different.
Test 1 – Boat is returned during the same hour as rental starts
Start time value ....................................... Duration value
.......................................
Expected new time value .......................................

Test 2 – Boat is returned during the hour after the rental starts
Start time value ....................................... Duration value
.......................................
Expected new time value .......................................
[2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 319

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 320

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 321

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 322

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 323
10.3 File Handling
Syllabus outline:

10.3 Files
• show understanding of why files are needed
• Write pseudocode to handle text files that consist of one or more lines
Text File Functions
EOF(FileName : STRING) RETURNS BOOLEAN
returns TRUE if there are no more lines to be read from file FileName
The function will generate an error if the file is not already open in READ mode.

https://www.bbc.co.uk/bitesize/guides/zb3yb82/revision/6
Handling text files
Text files consist of lines of text that are read or written consecutively as strings.
Why files are needed?
Files are used to store data permanently.
When a program is being executed data is stored in variables, constants, arrays, lists etc.
These data structures use RAM, making them temporary. While files stores data in
secondary storage devices like HDD or SSD. These are permanent and non-volatile. They
retain data even after computer is switched OFF, so the data can be accessed next time
program is run. Data can be used by more than one program. Data can be backed-up. It can
be transferred be transferred from one place to another, from one system to another.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 324
A file must be opened in a specified mode before any file operations are attempted. This is
written as follows:
OPENFILE <File identifier> FOR <File mode>
The file identifier may be a literal string containing the file names, or a variable of type
STRING that has been assigned the file name.
File Modes: Following are file mode:
x READ for data to be read from the file
x WRITE for data to be written to the file. A new file will be created and any existing
data
in the file will be lost.
x APPEND for data to be added to the file, after any existing data.
A file should be opened in only one mode at a time.
WRITE MODE: To create a new text file and write data in it
To create a new text file, firstly it is opened in WRITE mode, data is written in it and then it is
closed. If file is already existing, new file will be created and all existing data will be lost.
Syntax to create a new text file:
OPENFILE <File name> FOR WRITE
WRITEFILE <File name>, <String Variable to be written>
CLOSEFLE <File name>
For example, to store a name “Inqilab Patel” in a text file Teachers.txt, firstly “Inqilab Patel” is
stored in a string variable and then file is opened and variable is stored at the end of file.
OPENFILE “Teachers.txt” FOR WRITE
WRITEFILE “Teachers.txt”, Name
CLOSEFILE “Teachers.txt”
To input and store name of 5 teachers in a text file “Teachers.txt”.
OPENFILE “Teachers.txt” FOR WRITE
FOR Count Å 1 TO 5
INPUT Name
WRITEFILE “Teachers.txt”, Name
NEXT Count
CLOSEFILE “Teachers.txt”

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 325
APPEND MODE: To add data in existing file
If a file is already created, new data can be added in it.
To add data in existing file, firstly it is opened in APPEND mode, data is written in it and then
it is closed. New data is added at the end of the file.
Syntax to add data in existing file:
OPENFILE <File name> FOR APPEND
WRITEFILE <File name>, <String variable to be written>
CLOSEFLE <File name>
For example, to add a name “Abdullah Patel” in a text file Teachers.txt, firstly it is stored in a
string variable then file is opened and variable is stored at the end of file.
OPENFILE “Teachers.txt” FOR APPEND
WRITEFILE “Teachers.txt”, Name
CLOSEFILE “Teachers.txt”
To input and store name of 5 more teachers in a text file “Teachers.txt”.
OPENFILE “Teachers.txt” FOR APPEND
FOR Count Å 1 TO 5
INPUT Name
WRITEFILE “Teachers.txt”, Name
NEXT Count
CLOSEFILE “Teachers.txt”

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 326
READ MODE: To display contents of text file
To display contents of a text file, firstly it is opened in READ mode, data is read one line at a
time into a temporary variable and displayed on screen, then next line is read until it reaches
End Of File (EOF) marker. Then files is closed.
Syntax to read first line from text file:
OPENFILE <File name> FOR READ
READFILE <File name>, <String Variable to store content>
OUTPUT <String Variable>
CLOSEFLE <File name>
For example to read 1st line from text file Teachers.txt and to store in a variable “TextLine”
OPENFILE “Teachers.txt” FOR READ
READFILE “Teachers.txt”, TextLine
PRINT TextLine
CLOSEFILE “Teachers.txt”
To read all contents of text file “Teachers.txt”.
OPENFILE “Teachers.txt” FOR READ
WHILE NOT EOF(“Teachers.txt”) DO
READFILE “Teachers.txt”, TextLine
OUTPUT TextLine
ENDWHILE
CLOSEFILE “Teachers.txt”

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 327
EOF() Function
The function EOF() is used to test whether there are any more lines to be read from a given
file. It is called as follows:
EOF(<File Identifier>)
This function returns TRUE if there are no more lines to read (or if an empty file has been
opened in READ mode) and FALSE otherwise.
Data is written into the file (after the file has been opened in WRITE or APPEND mode) using
the
WRITEFILE command as follows:
WRITEFILE <File identifier>, <data>
Files should be closed when they are no longer needed using the CLOSEFILE command as
follows:
CLOSEFILE <File identifier>

Example – file handling operations


This example uses the operations together, to copy all the lines from FileA.txt to FileB.txt,
replacing any blank lines by a line of dashes.
DECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR READ
OPENFILE "FileB.txt" FOR WRITE
WHILE NOT EOF("FileA.txt")
READFILE "FileA.txt", LineOfText
IF LineOfText = " "
THEN
WRITEFILE "FileB.txt", "---"
ELSE
WRITEFILE "FILEB.txt", LineOfText
ENDIF
ENDWHILE
CLOSEFILE "FileA.txt"
CLOSEFILE "FileB.txt"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 328
Pseudo code and Python Code
A file must be open before a record can be read from or written to it. To open a file, it must be
referred to by its identifier, for example:
Pseudo code Python
OPENFILE "test.txt" FOR WRITE FileHandle = open ("test.txt", "w")
OPENFILE "test.txt" FOR FileHandle = open ("test.txt", "a")
APPEND
OPENFILE "test.txt" FOR READ FileHandle = open ("test.txt", "r")

Once all the data has been written to a file, the file must be closed otherwise the file contents
will not be saved.
Pseudo code Python
Sytax CLOSEFILE <filename> FileHandle.close()
Example CLOSEFILE "Test.txt" FileHandle.close()

Writing to file
Pseudo code Python

Syntax OPENFILE <filename> FOR WRITE FileHandle = open (<FileName> , "w" )


WRITEFILE <filename> <stringvalue> FileHandle.write(<StringValue>)
CLOSEFILE <filename> FileHandle.close()
Example OPENFILE "test.txt" FOR WRITE FileHandle = open ("test.txt" , "w" )
WRITEFILE “test.txt”, TextLine FileHandle.write(TextLine)
CLOSEFILE “test.txt” FileHandle.close()

To input name of 10 students and to write in students.txt file:


Pseudo code Python
OPENFILE “Student.txt” FOR WRITE file = open ("students.txt", “w”)
FOR Count ← 1 TO 10 for Count in range(10):
INPUT Name
Name=str(input(“Enter next name: “))
WRITEFILE “Student.txt”, Name
NEXT Count file.write(Name + "\n")
CLOSEFILE “Student.txt” file.close()
"\n" is used as end of line marker in Python

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 329
Reading from a file
Pseudo code Python
Syntax OPENFILE <filename> FOR READ FileHandle = open (<FileName>, "r" )
READFILE <filename> <StringVariable>=FileHandle.readline()
<StringVariable> FileHandle.close()
CLOSEFILE <filename>
Example OPENFILE "test.txt" FOR READ FileHandle = open ("test.txt" , "r" )
READFILE “test.txt”, TextLine FileHandle.write(TextLine)
CLOSEFILE “test.txt” FileHandle.close()

End of file- EOF()


OPENFILE "Test .txt" FOR READ
WHILE NOT EOF("Test.txt")
READFILE "Test. txt", TextString
OUTPUT TextString
ENDWHILE
CLOSEFILE "Test. txt
In Python there is no explicit EOF() function . However, when a line of text has been read that
only consists of the end-of-file marker, the line of text is of length 0.
FileHandle = open ("Test.txt" , "r" )
LineOfText = FileHandle.readline()
while len(LineOfText) > 0:
LineOfText = FileHandle.readline()
print(LineOfText)
FileHandle.close()

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 330
Specimen Paper (Copying data from Array into File)
7 LogArray is a 1D array containing 500 elements of type STRING.
A procedure, LogEvents, is required to add data from the array to the end of the existing text
file LoginFile.txt
Unused array elements are assigned the value "Empty". These can occur anywhere in the
array and should not be added to the file.
Write pseudocode for the procedure LogEvents.

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................ [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 331

1ac 9618 S21 P21


3 (a) A concert venue uses a program to calculate admission prices and store information
about ticket sales.
A number of arrays are used to store data. The computer is switched off overnight and data
has to be input again at the start of each day before any tickets can be sold. This process is
very time consuming.
(i) Explain how the program could use text files to speed up the process.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [2]
(ii) State the characteristic of text files that allow them to be used as explained in part (a)(i).
...........................................................................................................................................
..................................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 332
(iii) Information about ticket sales will be stored as a booking. The booking requires the
following data:
• name of person booking
• number of people in the group (for example a family ticket or a school party)
• event type.
Suggest how data relating to each booking may be stored in a text file.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [2]
(b) A procedure Preview() will:
• take the name of a text file as a parameter
• output a warning message if the file is empty
• otherwise output the first five lines from the file (or as many lines as there are in the file if
this number is less than five).
Write pseudocode for the procedure Preview().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................ [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 333

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 334
3b 9618 s22p22
4 (a) A procedure LastLines() will:
• take the name of a text file as a parameter
• output the last three lines from that file, in the same order as they appear in the file.
Note:
• Use local variables LineX, LineY and LineZ to store the three lines from the file.
• You may assume the file exists and contains at least three lines.
Write pseudocode for the procedure LastLines().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 335
(b) The algorithm in part (a) is to be amended. The calling program will pass the number of
lines to be output as well as the name of the text file.
The number of lines could be any value from 1 to 30.
It can be assumed that the file contains at least the number of lines passed.
Outline three changes that would be needed.
1 ................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
...................................................................................................................................................
................................................................................................................................................ [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 336

4(b) One mark per point to Max 3: 3


1 Change the procedure header to include a (numeric) parameter (as well as the filename)
2 Replace LineX, Y and Z with an array
3 Amend shuffle mechanism
4 Use new parameter to determine first line to output
5 Output the lines in a loop
Alternative 'two loop' solution to Max 3:
1 Change the procedure header to include a numeric parameter (as well as the filename)
2 A loop to count the total number of lines in the file
3 Ref use of single variable rather than LineX, LineY and LineZ
4 Close and re-open the file
5 Use the new parameter value to determine first line to output
6 Output the lines in a loop

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 337
3c 9618 S22 P23
7 The following pseudocode represents an algorithm intended to output the last three lines as
they appear in a text file. Line numbers are provided for reference only.
10 PROCEDURE LastLines(ThisFile : STRING)
11 DECLARE ThisLine : STRING
12 DECLARE Buffer : ARRAY[1:3] OF STRING
13 DECLARE LineNum : INTEGER
14 LineNum Å 1
15 OPENFILE ThisFile FOR READ
16
17 WHILE NOT EOF(ThisFile)
18 READFILE Thisfile, ThisLine // read a line
19 Buffer[LineNum] Å ThisLine
20 LineNum Å LineNum + 1
21 IF LineNum = 4 THEN
22 LineNum Å 1
23 ENDIF
24 ENDWHILE
25
26 CLOSEFILE ThisFile
27 FOR LineNum Å 1 TO 3
28 OUTPUT Buffer[LineNum]
29 NEXT LineNum
30 ENDPROCEDURE
(a) There is an error in the algorithm. In certain cases, a text file will have at least three lines
but
the output will be incorrect.
(i) State how the output may be incorrect.
.....................................................................................................................................................
................................................................................................................................................ [1]
(ii) Describe the error in the algorithm and explain how it may be corrected.
Description ..................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
Explanation .................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................... [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 338
(b) The original algorithm is implemented and sometimes the last three lines of the text file
are output correctly. State the condition that results in the correct output.
.....................................................................................................................................................
........................................................................................................................................... [1]
(c) Lines 20 to 23 inclusive could be replaced with a single pseudocode statement.
Write the pseudocode statement.
.....................................................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 339
Summer 15 P22
5 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 (using variable SalesX) and
Site Y (using variable SalesY).
(d) The company decides to offer a discount on selected dates. A program is written to
indicate the dates on which a discount is offered.
The program creates a text file, DISCOUNT_DATES (with data as shown), for a number of
consecutive dates.
03/06/2015 TRUE
04/06/2015 FALSE
05/06/2015 FALSE
06/06/2015 FALSE
07/06/2015 FALSE
08/06/2015 FALSE
09/06/2015 FALSE
10/06/2015 TRUE
11/06/2015 FALSE

01/07/2015 FALSE
Each date and discount indicator is separated by a single <Space> character.
The discount indicators are:
• FALSE – indicates a date on which no discount is offered
• TRUE – indicates a date on which a discount is offered

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 340
The following incomplete pseudocode creates the text file DISCOUNT_DATES.
Complete the pseudocode.
OPENFILE "DISCOUNT_DATES" FOR .........................
INPUT ........................................
WHILE NextDate<>"XXX"
INPUT Discount
……………………………… Å NextDate & " " & Discount)
WRITEFILE "DISCOUNT_DATES", NextLine
INPUT NextDate
...........................................................
OUTPUT "File now created"
CLOSEFILE "DISCOUNT_DATES" [4]
(e) The DISCOUNT_DATES text file is successfully created.
The company now wants a program to:
• key in a date entered by the user
• search the text file for this date
• if found, output one of the following messages:
o “No discount on this date”
o “This is a discount date”
• if not found, output “Date not found”
(ii) Write the pseudo code.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...........................................................................................................................................[7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 341

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 342
Summer 15 P23 (Create a text file)(Search data in a file)
4 (b) A country has a number of banks. There are cash dispensers all over the country. Each
bank is responsible for a number of dispensers.
• banks have a three digit code in the range 001 – 999
• each dispenser has a five digit code in the range 00001 – 99999
A text file, DISPENSERS, is to be created.
It has one line of text for each dispenser. For example: 00342▼007.
This line in the file is the data for dispenser 00342 which belongs to bank 007.
Incomplete pseudocode follows for the creation of the file DISPENSERS.
For the creation of the file, data is entered by the user at the keyboard.
(i) Complete the pseudocode.
OPENFILE .................... FOR WRITE
........................................
OUTPUT "Enter dispenser code (XXXXX to end)"
INPUT DispenserCode
IF DispenserCode<> "XXXXX"
THEN
OUTPUT "Enter bank code"
INPUT BankCode
LineString Å ............ & "▼" & BankCode
// now write the new line to the file
.....................................
ENDIF
UNTIL ..................................
........................................
OUTPUT "DISPENSERS file now created"
[6]
(ii) No attempt has been made to validate the data entered by the user.
Describe two different types of validation check for the data entry.
1 ........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
.......................................................................................................................................[2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 343
(iii) The programmer coded this algorithm above and the user successfully entered 15
dispenser records into the text file.

There is data for another 546 dispensers which needs to be added.


State the error that will occur if the user runs the program a second time for further data entry.

.......................................................................................................................................[1]
(iv) Give the ‘file mode’ available in the programming language which will be used to address
this issue.

.......................................................................................................................................[1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 344
Write the pseudo code. Do not attempt to include any validation checks.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................[10]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 345

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 346

Winter 17 P22 (Reading data from Array and writing in File)


5 A multi-user computer system records user login data. Each time a user successfully logs
into the system, it records the following data.
Data item Example data
User ID "Jim27"
Port ID "3456"
Time and date "08:30 Jun 01 2015"
The data items are concatenated (joined) using a separator character to form a single string.
Each string represents one log entry.
(a) (i) Suggest a suitable separator character. Give the reason for your choice.
Character ..........................................................................................................................
Reason ..............................................................................................................................
........................................................................................................................................... [2]
(ii) The concatenated strings are stored in an array, LogArray, which may contain up to 20 log
entries. Use pseudocode to declare LogArray.
...................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 347
(b) A procedure, LogEvents, is required to add the log entry data from LogArray to the
existing text file, LoginFile.txt.
Unused array elements are assigned the value "****". These can occur anywhere in the array
and should not be written to the file.
Write pseudo code for the procedure LogEvents.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 348

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 349
Winter 17 Paper 21 (Reading data from one file and storing in other after modification)
5 A sports club maintains a record of the email address of each of its members. The details
are stored in a text file, EmailDetails.txt. The format of each line of the text file is as follows:
<MembershipNumber><EmailAddress>
• MembershipNumber is a four-character string of numerals.
• EmailAddress is a variable-length string.
Membership of the club has increased and a four-character membership number is no longer
adequate.
A procedure, MakeNewFile, is required to perform the following actions:
1. Create a new file, NewEmailDetails.txt
2. Read a line from file EmailDetails.txt
3. Extend MembershipNumber by adding two leading zero digits (for example, "1234"
becomes "001234")
4. Write the new line to file NewEmailDetails.txt
5. Repeat steps 2 to 4 for all lines in the original file.
(a) Write pseudocode for the procedure MakeNewFile.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 350

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 351
Summer 16 P21-22 (Input from user and store in file)
5 Toni has a large collection of jazz CDs that are stored in different places. She wants to
record
where the CDs are stored. She decides to write a program to do this.
The program must store the data in a file, MyMusic.
(a) (i) Why is a file needed?
...........................................................................................................................................
.......................................................................................................................................[1]
(ii) MyMusic is a text file with the data for each CD as one line of text.
Data for a typical CD are:
Title: Kind of Green
Artist: Miles Coltrane
Location: Rack1-5
The line will be formed by concatenating the three data items.
For the example above, the line stored will be:
Kind of GreenMiles ColtraneRack1-5
Describe a problem that might occur when organising the data in this way.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Describe a possible solution.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
........................................................................................................................................... [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 352
(b) Toni must input the data into the file MyMusic for all of her CDs.
A procedure, InputData, is needed to do this.
Toni designs the procedure and chooses the following identifiers:
Identifier Data type
CDTitle STRING
CDArtist STRING
CDLocation STRING
The procedure repeatedly performs the following steps:
• input a CD title (A rogue value of “##” is to be used to end the input)
• input the artist
• input the location
• create the text line
• write the text line to the file
When the rogue value is encountered the file is closed.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 353

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 354

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 355
9618 Summer 21 P21 (Passing file name as parameter)
3 (a) A concert venue uses a program to calculate admission prices and store information
about ticket sales. A number of arrays are used to store data. The computer is switched off
overnight and data has to be input again at the start of each day before any tickets can be
sold. This process is very time consuming.
(i) Explain how the program could use text files to speed up the process.
.....................................................................................................................................................
................................................................................................................................. [2]
(ii) State the characteristic of text files that allow them to be used as explained in part (a)(i).
.....................................................................................................................................................
........................................................................................................................... [1]
(iii) Information about ticket sales will be stored as a booking. The booking requires the
following data:
• name of person booking
• number of people in the group (for example a family ticket or a school party)
• event type.
Suggest how data relating to each booking may be stored in a text file.
.....................................................................................................................................................
................................................................................................................................. [2]
(b) A procedure Preview() will:
• take the name of a text file as a parameter
• output a warning message if the file is empty
• otherwise output the first five lines from the file (or as many lines as there are in the file if
this number is less than five).
Write pseudocode for the procedure Preview().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 356
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 357
5 The following data items will be recorded each time a student successfully logs on to the
school network:
Data item Example data
Student ID "CJL404"
Host ID "Lib01"
Time and date "08:30, June 01, 2021"
The Student ID is six characters long. The other two data items are of variable length.
A single string will be formed by concatenating the three data items. A separator character will
need to be inserted between items two and three.
For example:
"CJL404Lib01<separator>08:30, June 01, 2021"
Each string represents one log entry.
A programmer decides to store the concatenated strings in a 1D array LogArray that contains
2000 elements. Unused array elements will contain an empty string.
(a) Suggest a suitable separator character and give a reason for your choice.
Character ..................................................................................................................................
Reason .....................................................................................................................................
................................................................................................................................................ [2]
(b) The choice of data structure was made during one stage of the program development life
cycle.
Identify this stage.
............................................................................................................................................. [1]
(c) A function LogEvents() will:
• take a Student ID as a parameter
• for each element in the array that matches the Student ID parameter:
◦ add the value of the array element to the existing text file LogFile
◦ assign an empty string to the array element
• count the number of lines added to the file
• return this count.
Write pseudocode for the function LogEvents().
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 358
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 359

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 360
Winter 21 P22
5 A company has several departments. Each department stores the name, email address and
the status of each employee in that department in its own text file. All text files have the same
format.
Employee details are stored as three separate data strings on three consecutive lines of the
file.
An example of the first six lines of one of the files is as follows:
File line Comment
1 First employee name
2 First email address
3 First employee status
4 Second employee name
5 Second email address
6 Second employee status
A procedure MakeNewFile() will:
• take three parameters as strings:
○ an existing file name
○ a new file name
○ a search status value
• create a new text file using the new file name
• write all employee details to the new file where the employee status is not equal to the
search status value
• count the number of sets of employee details that were in the original file
• count the number of sets of employee details that were written to the new file
• produce a summary output.
An example summary output is as follows:
File Marketing contained 54 employee details
52 employee sets of details were written to file
NewMarketingList
(a) Write pseudocode for the procedure MakeNewFile().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 361
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]
(b) An alternative format could be used for storing the data.
A text file will still be used.
(i) Describe the alternative format.
.....................................................................................................................................................
........................................................................................................................... [1]
(ii) State one advantage and one disadvantage of the alternative format.
Advantage .........................................................................................................................
...........................................................................................................................................
Disadvantage ....................................................................................................................
...................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 362

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 363
Winter 20 P21
3 The procedure OutputLines() outputs a number of lines from a text file.
An example of the use of the procedure is given by the following pseudocode:
CALL OutputLines(FileName, StartLine, NumberLines)
Parameter Data type Description
FileName STRING The name of the text file
StartLine INTEGER The number of the first line to be output
NumberLines INTEGER The number of lines to be output

The procedure is tested using the file MyFile.txt that contains 100 lines of text.
The procedure gives the expected result when called as follows:
CALL OutputLines("MyFile.txt", 1, 10)
(a) The procedure is correctly called with three parameters of the appropriate data types, but
the procedure does not give the expected result.
Give three different reasons why this might happen.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
................................................................................................................................................ [3]
(b) Write pseudo code for the procedure OutputLines().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 364
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 365
10.4 Introduction to Abstract Data Types (ADT)
Candidates should be able to: Notes and guidance
Show understanding that an ADT is a collection of
data and a set of operations on those data
Show understanding that a stack, queue and linked Describe the key features of a stack, queue and linked
list are examples of ADTs list and justify their use for a given situation
Use a stack, queue and linked list to store data Candidates will not be required to write pseudocode
for these structures, but they should be able to add,
edit and delete data from these structures
Describe how a queue, stack and linked list can be
implemented using arrays

Data types:
A data type is a classification of data which tells the compiler or interpreter how the
programmer intends to use the data. Most programming languages support various types of
data, including integer, real, character or string, and Boolean.
Before a variable can be used in a program, the variable’s data type has to be identified.
Built-in data types
Remember, for each built-in data type:
• The programming language defines the range of possible values that can be assigned to a
variable when its type has been chosen.
• The programming language defines the operations that are available for manipulating
values assigned to the variable.

An abstract data type is a conceptual model that describes how data is organised and which
operations can be carried out on the data (e.g. insert, delete) from the perspective of an end
user who does not need to know how this is implemented. There are often many ways to
implement an abstract data type, depending on the programming language being used.
Stack, Linked List and Queue are examples of abstract data types

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 366
Stack

Courtesy: https://learning.cambridgeinternational.org/classroom/course/view.php?id=4007
Stack: A stack is a collection of data elements that are stored in a linear method.
LIFO: Last in First Out, First item entered in stack will be removed at last
Pop: Remove data item from stack
Push: Insert data item into a stack
Base Pointer: address of 1st data item in stack, it is static (remain unchanged during Pop and Push)
Top Pointer: address of last data item, it is dynamic (increases with each Push and decreases with each
Pop)
Empty Stack: If no data item is entered yet, top pointer is lesser than base pointer.
Full Stack: All elements have been entered, top pointer will be equals to stack size.

A stack is a collection of data elements that are stored in a linear method. A simple way to view

this is as a vertical stack of blocks, like this. There are two main operations that are used to
manipulate the data in the stack, these are push and pop. The push operation adds a data
element to the stack. The pop operation removes a data element from the stack.
A stack operates as a LIFO (Last In First Out) structure. This means that the last item that is
pushed to the stack when data is added, is the first item that is popped from the stack when data
is removed. When data is added to the stack, the push command is used along with the data
element that needs to be added to the stack. When data is removed from the stack the pop
command is used. That will remove the last element of data added to the stack.
Okay, Let’s take a look at another stack.
In an empty stack Red, Blue and yellow has been added. Now this stack currently stores the

colours red, blue and yellow. Here is a set of commands for the stack:
• PUSH Red, Blue, Yellow
• POP
• PUSH Green
• PUSH Purple
• PUSH Orange
• POP
• PUSH Pink


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 367

Let’s follow the commands and see how they affect the stack:
Current status was Red, Blue and Yellow
• First Yellow is removed from the stack
• Then Green, Purple and Orange are added to the stack
• Then Orange is removed from the stack
• Finally, Pink is added to the stack
The size of a stack needs to be defined. This means that the maximum number of data elements in
the list needs to be defined. For example, the stack size of this stack is 5. If there are 5 data
elements in the stack and the system tries to add another data element, a message is sent to
report that the stack is full and the additional data cannot be added. If all the data elements are
popped from the stack and the systems tries to remove another data element, a message is sent
to report that the stack is empty and that there is no data to be removed. The bottom of the stack
will always remain in the same place, it has a static position. The top of the stack however is
dynamic and will move each time a data element is pushed to or popped from the stack.

Application of Stack
One common application of the use of stacks is backtracking. In the backtracking process, a
system may need to remove the last actions that have taken place in order to get back to an
earlier stage of the process. Therefore, a stack is easy to use in this situation as the items pushed
to the stack can be just popped off it.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 368
Activity:

A stack “Letters” has a size of 5. Following operations are to be performed. Complete the stack
diagram and label the pointers:
PUSH A
PUSH B
PUSH C
POP
PUSH D
POP
PUSH E
Implementation of Data structures in stack ADT
Declare a (1D) array of stack size of the required data type.
Declare integer variable for TopOfStack Pointer.
Declare integer variable for BaseOfStack Pointer.
Initialise TopOfStack and BaseOfStack to represent an empty stack.
Declare integer variable for SizeOfStack to count, limit the max number of items allowed.
Understanding Stack Algorithms
1D arrays are used to create new stack, TopPointer is initialised with 0 and BasePointer with 1. Like
here an stack of 5 data items is created:
DECLARE MyStack : ARRAY[1:5] OF INTEGER
TopPointer Å 0
BasePointer Å 1
StackSize Å 5
To add data items in stack PUSH procedure is written.
PROCEDURE PUSH(DataToInsert : INTEGER)
IF TopPointer = StackSize
THEN
PRINT “Stack is full”
ELSE
TopPointer Å TopPointer + 1
MyStack[TopPointer] Å DataToInsert
ENDIF
ENDPROCEDURE


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 369
To remove data items POP function is used, stack is empty it returns -1.
FUNCTION POP( ) RETURN INTEGER
DECLARE DataToReturn : INTEGER
IF TopPointer = 0
THEN
DataToReturn Å -1
ELSE
DataToReturn Å MyStack[TopPointer]
TopPointer Å TopPointer – 1
ENDIF
RETURN DataToReturn
ENDFUCNTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 370
Queue

Courtesy: https://learning.cambridgeinternational.org/classroom/course/view.php?id=4007
Queue: A queue is a collection of data elements that are stored in a linear method.
FIFO: First In First Out (Data item entered first will be removed first)
Front Pointer: Pointer from where data items are removed from queue, increases with each Pop.
End Pointer: Pointer from where new data items are entered, increases with each Push.
A queue is a collection of data elements that are stored in a linear method. A simple way to view
this is as a horizontal line of blocks. A queue uses the same two main operations to manipulate
data as a stack; push and pop.
A queue operates as a FIFO (First In First Out) structure. This means that the first item that is
pushed to the queue when data is added, is the first item that is popped from the queue when
data is removed.
Let’s look at an example;
A queue size is 5, it is empty (the End Pointer = 0). Following operations are to be performed:
• PUSH Red
• PUSH Blue
• PUSH Yellow
• POP
• PUSH Green
• PUSH Purple
• PUSH Orange
• POP
• PUSH Pink

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 371
Let’s follow the commands and see how they affect the queue:

• First Yellow, Blue and Red are to the end of the queue
• Then red is removed from the front of the queue
• Then Green, Purple and Orange are added to the end of the queue
• Then Blue is removed from the front of the queue
• Finally, Pink is added to the end of the queue
As with stacks, the size of a queue also needs to be defined. This queue has a size of 5. If there are
5 data elements in the queue and the system tries to add another data element, a message is sent
to report that the queue is full and the data cannot be added. If all the data elements are popped
from the queue and the system tries to remove another data element, a message is sent to report
that the queue is empty.

Both the front and end of the queue are dynamic positions in a queue. This is because the front of
the queue will move if data is popped from the queue, and the end of the queue will move is data
is added to the end of the queue.
Application Of Queue
One common application of a queue is a job list for a printer. Each time a computer sends a print

job to the printer it is placed in a queue. Each time the printer begins to print a job it can be
removed from the queue.
An array can be used to implement both a stack and a queue. Each element in the array stores a
data element in the stack or queue.
Activity:

A Queue “Letters” has a size of 5. Following operations are to be performed. Complete the stack
diagram and label the pointers:
PUSH A
PUSH B
PUSH C
POP
PUSH D
POP
PUSH E


+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 372
Implementation of Data structures in queue
Declare a (1D) array of queue size of the required data type.
Declare integer variable for FrontOfQueuePointer.
Declare integer variable for EndOfQueuePointer.
Initialise FrontOfQueuePointer and EndOfQueuePointer to represent an empty queue.
Declare integer variable or NumberInQueue.
Declare integer variable for SizeOfQueue to count, limit the max number of items allowed.
Reference to mechanism for defining 'wrap' of circular queue8 Initialise SizeOfQueue.
Initialise NumberInQueue with null pointer.

Understanding Queue Algorithms


To add data item PUSH Function or Procedure are used. Function returns True if push
operation is successful.
Here is an example of a queue MyNumbers. Queue size is 10. When queue is empty,
EndProinter and FrontPointer both are same or NumberInQueue is 0. Like here in a new
empty queue EndPointer is 0 and FrontPointer is 0 while Number of queue items are 0.
DECLARE MyQueue : ARRAY[1:10] OF INTEGER
EndPointer Å 0
FrontPointer Å 0
NumberInQueue Å 0
QueueSize Å 10
Index 1 2 3 4 5 6 7 8 9 10
Mynumbers
To push (add) a data item in queue, firstly it is made sure that queue is not full. Queue will be
full if number in queue equals queue size. If queue is not full, then end pointer is incremented
by 1 and new data is stored at new end pointer.
PROCEDURE PUSH(BYVAL DataToInsert : INTEGER)
IF NumberInQueue = QueueSize
THEN
PRINT “Queue is full”
ELSE
EndPointer ←EndPointer + 1
IF EndPointer = QueueSize
THEN
EndPointer Å 1
ENDIF
MyQueue[EndPointer] Å DataToInsert
NumberInQueue Å NumberInQueue + 1
ENDIF
ENDPROCEDURE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 373
FUNCTION PUSH(BYVAL DataToInsert : INTEGER) RETURN BOOLEAN
IF NumberInQueue = QueueSize
THEN
RETURN FALSE
ELSE
EndPointer ←EndPointer + 1
IF EndPointer = QueueSize
THEN
EndPointer Å 1
ENDIF
MyQueue[EndPointer] Å DataToInsert
NumberInQueue Å NumberInQueue + 1
RETURN TRUE
ENDIF
ENDFUNCTION
To pop (remove) a data item in queue, firstly it is made sure that queue is not empty. Queue
will be full if number in queue equals queue size. If queue is not full, then end pointer is
incremented by 1 and new data is stored at new end pointer.

FUNCTION POP() RETURNS INTEGER


DECLARE NumberToReturn : INTEGER
IF NumberInQueue = 0
THEN
ItemToReturn ← -1
ELSE
ItemToReturn ← MyQueue[FrontPointer]
IF FrontPointer = QueueSize
THEN
FrontPointer ← 1
ELSE
FrontPointer Å FrontPointer + 1
ENDIF
NumberInQueue ← NumberInQueue – 1
IF NumberInQueue = 0
THEN
FrontPointer Å 0
EndPointer Å 0
ENDIF
ENDIF
RETURN ItemToReturn
END FUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 374
Work Example 2 – Queues
TASK 2.1: A queue is an abstract data type (ADT) that stores and manipulates a collection of
data.
The values 101, 111 and 151 are currently stored in a queue as follows:
Front Pointer End Pointer

101
01 111 151
15

A command has been carried out on the queue. This is the new state of the queue.
Front Pointer End Pointer

111 151
15

Explain what has happened to the queue.


……………………………………………………………………………………………………………
….…………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……….
TASK 2.2 Further commands are carried out as follows:
PUSH(175)
X=POP()
Y=POP()
PUSH(150)
Draw a representation to show the queue after the commands have been carried out.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 375
TASK 2.3: Queues can be linear or circular structures.
Explain the difference between a linear queue and a circular queue to another student.
TASK 2.4
The current status of a circular queue is as follows:
Front Pointer End Pointer

200 111 151


15 125 190 145
The following commands are carried out:
X=POP()
Y=POP()
PUSH(99)
PUSH(180)
Draw a diagram to show the queue after the commands have been carried out.

TASK 2.5
Discuss what should happen if a program were to execute the following command on the
queue that you have drawn in TASK 2.4.
ADD 120
……………………………………………………………………………………………………………
….…………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……….

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 376
Winter 19 P41
When a student prints a document, a print job is created. The print job is sent to a print
server.
The print server uses a queue to hold each print job waiting to be printed.
(i) The queue is circular and has six spaces to hold jobs.
The queue currently holds four jobs waiting to be printed. The jobs have arrived in the order
A, B, D, C.
Complete the diagram to show the current contents of the queue.
[1]
Front Pointer End Pointer

(ii) Print jobs A and B are now complete. Four more print jobs have arrived in the order E, F,
G, H.
Complete the diagram to show the current contents and pointers for the queue.
[3]

(iii) State what would happen if another print job is added to the queue in the status in part
(b)(ii).
...........................................................................................................................................
..................................................................................................................................... [1]
(iv) The queue is stored as an array, Queue, with six elements. The following algorithm
removes a print job from the queue and returns it.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 377
Complete the following pseudocode for the function Remove.
FUNCTION Remove RETURNS STRING
DECLARE PrintJob : STRING
IF ............................................................................... = EndPointer
THEN
RETURN "Empty"
ELSE
PrintJob Å Queue[...............................................................................]
IF StartPointer = ...............................................................................
THEN
StartPointer Å .........................................................................
ELSE
StartPointer Å StartPointer + 1
ENDIF
RETURN PrintJob
ENDIF
ENDFUNCTION [4]
(v) Explain why the circular queue could not be implemented as a stack.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 378

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 379
4 Zara is writing a program to simulate a circular queue.
The queue, MyNumbers, has 10 elements. Push() takes a parameter value and stores it at
the tail of the queue. Pop()returns the item at the head of the queue.
The current state of the circular queue is:

Index 0 1 2 3 4 5 6 7 8 9
Data 31 45 89 500 23 2

FrontPointer: 2
EndPointer: 8
Show the state of the queue, FrontPointer and EndPointer after the following operations:
Push(23)
Push(100)
Pop()
Pop()
Push(50)
Index 0 1 2 3 4 5 6 7 8 9
Data

FrontPointer: …………………………….
EndPointer: …………………………… [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 380
Linked List

Courtesy: https://learning.cambridgeinternational.org/classroom/course/view.php?id=4007
Node: an element of a list
Pointer: a variable that stores the address of the node it points to
Null pointer: a pointer that does not point at anything
Start pointer: a variable that stores the address of the first element of a linked list
Linked lists are an abstract data type. They are a collection of data elements that are stored in
a linear method. Let’s take look at how they operate.

A standard list stores each data element that is added in the next location. However, a linked
list does not store each element at an adjacent location. This is why it needs the ability to link

the data elements in order to know their correct order. Each data element in a linked list is

called a node, and each node contains the data stored as well as a pointer. A pointer is data
that references where the next data element in the list can be located. This can often be a

value to represent where the data is stored.


The last node in the list does not have another data element to point to, so the pointer for

this data element is called a null pointer. If data is removed from the list certain actions need
to occur. Let take a look at an example;

The second item of data in this list is removed. The pointer is removed from the data element
that is removed, and the pointer from the node before the data element removed is changed.
It can no longer point to the removed element as it is gone, so it is changed to point to the
next item in the list. When data is added to a linked list, it is added to the first available space

in the list. This could be at the end of the list. In this case, the pointer from the previous node
is changed from null to point to the data just added. The pointer for the data just added is

now set to null.


However, if a data element has been removed from the list, this may create an earlier space in

the list. For example, if item 2 is removed from the list, this becomes the next available space
in the list. Therefore, the data is added to this space, and the pointer of the last item in the list

is changed from null to point to the new data element added.


The pointer of the data just added then becomes the null pointer.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 381
Okay, let’s look at an example of the operation of a linked list. This linked list stores letters in

alphabetical order:

A new node containing data value B is to be added to the list in alphabetic sequence.
Following operations are performed:
1. Check for a free node
2. Search for correct insertion point
3. Assign data value B to first node in free list / node pointed to by start pointer of free list
4. Pointer from A will be changed to point to node containing B (instead of C)
5. Pointer from B will be changed to point to node containing C
6. Free List pointer will point to next free node

An array can be used to store a linked list. Each item of data in the linked list is stored in an

element of the array.


Application of Linked List

Linked list structures can be useful when storing data in an array, especially if the data needs
to be in a certain order. If an item of data is added to the array that needs to appear in the

middle of the order, this can be an expensive process in terms of time and resources for the
computer. It will need to shift items around in the array to make space for the new data.

However, if the data is stored in the array as a linked list, then it will just be the pointers that
need to be changed.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 382
Understanding Linked List Algorithms

Two 1D arrays are used to implement linked list, one to store data items and other to store

memory address of next data item. Record Data structure can be used to create a new list.
MyList
Data Pointer
[0]
Start Pointer [1]
[2]
FreeListPointer [3]
[4]
[5]
TYPE Node
DECLARE Data: STRING
DECLARE Pointer : INTEGER
END TYPE
DECLARE MyList : ARRAY[0:5] OF Node
A variable StartPointer stores memory address of start of the list and FreeListPointer stores

address from where free list is starting. In this empty list StartPointer will be -1 and
freeListPointer will be 0. And each pointer will point to next memory location, while at the end

of list there will be null value.


DECLARE StartPointer, NullPointer, FreeListPointer : INTEGER
StartPointer Å -1
FreeListPointer Å 0
NullPointer Å -1
FOR Count Å 0 TO 4
MyList[Count].Pointer Å Count + 1
NEXT Count
MyList[5] Å NullPointer
MyList
Data Pointer
[0] 1
Start Pointer -1 [1] 2
[2] 3
FreeListPointer 0 [3] 4
[4] 5
[5] -1

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 383
How arrays and variables are used to implement linked list

To insert data item in list


PROCEDURE InsertNode(NewItem)
DECLARE NewNodePointer, ThisNodePointer, PreviousNodePointer :
INTEGER
IF FreeListPtr <> NullPointer
THEN // there is space in the array take node from free list and store data item
NewNodePtr ← FreeListPtr
MyList[NewNodePtr].Data ← NewItem
FreeListPtr ← List[FreeListPtr].Pointer
// find insertion point
ThisNodePtr ← StartPointer // start at beginning of list
PreviousNodePtr ← NullPointer
WHILE ThisNodePtr <> NullPointer // while not end of list
AND List[ThisNodePtr].Data < NewItem
PreviousNodePtr ← ThisNodePtr // remember this node follow the
pointer to
// the next node
ThisNodePtr ← List[ThisNodePtr].Pointer
ENDWHILE
IF PreviousNodePtr = StartPointer
THEN // insert new node at start of list
List[NewNodePtr].Pointer ← StartPointer
StartPointer ← NewNodePtr
ELSE // insert new node between previous node and this node
List[NewNodePtr].Pointer ← List[PreviousNodePtr].Pointer

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 384
List[PreviousNodePtr].Pointer ← NewNodePtr
ENDIF
ENDIF
ENDPROCEDURE

Delete a node from an ordered linked list


PROCEDURE DeleteNode(DataItem)
ThisNodePtr ← StartPointer // start at beginning of list
WHILE ThisNodePtr <> NullPointer // while not end of list
AND List[ThisNodePtr].Data <> DataItem DO // and item not found
PreviousNodePtr ← ThisNodePtr // remember this node
// follow the pointer to the next node
ThisNodePtr ← List[ThisNodePtr].Pointer
ENDWHILE
IF ThisNodePtr <> NullPointer // node exists in list
THEN
IF ThisNodePtr = StartPointer // first node to be deleted
THEN
// move start pointer to the next node in list
StartPointer ← List[StartPointer].Pointer
ELSE
// it is not the start node; so make the previous node’s pointer point
to
// the current node’s 'next' pointer; thereby removing all
// references to the current pointer from the list
List[PreviousNodePtr].Pointer ← List[ThisNodePtr].Pointer
ENDIF
List[ThisNodePtr].Pointer ← FreeListPtr
FreeListPtr ← ThisNodePtr
ENDIF
ENDPROCEDURE

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 385
9618 Specimen Paper 2
3 A stack is created using a high-level language. The following diagram represents the
current state of the stack. The Top of Stack pointer points to the last item added to the stack.
Address Value Pointer

99
100
101 E ֚ TopOfStack
102 D
103 C
104 B
105 A
(a) Two operations associated with this stack are PUSH() and POP().
Describe these operations with reference to the diagram.
MyVar = POP()
...................................................................................................................................................
...................................................................................................................................................
PUSH('Z')
.....................................................................................................................................................
..............................................................................................................................................[4]
(b) Two programs use a stack to exchange data. Program AddString pushes a string of
characters onto the stack one character at a time. Program RemoveString pops the same
number of characters off the stack, one character at a time. The string taken off the stack is
different from the string put on the stack. Explain why the strings are different.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 386
1a 9618 21 P21
6 The following diagram represents an Abstract Data Type (ADT) for a linked list.

The free list is as follows:

(a) Explain how a node containing data value B is added to the list in alphabetic sequence.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [4]
(b) Describe how the linked list in part (a) may be implemented using variables and arrays.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]
1b 9618 S21 P22
3 The following diagram represents an Abstract Data Type (ADT).

(a) Identify this type of ADT.


.............................................................................................................................................[1]
(b) Give the technical term for the item labelled A in the diagram.
.......................................................................................................................................... [1]
(c) Give the technical term for the item labelled B in the diagram.
Explain the meaning of the value given to this item.
Term ..........................................................................................................................................
Meaning ....................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 387
(d) Complete the diagram to show the ADT after the data has been sorted in alphabetical
order.[2]

2abc W21 P21 23


3 (a) The diagram below represents a queue Abstract Data Type (ADT) that can hold a
maximum of eight items. The operation of this queue may be summarised as follows:
• The front of queue pointer points to the next item to be removed.
• The end of queue pointer points to the last item added.
• The queue is circular so that empty storage elements can be reused.
0 Frog Å Front of queue pointer
1 Cat
2 Fish
3 Elk Å End of queue pointer
4
5
6
7
(i) Describe how “Octopus” is added to the given queue.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
....................................................................................................... [2]
(ii) Describe how the next item in the given queue is removed and stored in the variable
AnimalName.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
....................................................................................................... [2]
(iii) Describe the state of the queue when the front of queue and the end of queue pointers
have the same value.
.....................................................................................................................................................
........................................................................................................................... [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 388
(b) Some operations are carried out on the original queue given in part (a).
(i) The current state of the queue is:

0 Frog
1 Cat
2 Fish
3 Elk
4
5
6
7

Complete the diagram to show the state of the queue after the following operations:
Add “Wasp”, “Bee” and “Mouse”, and then remove two data items. [3]

(ii) The state of the queue after other operations are carried out is shown:

0 Frog
1 Cat
2 Fish
3 Elk Å Front of queue pointer
4 Wasp
5 Bee
6 Mouse Å End of queue pointer
7 Ant

Complete the following diagram to show the state of the queue after the following operations:
Remove one item, and then add “Dolphin” and “Shark”. [2]

0
1
2
3
4
5
6
7

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 389
(c) The queue is implemented using a 1D array.
Describe the algorithm that should be used to modify the end of queue pointer when adding
an item to the queue. Your algorithm should detect any potential error conditions.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]

3a 9618 S22 P21


4 A stack is created using a high-level language. Memory locations 200 to 207 are to be used
to store the stack. The following diagram represents the current state of the stack.
TopOfStack points to the last value added to the stack.
Stack Pointer
Memory
Value
location
200
201
202
203 'F' TopOfStack
204 'C'
205 'D'
206 'E'
207 'H'
(a) Complete the following table by writing the answers. [2]
Answer
The value that has been on the stack for the longest time.
The memory location pointed to by TopOfStack if three
POP operations are performed.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 390
(b) The following diagram shows the current state of the stack:
Stack Pointer
Memory
Value
location
200
201
202 'W' TopOfStack
203 'Y'
204 'X'
205 'Z'
206 'N'
207 'P'
The following operations are performed:
POP
POP
PUSH 'A'
PUSH 'B'
POP
PUSH 'C'
PUSH 'D'
Complete the diagram to show the state of the stack after the operations have been
performed. [4]
Stack Pointer
Memory
Value
location
200
201
202
203
204
205
206
207

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 391
0 Specimen Paper 2

1a 9618 21 P21

1b 9618 S21 P22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 392

2ac W21 P21 23

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 393

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 394
2b 9618 W21 P22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 395

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 396
3a 9618 S22 P21

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 397
11.1 String manipulation Algorithms
A string is a variable that holds a sequence of one or more alphanumeric characters. It is usually
possible to manipulate a string to provide information or to alter the contents of a string.
The following examples use strings:
FirstName = "Abdullah" LastName = "Patel"
Practice Question:
Q 1) Write an algorithm to input password. Validate password i.e. must be 8 characters long. If password is not
valid then print error message and input password again. Stop input when a valid password is entered.

a) Write an algorithm that inputs a text string and output each letter in a separate line.

b) Write an algorithm that gives following output from a string TextString=”INQILAB”

I
IN
INQ
INQI
INQIL
INQILA
INQILAB

c) Write another program that input a name and print it in a format given in part (a).

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 398
Q 2) Write an algorithm that inputs email id and validate email ID. It must contain a ‘@’ character and a ‘.’.

Q 3) Write an algorithm that input Email ID, make sure that it contains a single ‘@’ and ‘.’.

Q 4a) Write an algorithm that inputs a text string and output how many characters are there.

Q 4b) Write an algorithm that inputs a text string and output number of letter, number of digits and number of
space in the string.

Q 5) Write an algorithm that inputs and validate password.


It must be 8 characters long. It must contain at least one upper case letter, at least one lower case letter, at
least one digit and at least one non-alpha-numeric character.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 399
Q 6) Write a program that input a text string contain name and email id separated by ‘:’ and prints name. E.g.
[email protected]” prints “inqilabpatel”, while “[email protected]” prints “abdullah”

Q 7) Write a program using pseudo code to define a procedure. This procedure input a text string and output
number of words in the string.
For Example, a string contains “Computer Science 9618” returns 3 as word count.

DECLARE Wcount, Count : INTEGER


DECLARE NextChar : CHAR
Wcount Å 1
INPUT “Enter a text string “, ThisString
WHILE ThisString=” “ DO
PRINT “Error! String is empty try again”
INPUT “Enter a text string “, ThisString
ENDWHILE
FOR Count Å 1 TO LENGTH(ThisString)
NextChar Å MID (ThisString, Count, 1)
IF NextChar = " "
THEN
Wcount Å Wcount + 1
ENDIF
NEXT Count
PRINT "There are ", Wcount , " words in the string"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 400
9618 Specimen Paper
6) Members of a family use the same laptop computer. Each family member has their own
password.
To be valid, a password must comply with the following rules:
1 At least two lower-case alphabetic characters
2 At least two upper-case alphabetic characters
3 At least three numeric characters
4 Alpha-numeric characters only
A function, ValidatePassword, is needed to check that a given password follows these rules.
This function takes a string, Pass, as a parameter and returns a boolean value:
• TRUE if it is a valid password
• FALSE otherwise
(a) Write pseudocode to implement the function ValidatePassword.
Refer to the Insert for the list of pseudocode functions and operators.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
..............................................................................................................................................[9]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 401
(b) The ValidatePassword function will be tested.
(i) Give a valid password that can be used to check that the function returns TRUE under the
correct conditions.
Password1: .................................................................................................................. [1]
(ii) Password1 is modified to test each rule separately. Give four modified passwords and
justify your choice.
Password to test rule 1: .............................................................................................................
Reason: ......................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
Password to test rule 2: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Password to test rule 3: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Password to test rule 4: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
........................................................................................................................................... [4]
(iii) When testing the ValidatePassword function a module it is necessary to test all possible
paths through the code. State the name given to this type of validation testing.
...................................................................................................................................... [1]
(iv) A program consisting of several functions can be tested using a process known as ‘stub
testing’ Explain this process.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
........................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 402

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 403

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 404
Summer 21 P21
4 Study the following pseudocode. Line numbers are for reference only.
10 FUNCTION Convert(Name : STRING) RETURNS STRING
11
12 DECLARE Flag: BOOLEAN
13 DECLARE Index : INTEGER
14 DECLARE ThisChar : CHAR
15 DECLARE NewName : STRING
16
17 CONSTANT SPACECHAR = ' '
18
19 Flag Å TRUE
20 Index Å 1
21 NewName Å "" // formatted name string
22
23 WHILE Index <= LENGTH(Name)
24 ThisChar Å MID(Name, Index, 1)
25 IF Flag = TRUE THEN
26 NewName Å NewName & UCASE(ThisChar)
27 IF ThisChar <> SPACECHAR THEN
28 Flag ÅFALSE
29 ENDIF
30 ELSE
31 NewName Å NewName & ThisChar
32 ENDIF
33 IF ThisChar = SPACECHAR THEN
34 Flag Å TRUE
35 ENDIF
36 Index Å Index + 1
37 ENDWHILE
38
39 RETURN NewName
40
41 ENDFUNCTION

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 405
(a) Complete the trace table below by dry running the function when it is called as follows:
Result Å Convert("‫׏‬in‫׏‬a‫׏׏‬Cup")
Note: The symbol '‫ '׏‬has been used to represent a space character.
Use this symbol for any space characters in the trace table.
The first row has been completed for you. [5]
Name Flag Index NewName ThisChar
"‫׏‬in‫׏‬a‫׏׏‬Cup"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 406
(b) The pseudocode for Convert() contains a conditional loop.
State a more appropriate loop structure.
Justify your answer.
Loop structure ...........................................................................................................................
...................................................................................................................................................
Justification ...............................................................................................................................
...................................................................................................................................................
................................................................................................................................................[2]
(c) Two changes need to be made to the algorithm.
Change 1: Convert to lower case any character that is not the first character after a space.
Change 2: Replace multiple spaces with a single space.
(i) Change 1 may be implemented by modifying one line of the pseudocode.
Write the modified line.
...........................................................................................................................................
.......................................................................................................................................[1]
(ii) Change 2 may be implemented by moving one line of the pseudocode.
Write the number of the line to be moved and state its new position.
Line number ......................................................................................................................
New position ......................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 407

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 408

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 409
14a 9608 W21 P21
2 (a) The following pseudocode function counts the occurrences of a character in a string.
Line numbers are shown for reference only.
01 DECLARE Message: STRING
02
03 FUNCTION CharacterCount(Letter : CHAR) RETURNS INTEGER
04
05 DECLARE LetterCount, Index : INTEGER
06 DECLARE ThisChar : INTEGER
07
08 LetterCount Å 1
09
10 FOR Index Å 1 TO LENGTH(Message) - 1
11 ThisChar Å LEFT(Message, Index, 1)
12 IF ThisChar = Letter
13 THEN
14 LetterCount LetterCount + 1
15 ENDIF
16 NEXT Index
17 RETURN LetterCount
18 ENDFUNCTION
(i) State the technical name of the iterative control structure used in this function.
.....................................................................................................................................
[1]
(ii) Examine the pseudocode and write the answer in the table for each item.
[4]
Item Answer
The scope of the variable Message is

The start and end line numbers of a selection structure

The identifier name of a user-defined function is

An arithmetic operator used in the function is


(b) Four lines of the pseudocode given in part (a) contain an error.
Identify the errors and write the correct pseudocode.
Line number for error 1 .............................................................................................................
Correct pseudocode .................................................................................................................
...................................................................................................................................................
Line number for error 2 .............................................................................................................
Correct pseudocode .................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 410
Line number for error 3 .............................................................................................................
Correct pseudocode .................................................................................................................
...................................................................................................................................................
Line number for error 4 .............................................................................................................
Correct pseudocode .................................................................................................................
................................................................................................................................................... [4]
14a 9608 W21 P21
(c) A procedure, Frequency(), outputs the number of times each vowel occurs in a string.
The procedure will:
• prompt and input a string
• count the occurrence of each vowel in the string using a CASE structure
• output each vowel with its count value.
You may assume that vowels are the upper-case or lower-case characters 'a', 'e', 'i', 'o',
and 'u'.
Write pseudocode for the procedure Frequency().

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 411
1b 9618 S21 P22
6 A procedure CountVowels() will:
• be called with a string containing alphanumeric characters as its parameter
• count and output the number of occurrences of each vowel (a, e, i, o, u) in the string
• count and output the number of occurrences of the other alphabetic characters (as a single
total).
The string may contain both upper and lower case characters.
Each count value will be stored in a unique element of a global 1D array CharCount of type
INTEGER. The array will contain six elements.
Write pseudocode for the procedure CountVowels().

.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
..................................................................................................................................... [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 412
7 A procedure, FormatName():
• is called with a string containing words and spaces as its parameter. In this context, a word
is any sequence of characters that does not contain a space character.
• creates a new formatted string from this string with the following requirements:
1. Any leading spaces removed (spaces before the first word).
2. Any trailing spaces removed (spaces after the last word).
3. Any multiple spaces between words converted to a single space.
4. All characters converted to lower case.
The FormatName() procedure has been written in a programming language and is to be
tested using the black-box method.
(a) Give a test string that could be used to show that all four formatting requirements have
been applied correctly.
Use the symbol ‘‫ ’׏‬to represent a space character.
............................................................................................................................................. [3]
(b) The FormatName() procedure should assign a value to the global variable FString.
There is a fault in the program, which means that the assignment does not always take place.
Explain two ways of exposing the fault.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 413
1b 9618 S21 P22
8 A program is needed to take a string containing a full name and to produce a new string of
initials. Some words in the full name will be ignored. For example, “the”, “and”, “of”, “for” and
“to” may all be ignored. Each letter of the new string must be upper case.
For example:
Full name Initials
Integrated Development Environment IDE
The American Standard Code for Information Interchange ASCII
The programmer has decided to use the following global variables:
• a ten element 1D array IgnoreList of type STRING to store the ignored words
• a string FNString to store the full name string.
Assume that:
• each alphabetic character in the full name string may be either upper or lower case
• the full name string contains at least one word.
The programmer has started to define program modules as follows:
Module Description
• Called with an INTEGER as its parameter, representing the number of a
word in FNString
GetStart() • Returns the character start position of that word in FNString or returns -1 if
that word does not exist
• For example: GetStart(3) applied to "hot and cold" returns 9
• Called with the position of the first character of a word in FNString as its
parameter
GetWord() • Returns the word from FNString
• For example: if FNString contains the string "hot and cold", GetWord(9)
returns "cold"
• Called with a STRING parameter representing a word
IgnoreWord() • Searches for the word in the IgnoreList array
• Returns TRUE if the word is found, otherwise returns FALSE
• Processes the sequence of words in the full name one word at a time
• Calls GetStart(), GetWord() and IgnoreWord() to process each word to form
GetInitials()
the new string
• Outputs the new string
(a) Write pseudocode for the module IgnoreWord().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 414
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [5]
(b) Write pseudocode for the module GetInitials().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 415

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 416

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 417

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 418

Write a program to encrypt data and another to decrypt data using following keys:

Message character A B C D E F G H I J K L M
Substitute character P L F N O C Q U D Z V G I

Message character N O P Q R S T U V W X Y Z
Substitute character X M W J B K E A H S Y R T

Your algorithm inputs a text string, encrypt it and displays encrypted text string.

Your another algorithm inputs a cypher text decrypt it into normal text using the same key.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 419
Winter 2015 P22
6 Some pseudocode statements follow which use the following built-in functions:
ONECHAR(ThisString : STRING, Position : INTEGER) RETURNS CHAR
returns the single character at position Position (counting from the start of the string with
value 1) from the string ThisString. For example: ONECHAR("Barcelona", 3) returns 'r'.

CHARACTERCOUNT(ThisString : STRING) RETURNS INTEGER


returns the number of characters in the string ThisString.
For example: CHARACTERCOUNT("South Africa") returns 12.
(a) Study the following pseudocode statements.
Give the values assigned to variables x and y. [1]
(i) x ← CHARACTERCOUNT("New Delhi") + 3 x .....................................
(ii) y ← ONECHAR("Sri Lanka", 5) y .....................................
(b) A program is to be written as follows:
x the user enters a string
x the program will form a new string with all <Space> characters removed
x the new string is output
NewString ← ""
INPUT InputString
j ← CHARACTERCOUNT(InputString)
FOR i ← 1 TO j
NextChar ← ONECHAR(InputString, i)
IF NextChar<> ""
THEN
// the & character joins together two strings
NewString ← NewString & NextChar
ENDIF
NEXT i
OUTPUT NewString
(i) Complete the identifier table below.[4]
Identifier Data type Description
InputString STRING The string value input by the user

7 ASCII character codes are used to represent a single character.


Part of the code table is shown below.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 420
ASCII code table (part)
Character Decimal Character Decimal Character Decimal
<Space> 32 I 73 R 82
A 65 J 74 S 83
B 66 K 75 T 84
C 67 L 76 U 85
D 68 M 77 V 86
E 69 N 78 W 87
F 70 O 79 X 88
G 71 P 80 Y 89
H 72 Q 81 Z 90
(a) Give the values assigned to the variables A, B, C and D.
The & operator is used to concatenate two strings.
The expression could generate an error; if so, write ERROR.
Num1 ← 5
A ← ASC('F') + Num1 + ASC('Z') (i) A ..................................................... [1]
B ← CHR(89) & CHR(69) & CHR(83) (ii) B ..................................................... [1]
C ← LENGTH(B & "PLEASE") (iii) C ..................................................... [1]
D ← ASC(LENGTH("CURRY SAUCE", 7,1)) (iv) D ..................................................... [1]
(b) A program is to be written to input a message string and then encrypt the message.
Study the following pseudocode:
OUTPUT "Enter message"
INPUT MyMessage
EncryptString ← ""
FOR i ← 1 TO LENGTH(MyMessage)
NextNum ← ASC(MID(MyMessage, I,1)) + 3
EncryptString ← EncryptString&CHR(NextNum)
NEXT i
OUTPUT EncryptString

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 421
(ii) Describe the encryption algorithm used to encrypt the message string entered by the
user.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 422

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 423

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 424
12 Software Development

12.1 Program Development Life cycle


Candidates should be able to: Notes and guidance
Show understanding of the purpose of a
development life cycle
Show understanding of the need for different Including, waterfall, iterative, rapid application
development life cycles depending on the development (RAD)
program being developed
Describe the principles, benefits and drawbacks
of each type of life cycle
Show understanding of the analysis, design,
coding, testing and maintenance stages in the
program development life cycle

The program development life cycle (SDLC) is a process for planning, creating, testing,
and deploying an information system. The systems development life cycle concept applies to
a range of hardware and software configurations, as a system can be composed of hardware
only, software only, or a combination of both.
The purpose of a program development lifecycle
In order to develop a successful program or suite of programs that is going to be used by
others
to perform a specific task or solve a given problem, the development needs to be well ordered
and clearly documented, so that it can be understood and used by other developers.
Stages of System Development Life Cycle
Following are the steps of system development life cycle:

Analysis

Maintenance Design

Testing
Coding

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 425
1. Analysis:
Identification, abstraction, decomposition of the problem and identification of
requirements.
This stage involves the process of gathering and interpreting facts, diagnosing problems, and
recommending improvements to the system. Project goals will be further aided by analysis of
end-user information needs and the removal of any inconsistencies and incompleteness in
these requirements. Problem is defined and requirement specification is prepared.
A series of steps followed by the developer include:

i. Collection of facts: Obtain end user requirements through documentation, client


interviews, observation, and questionnaires.
ii. Scrutiny of the existing system: Identify pros and cons of the current system in-place, so
as to carry forward the pros and avoid the cons in the new system.
iii. Analysis of the proposed system: Find solutions to the shortcomings described in step two
and prepare the specifications using any specific user proposals.
2. Design
Shown by decomposition using structure diagrams, flowcharts and pseudocode.
The program specification from the analysis stage is used to show how the program should
be developed. In this stage:
i. Identifier table is developed, variables, constants, arrays and other data structures are
decided.
ii. Algorithm flowchart and/or pseudo code is designed.
iii. Structure chart and state-transition diagrams are also designed.
iv. Program structure, modules, library routines and team allocation is decided.
v. Testing plan is decided.
vi. Programming language is chosen.
3. Coding
Writing program code and performing iterative testing.
In this stage the program or set of programs is written using a suitable programming
language.
When you have designed your solution, you might need to choose a suitable high-level
programming language. If you know more than one programming language, you have to
weigh up the pros and cons of each one. Looking at Chapter 14, you need to decide which
programming language would best suit the problem you are trying to solve and which
language you are most familiar with.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 426
4. Testing
Testing program code using test data.
The program is run many times with different sets of test data, to test that it does everything it
is supposed to do in the way set out in the program design.

5. Maintenance
The program is maintained throughout its life, to ensure it continues to work effectively. This
involves dealing with any problems that arise during use, including correcting any errors that
come to light, improving the functionality of the program, or adapting the program to meet new
requirements.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 427
Types of Software Development Life Cycles:
Show understanding of the need for different Including, waterfall, iterative, rapid
development life cycles depending on the application development (RAD)
program being developed
SDLC Methodologies are processes and practices used by software development teams in
order to successfully navigate the Software Development Life Cycle (SDLC).
There are several methodologies. Some of them are as follows:
1. Waterfall Model
2. Iterative Model
3. Rapid Application Development Model
1. Waterfall Model
This is the first model. According to the Waterfall method, the software development process
goes through all the SDLC phases with no overlapping and consists of a single development
cycle. According to the fact that it is a linear-sequential life cycle model, any phase in the
development process can begin only if the previous one is complete.

After the analysis, data structures, and functional designs are ready (Design), the
development team starts coding the software. Only after all code can be tested. This means
that the code is not tested before the coding. Testing phase and only unit tests are executed
during development.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 428
Finally, the software finishes testing and is deployed to production and for the first time, where
users can take it for a test drive.
The Waterfall method can take several months or even years to complete, which means that
if it doesn’t meet user expectations, changes are extremely slow and expensive
(maintenance).
Benefits include the following.
• Simple to understand as the stages are clearly defined.
• Easy to manage due to the fixed stages in the model. Each stage has specific outcomes.
• Stages are processed and completed one at a time.
• Works well for smaller projects where requirements are very well understood.
Drawbacks include the following.
• No working software is produced until late during the life cycle.
• Not a good model for complex and object-oriented projects.
• Poor model for long and ongoing projects.
• Cannot accommodate changing requirements.
• It is difficult to measure progress within stages.
• Integration is done at the very end, which doesn’t allow identifying potential technical or
business issues early.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 429
2. Iterative Model
With the Iterative Model, only the major requirements are known from the beginning. Based
on these, the development team creates a quick and cheap first version of the software.
Then, as additional requirements are identified, additional iterations of the software are
designed and built. Each iteration goes through all the phases of the SDLC and these cycles
are repeated until completion.

Benefits
• There is a working model of the system at a very early stage of development, which makes it
easier to find functional or design flaws. Finding issues at an early stage of development
means corrective measures can be taken more quickly.
• Some working functionality can be developed quickly and early in the life cycle.
• Results are obtained early and periodically.
• Parallel development can be planned.
• Progress can be measured.
• Less costly to change the scope/requirements.
• Testing and debugging of a smaller subset of program is easy.
• Risks are identified and resolved during iteration.
• Easier to manage risk – high-risk part is done first.
• With every increment, operational product is delivered.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 430
• Issues, challenges, and risks identified from each increment can be utilised/applied to the
next increment.
• Better suited for large and mission-critical projects.
• During the life cycle, software is produced early, which facilitates customer evaluation and
feedback.

Drawbacks
• Only large software development projects can benefit because it is hard to break a small
software system into further small serviceable modules.
• More resources may be required.
• Design issues might arise because not all requirements are gathered at the beginning of the
entire life cycle.
• Defining increments may require definition of the complete system.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 431
3. Rapid Application Development:
In Rapid Application Development, problem is decomposed in modules, and prototype of
each module is designed. A prototype is a working model of part of the solution.
All modules are developed in parallel as prototypes and are integrated to make the complete
product for faster product delivery. There is no detailed preplanning.
Changes are made during the development process.
The analysis, design, code and test phases are incorporated into a series of short, iterative
development cycles.

Benefits.
• Changing requirements can be accommodated.
• Progress can be measured.
• Productivity increases with fewer people in a short time.
• Reduces development time.
• Increases reusability of components.
• Quick initial reviews occur.
• Encourages customer feedback.
• Integration from very beginning solves a lot of integration issues.
Drawbacks include the following.
• Only systems that can be modularised can be built using RAD.
• Requires highly skilled developers/designers.
• Suitable for systems that are component based and scalable.
• Requires user involvement throughout the life cycle.
• Suitable for projects requiring shorter development times.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 432
2b 9618 W21 P22
2 (b) A software company is working on a project to develop a website for a school.
The school principal has some ideas about the appearance of the website but is unclear
about all the details of the solution. The principal would like to see an initial version of the
website.
(i) Identify a life cycle method that would be appropriate in this case.
Give a reason for your choice.
Life cycle method ..............................................................................................................
Reason ..............................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
[2]
(ii) The website project has progressed to the design stage.
State three activities that will take place during the design stage of the program development
life cycle.
1 ........................................................................................................................................
2 ........................................................................................................................................
3 ........................................................................................................................................
[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 433
3b 9618 s22p22
1 (a) A programmer is testing a program using an Integrated Development Environment
(IDE).
The programmer wants the program to stop when it reaches a specific instruction or program
statement in order to check the value assigned to a variable.
Give the technical term for the position at which the program stops.
.............................................................................................................................................
[1]
(b) The following table lists some activities from the program development life cycle.
Complete the table by writing the life cycle stage for each activity.
[4]
Activity Life cycle stage
An identifier table is produced.
Syntax errors can occur.
The developer discusses the program requirements with the customer.
A trace table is produced.
(c) An identifier table includes the names of identifiers used.
State two other pieces of information that the identifier table should contain.
1 ................................................................................................................................................
2 .............................................................................................................................................[2]
Marking Scheme
1 (a) Break Point
1 (b) Design, Coding, Analysis, Testing

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 434
3c 9618 S22 P23
8 The following diagram shows the incomplete waterfall model of the program development
life cycle.
(a) Complete the diagram. [3]

(b) Explain the meaning of the downward and upward arrows.


Downward arrows .....................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
Upward arrows .........................................................................................................................
...................................................................................................................................................
................................................................................................................................................ [2]
(c) Identify another type of model for the program development life cycle.
............................................................................................................................................. [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 435

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 436
3c 9618 S22 P23
2 A program has been written to implement a website browser and maintenance is now
required.
One type of maintenance is called perfective.
Name two other types of maintenance that the program may require and give a reason for
each.
Type 1 ........................................................................................................................................
Reason ......................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...................................................................................................................................................
Type 2 .......................................................................................................................................
Reason .......................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
........................................................................................................................................... [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 437
ͳʹǤ͵”‘‰”ƒ‡•–‹‰ƒ†ƒ‹–‡ƒ ‡
12.3 Program Testing and maintenance
Candidates should be able to: Notes and guidance
Show understanding of ways of exposing and
avoiding faults in programs
Locate and identify the different types of errors • syntax errors
• logic errors
• run-time errors
Correct identified errors
Show understanding of the methods of testing Including dry run, walkthrough, white-box, black-
available and select appropriate data for a given box, integration, alpha, beta, acceptance, stub
method
Show understanding of the need for a test
strategy and test plan and their likely contents
Choose appropriate test data for a test plan Including normal, abnormal and
extreme/boundary
Show understanding of the need for continuing Including perfective, adaptive, corrective
maintenance of a system and the differences
between each type of maintenance
Analyse an existing program and make
amendments to enhance functionality

Program Faults
A program fault is something that makes the program not to do what is supposed to do under
certain circumstance.
Programs are written by human, and to err is human. What we can do is exposing and
avoiding program faults. The reasons of program faults are:
• the programmer has made a coding mistake
• the requirement specification was not drawn up correctly
• the software designer has made a design error
• the user interface is poorly designed, and the user makes mistakes
• computer hardware experiences failure.
Ways to expose and minimise program faults:
System development life cycle plays an important role in avoiding program faults.
Faults in an executable program are frequently faults in the design of the program.
Fault avoidance starts with the provision of a comprehensive and rigorous program
specification at the end of the analysis phase of the program development lifecycle, followed
by the use of formal methods such as structure charts, state-transition diagrams and
pseudocode at the design stage.
At the coding stage, the use of programming disciplines such as information hiding,
encapsulation and exception handling, as described in Chapter 20, all help to prevent faults.
Faults or bugs in a program are then exposed at the testing stage. Testing will show the
presence

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 438
of faults to be corrected, but cannot guarantee that large, complex programs are fault free
under
all circumstances. Faults can appear during the lifetime of a program and may be exposed
during
live running. The faults are then corrected as part of the maintenance stage of the program
lifecycle.
Means to avoid faults:
To avoid faults subroutines and programs are tested. Modular programming techniques (to
break the problem down and make it easier to solve) are used. Good programming practice
like formatting, sensible variable names, comments etc. are also helpful in avoiding program
fault. An IDE is used during coding stage having features like parameter type-checking, auto-
complete. Some software development IDEs check the source code for syntax errors in real-
time.
Locate and identify the different types of errors.
Errors in program can be classified as follows:
1. Syntax Error
2. Run-Time Error
3. Logic Error
Syntax error
an error in which a program statement does not follow the rules of the programming language
(grammar of programming language). For example, a message to be printed if written without
quotation marks, or space in variable name.
Syntax error prevent an application from being successfully compiled, programs cannot be
executed.
Some software development IDEs check the source code for syntax errors in real-time, while
others only generate syntax errors when a program is compiled.
In most cases, the compiler or interpreter provides the location (or line number) of the syntax
error, making it easy for the programmer to find and fix the error.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 439

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 440
Run-time Error
A runtime error occurs when a program is syntactically correct but contains an issue that is
only detected during program execution. These issues cannot be caught at compile-time.

Divide by zero, numeric overflow are examples of run-time error. Run-time error may be
identified by careful testing in an IDE. They are much more difficult to discover, as program
appears to work until a certain set of data causes a malfunction.
Logic Error
An error in the logic of program, program is executed but not work as it is intended to be. It
causes program to operate incorrectly, but not to terminate abnormally (or crash). A logic
error produces unintended or undesired output or other behaviour, although it may not
immediately be recognized as such. Because a program with a logic error is a valid program
in the language, though it does not behave as intended.

Often the only clue to the existence of logic errors is the production of wrong solutions, though
static analysis may sometimes spot them.
Why errors in a program are called BUG

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 441
The term "bug" was used in an account by computer pioneer Grace Hopper, who publicized the cause of a
malfunction in an early
electromechanical computer. A typical
version of the story is:

“In 1946, when Hopper was released


from active duty, she joined the
Harvard Faculty at the Computation
Laboratory where she continued her
work on the Mark II and Mark III.
Operators traced an error in the Mark
II to a moth trapped in a relay, coining
the term bug. This bug was carefully
removed and taped to the log book.
Stemming from the first bug, today we
call errors or glitches in a program.”
a bug. Courtesy Wikipedia

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 442
Integrated Development Environment
An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. An IDE
normally consists of at least a source code editor, debugger, compiler and/or interpreter,
tester and documenter.

Code
editor

Document Debugger

IDE
Compiler/
Test
Interpreter

Source code editor


IDE provides a text editor to type and edit the program code.
A source code editor allows a program to be written and edited without the need to use a
separate text editor. The use of an integrated source code editor speeds up the development
process, as editing can be done without changing to a different piece of software each time
the program needs correcting or adding to.
Pretty printing is a feature of IDE that refers to the presentation of the program code typed
into an editor. For example, IDE automatically colour-codes keywords, built-in function, calls,
comments, strings, and the identifier in a function header. In addition, indentation is
automatic.
Dynamic Syntax Checking is also offered by some source code editors. When a line has
been typed, some editors perform syntax checks and alert the programmer to errors.
Context-sensitive prompts feature displays hints (or a choice of keywords) and available
identifiers that might be appropriate at the current insertion point of the program code.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 443
Testing Methods:
Trace table – a table showing the process of dry-running a program with columns showing
the values of each variable as it changes.
Run-time error – an error found in a program when it is executed; the program may halt
unexpectedly.
Test strategy – an overview of the testing required to meet the requirements specified for a
particular program; it shows how and when the program is to be tested.
Test plan – a detailed list showing all the stages of testing and every test that will be
performed for a particular program.
Dry run – a method of testing a program that involves working through a program or module
from a program manually.
Walkthrough – a method of testing a program. A formal version of a dry run using predefined
test cases.
Normal test data – test data that should be accepted by a program.
Abnormal test data – test data that should be rejected by a program.
Extreme test data – test data that is on the limit of that accepted by a program.
Boundary test data – test data that is on the limit of that accepted by a program or data that
is just outside the limit of that rejected by a program.
White-box testing – a method of testing a program that tests the structure and logic of every
path through a program module.
Black-box testing – a method of testing a program that tests a module’s inputs and outputs.
Integration testing – a method of testing a program that tests combinations of program
modules that work together.
Stub testing – the use of dummy modules for testing purposes.
Alpha testing – the testing of a completed or nearly completed program in-house by the
development team.
Beta testing – the testing of a completed of off-the shelf program by a small group of users
before it is released.
Acceptance testing – the testing of a completed bespoke program to prove to the customer
that it works as required.
Corrective maintenance – the correction of any errors that appear during use.
Perfective maintenance – the process of making improvements to the performance of a
program.
Adaptive maintenance – the alteration of a program to perform new tasks.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 444
2ac 9618 W21 P21 23
4 A program controls the heating system in a sports hall.
Part of the program involves reading a value from a sensor. The sensor produces a numeric
value that represents the temperature. The value is an integer, which should be in the range 0
to 40 inclusive.
A program function has been written to validate the values from the sensor.
(a) A test plan is needed to test the function.
Complete the table. The first line has been completed for you.
You can assume that the sensor will generate only integer data values.
[4]
Test Test data value Explanation Expected outcome
1 23 Normal data Data is accepted
2
3
4
5

4 (a) An inexperienced user buys a games program. A program fault occurs while the user is
playing the game. Explain what is meant by a program fault.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 445
(b) Give three ways to minimise the risk of faults when writing programs.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
............................................................................................................................................. [3]
(c) Three types of program error are syntax, logic and run-time.
Define these three types.
Syntax error ..............................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
Logic error ................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
Run-time error ..........................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 446

The testing stage is part of the program development cycle.


(i) The program for the music player has been completed. The program does not contain any
syntax errors, but testing could reveal further errors.
Identify and describe one different type of error that testing could reveal.
Type ..................................................................................................................................
Description ........................................................................................................................
...........................................................................................................................................
........................................................................................................................................... [2]
(ii) Stub testing is a technique often used in the development of modular programs.
Describe the technique.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
..................................................................................................................................... [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 447

2 (a) Describe the program development cycle with reference to the following:
• source code
• object code
• corrective maintenance.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]
(b) Give three features of an Integrated Development Environment (IDE) that can help with
initial error detection while writing the program.
1 ................................................................................................................................................
...................................................................................................................................................
2 ................................................................................................................................................
...................................................................................................................................................
3 ................................................................................................................................................
................................................................................................................................................ [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 448

(b) Identify and describe one feature of an Integrated Development Environment (IDE) that
can help with program presentation.
Feature .....................................................................................................................................
Description ................................................................................................................................
................................................................................................................................................ [2]
(c) By value is one method of passing a parameter to a subroutine.
Identify and describe the other method.
Method ......................................................................................................................................
Description ................................................................................................................................
...................................................................................................................................................
............................................................................................................................................... [2]
(d) Explain the term adaptive maintenance.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 449

2 (a) (i) Procedures and functions are examples of subroutines.


State a reason for using subroutines in the construction of an algorithm.
.....................................................................................................................................................
............................................................................................................................................... [1]
(ii) Give three advantages of using subroutines in a program.
1 ........................................................................................................................................
...........................................................................................................................................
2 ........................................................................................................................................
...........................................................................................................................................
3 ........................................................................................................................................
...........................................................................................................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 450
(iii) The following pseudocode uses the subroutine DoSomething().
Answer Å23 + DoSomething("Yellow")
State whether the subroutine is a function or a procedure. Justify your answer.
Type of subroutine .............................................................................................................
Justification .......................................................................................................................
...........................................................................................................................................[2]
(b) The program development cycle involves writing, translating and testing a high-level
language
program. Describe these activities with reference to each of the following:
• editor
• translator
• debugger
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.............................................................................................................................................. [3]
(c) The following lines of code are taken from a high-level language program.
WHEN Result < 20
{
Call ResetSensor(3)
Result :=GetSensor(3)
}
Identify the type of control structure and describe the function of the code.
Control structure ........................................................................................................................
Function of code ........................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
......................................................[3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 451

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 452

9608 Winter 18 P22


3 (a) Programming is sometimes referred to as a transferable skill.
You are asked to work on a program written in a language you are not familiar with.
Explain how transferable skills would help you work on the program.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................[2]
(b) Stepwise refinement is often used in the development of an algorithm.
Describe stepwise refinement.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................[2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 453
(c) A program needs to search through 1000 elements of an unsorted array to find a given
value.
The program will output:
• either the position in the array of the value
• or the message “Not Found”
Outline the steps the program needs to follow.
Do not write pseudocode or program code.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................[4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 454
ͳʹǤʹ–ƒ–‡”ƒ•‹–‹‘‹ƒ‰”ƒ
Syllabus Outline
Show understanding of the purpose of state-transition diagrams to document an algorithm

State: a value or a position of a system at a given point.


Transition: The change from one state to another state.
Event: Something that can happen within a system, such as a timer event, or an input to the
system, that may trigger a transition to another state.
Guard Condition: A condition which must be met for a transition to occur from one state to
another
A finite-state machine (FSM): A system that consists of a fixed set of possible states with a
set of allowable inputs that may change the state and a set of possible outputs.
State transition diagram: A graphical representation of a finite state machine
State transition table: A table that shows all the states of an FSM, all possible inputs and the
state resulting from each input
A finite-state machine (FSM) is a mathematical model of computation. It is a machine that
can be in exactly one of a finite number of states at any given time. The FSM can change
from one state to another in response to some inputs; the change from one state to another is
called a transition.
An FSM is defined by a list of its states, its initial state, and the inputs that trigger each
transition.
The behaviour of state machines can be observed in many devices in modern society that
perform a predetermined sequence of actions depending on a sequence of events with which
they are presented.
State-transition diagrams give a visual representation of all the states that a system can
have, the events such as inputs or timers that may result in transition between states, and
the transitions between states. They may also show the conditions needed for an event(s) to
cause a transition to occur (the guard condition), and the outputs or actions carried out as the
result of a transition.
There are different conventions for state-transition diagrams, but states are normally
represented as nodes, transitions as interconnecting arrows, and events as labels on the
arrows. Conditions are normally specified in square brackets after the event label. The initial
state is indicated by an arrow with a black dot.
Simple examples are:

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 455
vending machines, which dispense products when the proper combination of coins is
deposited;
elevators, whose sequence of stops is determined by the floors requested by riders;
traffic lights, which change sequence when cars are waiting;
combination locks, which require the input of a sequence of numbers in the proper order.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 456
Worked Example: Coin-operated Turnstile
An example of a simple mechanism that can be
modelled by a state machine is a turnstile. A turnstile,
used to control access to subways and amusement
park rides, is a gate with three rotating arms at waist
height, one across the entryway. Initially the arms are
locked, blocking the entry, preventing patrons from
passing through. Depositing a coin or token in a slot
on the turnstile unlocks the arms,
allowing a single customer to push
through. After the customer passes
through, the arms are locked again until another coin is inserted.
Considered as a state machine, the turnstile has two possible states: Locked and
Unlocked. There are two possible inputs that affect its state: putting a coin in the slot
(coin) and pushing the arm (push). In the locked state, pushing on the arm has no effect;
no matter how many times the input push is given, it stays in the locked state. Putting a
coin in – that is, giving the machine a coin input – shifts the state from Locked to
Unlocked. In the unlocked state, putting additional coins in has no effect; that is, giving
additional coin inputs does not
change the state. However, a
customer pushing through the arms,
giving a push input, shifts the state
back to Locked.
The turnstile state machine can be
represented by a state-transition
table, showing for each possible state,
the transitions between them (based upon the inputs given to the machine) and the outputs resulting from
each input:

Current State Input Next State Output

coin Unlocked Unlocks the turnstile so that the customer can push through.
Locked
push Locked None
coin Unlocked None
Unlocked
push Locked When the customer has pushed through, locks the turnstile.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 457
Worked example – media player
The example below shows a simple state-transition diagram for a media player with three
buttons: stop, play and pause.
The initial state of the player is stopped. In each state, only the buttons for the other states
can be pressed (e.g. in play, only the stop and pause buttons can be pressed). Pressing the
pause button when the player is stopped does not result in any change to the player.

The event (press pause when state is Stopped) that does not cause any change in state is
indicated by the circular arrow.
A finite-state machine can also be represented by a state-transition table, which lists all the
states, all possible events, and the resulting state. The following is the state-transition table
for the diagram above:
Current State Event Next State
Stopped Press play button Play
Stopped Press pause button Stopped
Play Press stop button Stopped
Play Press pause button Paused
Paused Press play button Play
Paused Press stop button Stopped

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 458
Worked example – combination lock
State-transition diagrams are also useful for showing the working of algorithms that involve a
finite number of states. The following algorithm is for a three-digit combination lock where the
correct combination to unlock is ‘367’. The initial state is Locked, each correct digit changes
the state, until the combination unlocks the lock. An incorrect digit returns the lock to the
original locked state.

DECLARE State : String


DECLARE Number : Integer
State ÅLocked
INPUT Number
CASE OF Number
3 : IF State = Locked THEN
State Å1stDigit
ENDIF
6 : IF State = 1stDigit THEN
State Å2ndDigit
ELSE
State ÅLocked
ENDIF
7 : IF State = 2ndDigit THEN
State ÅUnlocked
ELSE
State ÅLocked
ENDIF
ENDCASE
Draw state-transition diagram for the algorithm:

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 459
Note: The double line around the Unlocked state indicates that lock halts in this state – this is
also known as the ‘accepting state’.

1b 9618 S21 P22


2 (a) Examine the following state-transition diagram.

(i) Complete the table with reference to the diagram.


[4]
Answer
The number of transitions that result in a different state
The number of transitions with associated outputs
The label that should replace ‘X’
The final or halting state
(ii) The current state is S1. The following inputs occur.
1. Low level detected
2. Low level detected
3. Low level detected
4. Low level detected
Give the number of outputs and the current state.
Number of outputs .............................................................................................................
Current state ..................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 460
2ac 9618 W21 P22-23
(b) A program module controls the heaters. This module operates as follows:
• If the temperature is below 10, switch the heaters on.
• If the temperature is above 20, switch the heaters off.
Complete the following state-transition diagram for the heating system:
[3]

3a 9618 S22 P21


2 Examine the following state-transition diagram.

(a) Complete the table with reference to the diagram. [3]


Answer
The number of different inputs
The number of different outputs
The single input value that could result in S4

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 461
(b) The initial state is S1.
Complete the table to show the inputs, outputs and next states.
[4]
Input Output Next state
Button-Y
None
Button-Z S2
None

1b 9618 S21 P22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 462
2ac 9618 W21 P21 23

3a 9618 S22 P21

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 463
1. Create a state transition diagram for the following system.
A door can be in one of the following three states:
xOpened
xClosed
xLocked
The door is initially open.
An open door can be closed if the condition that the doorway is empty is met.
A closed door can be opened.
A closed door can be locked.
A locked door can be unlocked.

2. Create a state transition diagram for the following system.


A burglar alarm has three states:
xOff
xAlarmed (the alarm is switched on)
xSounding
The possible inputs are: turning the alarm on or off with a key, and sensors on (movement detected
which sounds the alarm) or off. The state-transition table that describes the burglar alarm is a follows:
Current State Key Sensors Next State
Off Off On Off
Off On Off Alarmed
Off On On Sounding
Alarmed Off Off Off
Alarmed Off On Off
Alarmed On On Sounding
Sounding Off Off Off
Sounding Off On Off
Sounding On Off Alarmed

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 464
3. Draw a state-transition diagram for the following algorithm for a bank account. The account
has two states, one for zero balance, and one for a positive balance. Withdrawals are not
allowed if this would cause a negative balance.
DECLARE State : String
DECLARE Transaction : Integer
DECLARE Balance : Integer

State ÅZeroBalance
Balance = 0

INPUT Transaction
// Calculate the new balance, first saving the current balance in case the
transaction cannot be made
OldBalance ÅBalance
Balance ÅBalance + Transaction
IF Transaction > 0 THEN // This is a deposit
State ÅPositiveBalance
ELSE IF Transaction < 0 THEN // This is a withdrawal
CASE OF Balance
= 0 : State ÅZeroBalance
> 0 : State ÅPositiveBalance
< 0 : Balance ÅOldBalance // As the balance would be negative, no
transaction can be made

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 465
An intruder detection system is inactive when the power is switched off. The system is
activated when the power is switched on. When the system senses an intruder the alarm bell
rings. A reset button is pressed to turn the alarm bell off and return the system to the active
state.
The transition from one state to another is as shown in the state transition table below.
Current state Event Next state
System inactive Switch power on System active
System active Senses intruder Alarm bell rings
System active Switch power off System inactive
Alarm bell rings Press reset button System active
Alarm bell rings Switch power off System inactive

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 466
Summer 2015 9608/41/42

1 A turnstile is a gate which is in a locked state. To open it and pass through, a customer
inserts a coin into a slot on the turnstile. The turnstile then unlocks and allows the customer to
push the turnstile and pass through the gate.
After the customer has passed through, the turnstile locks again. If a customer pushes the
turnstile while it is in the locked state, it will remain locked until another coin is inserted.
The turnstile has two possible states: locked and unlocked. The transition from one state to
another is as shown in the table below.
Current state Event Next state
Locked Insert coin Unlocked
Locked Push Locked
Unlocked Attempt to insert coin Unlocked
Unlocked Pass through Locked
Complete the state transition diagram for the turnstile:

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 467
Summer 2015 9608/43
1 A petrol filling station has a single self-service petrol pump.
A customer can use the petrol pump when it is ready to dispense petrol.
The pump is in use when the customer takes the nozzle from a holster on the pump.
The pump dispenses petrol while the customer presses the trigger on the nozzle.
When the customer replaces the nozzle into the holster, the pump is out of use.
The cashier must press a reset button to make the pump ready for the next customer to use.
The petrol pump’s four possible states and the transition from one state to another are as
shown in the table below.
Current state Event Next state
Pump ready Take nozzle Pump in use
Pump in use Press trigger Pump dispensing
Pump dispensing Stop pressing trigger Pump in use
Pump in use Replace nozzle Pump out of use
Pump out of use Reset pump display Pump ready
Complete the state transition diagram for the petrol pump:

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 468
Summer 2016 9608/41/42/43
6 In a board game, one player has white pieces and the other player has black pieces. Players take
alternate turns to move one of their pieces. White always makes the first move.
The game ends if:
• a player is unable to make a move when it is their turn. In this case, there is no winner. This is called
‘stalemate’.
• a player wins the game as a result of their last move and is called a ‘winner’.
(a) A state-transition diagram is drawn to clarify how the game is played.
Complete the following state-transition diagram. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 469
Winter 2017 Paper 41_43
1 A greenhouse has a window that automatically opens and closes depending on the internal
temperature.
If the temperature rises above 20°C, the window half opens. If the temperature rises above
30°C, the window fully opens. If the temperature drops below 25°C, the window returns to
being half open. If the temperature drops below 15°C, the window fully closes.
The window has three possible states: Closed, Half Open and Fully Open.
Current state Event Next state
Closed Temperature rises above 20°C Half Open
Half Open Temperature drops below 15°C Closed
Half Open Temperature rises above 30°C Fully Open
Fully Open Temperature drops below 25°C Half Open
Complete the state-transition diagram for the window: [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 470
Winter 2019 Paper 41
(c) The university wants to analyse how a printer and a print server deal with the print jobs.
The following table shows the transitions from one state to another for the process.
Current state Event Next state
Printer idle Print job sent Printer active
Printer active Print job added to queue Print job received
Print job received Print job in progress Print job successful
Print job received Print job in progress Print job unsuccessful
Print job successful Check print queue Printer active
Print job unsuccessful Error message displayed Printer active
Printer active Timeout Printer idle
Complete the state-transition diagram for the table.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 471
Winter 2019 Paper 42
4 A bank wants to analyse how an automated teller machine (ATM) deals with transactions.
The following state-transition table shows the transitions from one state to another for a transaction.
Current state Event Next state
ATM active Insert card Waiting for PIN
Waiting for PIN Enter PIN Checking PIN
Waiting for PIN Cancel selected Transaction cancelled
Checking PIN PIN valid Account accessed
Checking PIN PIN invalid Waiting for PIN
Account accessed Cancel selected Transaction cancelled
Account accessed Input amount to withdraw Checking account
Checking account Funds available Transaction complete
Transaction complete Return card and dispense cash ATM active
Checking account Funds not available Account accessed
Transaction cancelled Return card ATM active
Complete the state-transition diagram to correspond with the table.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 472
End of the Paper Algorithms
0 9618 Specimen Paper 2
6 Members of a family use the same laptop computer. Each family member has their own
password.
To be valid, a password must comply with the following rules:
1 At least two lower-case alphabetic characters
2 At least two upper-case alphabetic characters
3 At least three numeric characters
4 Alpha-numeric characters only
A function, ValidatePassword, is needed to check that a given password follows these rules.
This function takes a string, Pass, as a parameter and returns a boolean value:
• TRUE if it is a valid password
• FALSE otherwise
(a) Write pseudocode to implement the function ValidatePassword.
Refer to the Insert for the list of pseudocode functions and operators.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...........................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.....................................................................................................................................................
............................................................................................................................................ [9]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 473
(b) The ValidatePassword function will be tested.
(i) Give a valid password that can be used to check that the function returns TRUE under the
correct conditions.
Password1: .................................................................................................................. [1]
(ii) Password1 is modified to test each rule separately. Give four modified passwords and
justify your choice.
Password to test rule 1: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Password to test rule 2: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Password to test rule 3: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
Password to test rule 4: .....................................................................................................
Reason: .............................................................................................................................
...........................................................................................................................................
........................................................................................................................................... [4]
(iii) When testing the ValidatePassword function a module it is necessary to test all possible
paths through the code.
State the name given to this type of validation testing.
...................................................................................................................................... [1]
(iv) A program consisting of several functions can be tested using a process known as ‘stub
testing’ Explain this process.
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...................................................................................................................................... [2]

7 LogArray is a 1D array containing 500 elements of type STRING.


A procedure, LogEvents, is required to add data from the array to the end of the existing text

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 474
file LoginFile.txt
Unused array elements are assigned the value "Empty". These can occur anywhere in the
array and should not be added to the file.
Write pseudocode for the procedure LogEvents.
Refer to the Insert for the list of pseudocode functions and operators.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
..................................................
.....................................................................................................................................................
.....
.....................................................................................................................................................
.....
.....................................................................................................................................................
.....
.....................................................................................................................................................
.....
.....................................................................................................................................................
.....
.....................................................................................................................................................
.....
.....................................................................................................................................................
[8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 475
1ac 9618 S21 P21-23
7 A program is needed to take a string containing a full name and produce a new string of
initials.
Some words in the full name will be ignored. For example, "the", "and", "of", "for" and "to" may
all be ignored. Each letter of the abbreviated string must be upper case.
For example:
Full name Initials
Integrated Development Environment IDE
The American Standard Code for Information Interchange ASCII
The programmer has decided to use a global variable FNString of type STRING to store the
full name.
It is assumed that:
• words in the full name string are separated by a single space character
• space characters will not occur at the beginning or the end of the full name string
• the full name string contains at least one word.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 476
The programmer has started to define program modules as follows:
Module Description
• Called with an INTEGER as a parameter, representing the number of a word in
FNString.
GetStart() • Returns the character start position of that word in FNString or returns –1 if that
word does not exist
• For example: if FNString contains the string "hot and cold", GetStart(3) returns 9
• Called with a parameter representing the position of the first character of a word in
FNString
GetWord() • Returns the word from FNString
• For example: if FNString contains the string "hot and cold", GetWord(9) returns
"cold"
(a) Write pseudocode for the module GetStart().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]
(b) The programmer has decided to use a global ten-element 1D array IgnoreList of type
STRING to store the ignored words. Unused elements contain the empty string ("") and may

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 477
occur anywhere in the array.
A new module AddWord() is needed as follows:
Module Description
• Called with a parameter representing a word
AddWord() • Stores the word in an unused element of the IgnoreList array and returns TRUE
• Returns FALSE if the array was already full or if the word was already in the array
Write a detailed description of the algorithm for AddWord(). Do not include pseudocode
statements in your answer.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [4]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 478
(c) As a reminder, the module description of GetWord() is repeated:
Module Description
• Called with a parameter representing the position of the first character of a
word in FNString
GetWord() • Returns the word from FNString
• For example: if FNString contains the string "hot and cold", GetWord(9)
returns "cold"
Write pseudocode for the module GetWord().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [5]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 479
1b 9618 S21 P22
6 A procedure CountVowels() will:
• be called with a string containing alphanumeric characters as its parameter
• count and output the number of occurrences of each vowel (a, e, i, o, u) in the string
• count and output the number of occurrences of the other alphabetic characters (as a single
total).
The string may contain both upper and lower case characters.
Each count value will be stored in a unique element of a global 1D array CharCount of type
INTEGER. The array will contain six elements.
Write pseudocode for the procedure CountVowels().
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................................................ [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 480
8 A program is needed to take a string containing a full name and to produce a new string of
initials.
Some words in the full name will be ignored. For example, “the”, “and”, “of”, “for” and “to” may
all be ignored.
Each letter of the new string must be upper case.
For example:
Full name Initials
Integrated Development Environment IDE
The American Standard Code for Information Interchange ASCII
The programmer has decided to use the following global variables:
• a ten element 1D array IgnoreList of type STRING to store the ignored words
• a string FNString to store the full name string.
Assume that:
• each alphabetic character in the full name string may be either upper or lower case
• the full name string contains at least one word.
The programmer has started to define program modules as follows:
Module Description
• Called with an INTEGER as its parameter, representing the number of a
word in FNString
GetStart() • Returns the character start position of that word in FNString or returns -1 if
that word does not exist
• For example: GetStart(3) applied to "hot and cold" returns 9
• Called with the position of the first character of a word in FNString as its
parameter
GetWord() • Returns the word from FNString
• For example: if FNString contains the string "hot and cold", GetWord(9)
returns "cold"
• Called with a STRING parameter representing a word
IgnoreWord() • Searches for the word in the IgnoreList array
• Returns TRUE if the word is found, otherwise returns FALSE
• Processes the sequence of words in the full name one word at a time
• Calls GetStart(), GetWord() and IgnoreWord() to process each word to form
GetInitials()
the new string
• Outputs the new string
(a) Write pseudocode for the module IgnoreWord().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 481
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [5]
(b) Write pseudocode for the module GetInitials().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 482
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [8]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 483
2ac 9618 W21 P21 P23
5 The following data items will be recorded each time a student successfully logs on to the
school network:
Data item Example data
Student ID "CJL404"
Host ID "Lib01"
Time and date "08:30, June 01, 2021"
The Student ID is six characters long. The other two data items are of variable length.
A single string will be formed by concatenating the three data items. A separator character will
need to be inserted between items two and three.
For example:
"CJL404Lib01<separator>08:30, June 01, 2021"
Each string represents one log entry.
A programmer decides to store the concatenated strings in a 1D array LogArray that contains
2000 elements. Unused array elements will contain an empty string.
(a) Suggest a suitable separator character and give a reason for your choice.
Character ..................................................................................................................................
Reason .....................................................................................................................................
............................................................................................................................................... [2]
(b) The choice of data structure was made during one stage of the program development life
cycle.
Identify this stage.
............................................................................................................................................. [1]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 484
(c) A function LogEvents() will:
• take a Student ID as a parameter
• for each element in the array that matches the Student ID parameter:
◦ add the value of the array element to the existing text file LogFile
◦ assign an empty string to the array element
• count the number of lines added to the file
• return this count.
Write pseudocode for the function LogEvents().
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 485
2ac 9618 W21 P21 P23 6 A mobile phone has a touchscreen. The screen is represented by
a grid, divided into 800 rows and 1280 columns.
The grid is represented by a 2D array Screen of type INTEGER. An array element will be set
to 0 unless the user touches that part of the screen.
Many array elements are set to 1 by a single touch of a finger or a stylus.
The following diagram shows a simplified touchscreen. The dark line represents a touch to
the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These
elements are shaded. The element shaded in black represents the centre point.

A program is needed to find the coordinates (the row and column) of the centre point. The
centre point on the diagram above is row 6, column 11.
Assume:
• the user may only touch one area at a time
• screen rotation does not affect the touchscreen.
The programmer has started to define program modules as follows:
Module Description
• Called with three parameters of type INTEGER:
◦ a row number
SetRow()
◦ the number of pixels to be skipped starting from column 1
(generates test
◦ the number of pixels that should be set to 1
data)
• Sets the required number of pixels to 1
For example, SetRow(3, 8, 5) will give row 3 as in the diagram shown.
• Takes two parameters of type INTEGER:
◦ a row number
◦ a start column (1 or 1280)
SearchInRow() • Searches the given row from the start column (either left to right or right to left)
for the first column that contains an element set to 1
• Returns the column number of the first element in the given row that is set to 1
• Returns -1 if no element is set to 1
• Takes two parameters of type INTEGER:
◦ a column number
◦ a start row (1 or 800)
SearchInCol() • Searches the given column from the start row (either up or down) for the first
row that contains an element set to 1
• Returns the row number of the first element in the given column that is set to 1
• Returns -1 if no element is set to 1

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 486
(a) Write pseudocode to implement the module SetRow().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [5]
(b) The module description of SearchInRow() is provided here for reference.
Module Description
• Takes two parameters of type INTEGER:
◦ a row number
◦ a start column (1 or 1280)
SearchInRow() • Searches the given row from the start column (either left to right or right to left)
for the first column that contains an element set to 1
• Returns the column number of the first element in the given row that is set to 1
• Returns -1 if no element is set to 1
Write pseudocode to implement the module SearchInRow().
...................................................................................................................................................
...................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
...............................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 487
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [8]
(c) The following new module is introduced:
Module Description
• Called with a row number as an INTEGER
• Uses SearchInRow() to find the first and last columns in the given row which
GetCentreCol() have an array element set to 1
• Returns the index of the column midway between the first and last columns
• Returns -1 if no element is set to 1
Write pseudocode to implement the module GetCentreCol().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...............................................................................................................................................[6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 488
2b 9618 W21 P22
5 A company has several departments. Each department stores the name, email address and
the status of each employee in that department in its own text file. All text files have the same
format.
Employee details are stored as three separate data strings on three consecutive lines of the
file.
An example of the first six lines of one of the files is as follows:
File line Comment
1 First employee name
2 First email address
3 First employee status
4 Second employee name
5 Second email address
6 Second employee status
A procedure MakeNewFile() will:
• take three parameters as strings:
○ an existing file name
○ a new file name
○ a search status value
• create a new text file using the new file name
• write all employee details to the new file where the employee status is not equal to the
search status value
• count the number of sets of employee details that were in the original file
• count the number of sets of employee details that were written to the new file
• produce a summary output.
An example summary output is as follows:
File Marketing contained 54 employee details
52 employee sets of details were written to file
NewMarketingList
(a) Write pseudocode for the procedure MakeNewFile().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 489
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................[7]
(b) An alternative format could be used for storing the data.
A text file will still be used.
(i) Describe the alternative format.
.....................................................................................................................................................
........................................................................................................................... [1]
(ii) State one advantage and one disadvantage of the alternative format.
Advantage .........................................................................................................................
...........................................................................................................................................
Disadvantage ....................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 490
6 A mobile phone has a touchscreen. The screen is represented by a grid, divided into 800
rows and 1280 columns.
The grid is represented by a 2D array Screen of type INTEGER. An array element will be set
to 0 unless the user touches that part of the screen.
Many array elements will set to 1 by a single touch of a finger or a stylus.
The following diagram shows a simplified touchscreen. The dark line represents a touch on
the screen. All grid elements that are wholly or partly inside the outline will be set to 1. These
elements are shaded.
The element shaded in black represents the centre point of the touch.

A program is needed to find the coordinates (the row and column) of the centre point. The
centre point on the diagram shown is row 6, column 11. Assume:
• the user may only touch one area at a time
• screen rotation does not affect the touchscreen.
The programmer has decided to use global values CentreRow and CentreCol as coordinate
values for the centre point. The programmer has started to define program modules as
follows:
Module Description
• Searches for the first row that has an array element set to 1
FirstRowSet() • Returns the index of that row (1 is the first row)
• Returns -1 if there are no elements set to 1
• Searches for the last row that has an array element set to 1
LastRowSet() • Returns the index of that row
• Returns -1 if there are no elements set to 1
• Searches for the first column that has an array element set to 1
FirstColSet() • Returns the index of that column (1 is the first column)
• Returns -1 if there are no elements set to 1
• Searches for the last column that has an array element set to 1
LastColSet() • Returns the index of that column
• Returns -1 if there are no elements set to 1
(a) Write efficient pseudocode for the module FirstRowSet().
.....................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 491
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................................................. [7]
(b) Describe a feature of your solution to part (a) that indicates the pseudocode represents an
efficient algorithm.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
....................................................................................................................................... [2]
(c) The programmer decides to produce a single search module FindSet(), which will be able
to perform each of the individual searches performed by the first four modules in the table.
(i) Outline the changes needed to convert one of the existing modules into this single module.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
................................................................................... [2]
(ii) Give one possible advantage and one possible disadvantage of combining the four
searches into a single module.
Advantage .........................................................................................................................
...........................................................................................................................................
Disadvantage ....................................................................................................................
........................................................................................................................................... [2]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 492
(d) An additional module GetCentre() is defined as follows:
Module Description
• Calculates the coordinates of the centre point
• Uses the four modules: FirstRowSet(), LastRowSet(), FirstColSet(), LastColSet()
GetCentre()
• Assigns values to CentreRow and CentreCol
• Sets CentreRow to -1 if no screen touch is detected
Write pseudocode for the module GetCentre().
.....................................................................................................................................................
.................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 493
3a 9618 S22 P21
8 A program allows a user to save passwords used to login to websites. A stored password is
inserted automatically when the user logs into the corresponding website.
A student is developing a program to generate a password. The password will be of a fixed
format, consisting of three groups of four alphanumeric characters. The groups are
separated by the hyphen character '-'.
An example of a password is: "FxAf-3haV-Tq49"
A global 2D array Secret of type STRING stores the passwords together with the website
domain name where they are used. Secret contains 1000 elements organised as 500 rows by
2 columns.
Unused elements contain the empty string (""). These may occur anywhere in the array.
An example of a part of the array is:
Array
Value
element
Secret[27, 1] "www.thiswebsite.com"
Secret[27, 2] "••••••••••••••"
Secret[28, 1] "www.thatwebsite.com"
Secret[28, 2] "••••••••••••••"
Note:
• For security, passwords are stored in an encrypted form, shown as "••••••••••••••" in the
example.
• The passwords cannot be used without being decrypted.
• Assume that the encrypted form of a password will not be an empty string.
The programmer has started to define program modules as follows:
Module Description
• Generates a single random character from within one of the following ranges:
○ 'a' to 'z'
RandomChar() ○ 'A' to 'Z'
○ '0' to '9'
• Returns the character
• Takes a password as a parameter of type string
Encrypt()
• Returns the encrypted form of the password as a string
• Takes an encrypted password as a parameter of type string
Decrypt()
• Returns the decrypted form of the password as a string

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 494

For reference, relevant ASCII values are as follows:


Character
ASCII range
range
'a' to 'z' 97 to 122
'A' to 'Z' 65 to 90
'0' to '9' 48 to 57

(a) Write pseudocode for module RandomChar().


You may wish to refer to the insert for a description of the CHR() function. Other functions
may also be required.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 495
(b) A new module is defined as follows:
Module Description
• Takes a website domain name as a parameter of type string
• Searches for the website domain name in the array Secret
FindPassword() • If the website domain name is found, the decrypted password is returned
• If the website domain name is not found, a warning message is output,
and an empty string is returned
Write pseudocode for module FindPassword().
Assume that modules Encrypt() and Decrypt() have already been written.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 496
(c) The modules Encrypt() and Decrypt() are called from several places in the main program.
Identify a method that could have been used to test the main program before these modules
were completed. Describe how this would work.
Method ......................................................................................................................................
Description ................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]
(d) A validation function is written to check that the passwords generated are valid.
To be valid, each password must:
• be 14 characters long
• be organised as three groups of four case-sensitive alphanumeric characters. The groups
are separated by hyphen characters
• not include any duplicated characters, except for the hyphen characters.
Note: lower-case and upper-case characters are not the same. For example, 'a' is not the
same as 'A'.
Give two password strings that could be used to test different areas of the validation rules.
Password 1 ...............................................................................................................................
Password 2 ...............................................................................................................................
[2]
(e) The RandomChar() module is to be modified so that alphabetic characters are generated
twice as often as numeric characters.
Describe how this might be achieved.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 497
3B 9618 s22p22
6 A string represents a series of whole numbers, separated by commas.
For example:
"12,13,451,22"
Assume that:
• the comma character ',' is used as a separator
• the string contains only the characters '0' to '9' and the comma character ','.
A procedure Parse will:
• take the string as a parameter
• extract each number in turn
• calculate the total value and average value of all the numbers
• output the total and average values with a suitable message.
Write pseudocode for the procedure.
PROCEDURE Parse(InString : STRING)
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 498
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.
ENDPROCEDURE [7]
7 A programming language has string functions equivalent to those given in the insert.
The language includes a LEFT() and a RIGHT() function, but it does not have a MID()
function.
(a) Write pseudocode for an algorithm to implement your own version of the MID() function
which will operate in the same way as that shown in the insert.
Do not use the MID() function given in the insert, but you may use any of the other functions.
Assume that the values passed to the function will be correct.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [4]
(b) The values passed to your MID() function in part (a) need to be validated.
Assume that the values are of the correct data type.
State two checks that could be applied to the values passed to the function.
1 ................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 499
2 ................................................................................................................................................
............................................................................................................................................... [2]
3B 9618 s22p22
8 A program allows a user to save passwords used to log in to websites. A stored password is
then inserted automatically when the user logs in to the corresponding website.
A global 2D array Secret of type STRING stores the passwords together with the website
domain name where they are used. Secret contains 1000 elements organised as 500 rows by
2 columns.
Unused elements contain the empty string (""). These may occur anywhere in the array.
An example of a part of the array is:
Array element Value
Secret[27, 1] "thiswebsite.com"
Secret[27, 2] "••••••••••••"
Secret[28, 1] "thatwebsite.com"
Secret[28, 2] "••••••••••••"
Note:
• For security, the passwords are stored in an encrypted form, shown as "••••••••••••" in the
example.
• The passwords cannot be used without being decrypted.
• You may assume that the encrypted form of a password will NOT be an empty string.
The programmer has started to define program modules as follows:
Module Description
• Takes two parameters:
○ a string
Exists() ○ a character
• Performs a case-sensitive search for the character in the string
• Returns TRUE if the character occurs in the string, otherwise returns FALSE
• Takes a password as a parameter of type string
Encrypt()
• Returns the encrypted form of the password as a string
• Takes an encrypted password as a parameter of type string
Decrypt()
• Returns the decrypted form of the password as a string
Note: in a case-sensitive comparison, 'a' is not the same as 'A'.
(a) Write pseudocode for the module Exists().
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 500
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [5]
(b) A new module SearchDuplicates() will:
• search for the first password that occurs more than once in the array and output a message
each time a duplicate is found.
For example, if the same password was used for the three websites ThisWebsite.com,
website27.net and websiteZ99.org, then the following messages will be output:
"Password for ThisWebsite.com also used for website27.net"
"Password for ThisWebsite.com also used for websiteZ99.org"
• end once all messages have been output.
The module will output a message if no duplicates are found.
For example:
"No duplicate passwords found"
Write efficient pseudocode for the module SearchDuplicates(). Encrypt() and Decrypt()
functions have been written.
Note: It is necessary to decrypt each password before checking its value.
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 501
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 502
............................................................................................................................................. [8]

(c) A password has a fixed format, consisting of three groups of four alphanumeric characters,
separated by the hyphen character '-'.
An example of a password is:
"FxAf-3haV-Tq49"
Each password must:
• be 14 characters long
• be organised as three groups of four alphanumeric characters. The groups are separated by
hyphen characters
• not include any duplicated characters, except for the hyphen characters.
An algorithm is needed for a new function GeneratePassword(), which will generate and
return a password in this format.
Assume that the following modules have already been written:
Module Description
• Takes two parameters:
○ a string
Exists() ○ a character
• Performs a case-sensitive search for the character in the string
• Returns TRUE if the character occurs in the string, otherwise returns FALSE
• Generates a single random character from within one of the following ranges:
○ 'a' to 'z'
RandomChar() ○ 'A' to 'Z'
○ '0' to '9'
• Returns the character
Note: in a case-sensitive comparison, 'a' is not the same as 'A'.
Describe the algorithm for GeneratePassword().
Do not use pseudocode statements in your answer.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 503
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 504
3c 9618 S22 P23
9 A program allows a user to save passwords used to log in to websites. A stored password is
then inserted automatically when the user logs in to the corresponding website.
A student is developing a program to generate a strong password. The password will be of a
fixed format, consisting of three groups of four alphanumeric characters, separated by the
hyphen character '-'.
An example of a password is: "FxAf-3hzV-Aq49"
A valid password:
• must be 14 characters long
• must be organised as three groups of four alphanumeric characters. The groups are
separated by hyphen characters
• may include duplicated characters, provided these appear in different groups.
The programmer has started to define program modules as follows:
Module Description
• Generates a single random character from within one of the following ranges:
○ 'a' to 'z'
RandomChar() ○ 'A' to 'Z'
○ '0' to '9'
• Returns the character
• Takes two parameters:
○ a string
Exists() ○ a character
• Performs a case-sensitive search for the character in the string
• Returns TRUE if the character occurs in the string, otherwise returns FALSE
• Generates a valid password
Generate() • Uses RandomChar() and Exists()
• Returns the password
Note: in a case-sensitive comparison, 'a' is not the same as 'A'.

(a) Write pseudocode for the module Generate().


...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 505
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [7]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 506
(b) A global 2D array Secret of type STRING stores the passwords together with the website
domain name where they are used. Secret contains 1000 elements organised as 500 rows by
2 columns.
Unused elements contain the empty string (""). These may occur anywhere in the array.
An example of part of the array is:
Array element Value
Secret[27, 1] "www.thiswebsite.com"
Secret[27, 2] "●●●●●●●●●●●●"
Secret[28, 1] "www.thatwebsite.com"
Secret[28, 2] "●●●●●●●●●●●●"
Note:
• For security, the passwords are stored in an encrypted form, shown as "●●●●●●●●●●●●"
in the example.
• The passwords cannot be used without being decrypted.
• You may assume that the encrypted form of a password will not be an empty string.
Additional modules are defined as follows:
Module Description
• Takes a password as a string
Encrypt()
• Returns the encrypted form of the password as a string
• Takes an encrypted password as a string
Decrypt()
• Returns the decrypted form of the password as a string
• Takes a website domain name as a string
• Searches for the website domain name in the array Secret
FindPassword()
• If the website domain name is found, the decrypted password is returned
• If the website domain name is not found, an empty string is returned
• Takes two parameters as strings: a website domain name and a password
• Searches for the website domain name in the array Secret and if not found,
AddPassword() adds the website domain name and the encrypted password to the array
• Returns TRUE if the website domain name and encrypted password are
added to the array, otherwise returns FALSE
The first three modules have been written.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 507
Write pseudocode for the module AddPassword().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [6]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 508
(c) The content of the array Secret is to be stored in a text file for backup.
It must be possible to read the data back from the file and extract the website domain name
and the encrypted password.
Both the website domain name and encrypted password are stored in the array as strings of
characters.
The encrypted password may contain any character from the character set used and the
length of both the encrypted password and the website domain name is variable.
Explain how a single line of the text file can be used to store the website domain name and
the encrypted password.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
............................................................................................................................................. [3]

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 509
0 9618 Specimen Paper 2

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 510

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 511
1ac 9618 S21 P21-23

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 512

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 513

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 514
1b 9618 S21 P22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 515

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 516

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 517

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 518
2ac 9618 W21 P21 P23

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 519

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 520

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 521

2b 9618 W21 P22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 522

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 523

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 524

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 525
3a 9618 S22 P21

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 526

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 527

3B 9618 s22p22

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 528

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 529

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 530

3c 9618 S22 P23

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 531

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 532

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 533
Insert
An error will be generated if a function call is not properly formed or if the parameters are of an
incorrect type or an incorrect value.

String and Character Functions

• A string of length 1 may be either of type CHAR or STRING


• A CHAR may be assigned to, or concatenated with, a STRING
• A STRING of length greater than 1 cannot be assigned to a CHAR
LEFT(ThisString : STRING, x : INTEGER) RETURNS STRING
returns leftmost x characters from ThisString
Example: LEFT("ABCDEFGH", 3) returns "ABC"

RIGHT(ThisString : STRING, x : INTEGER) RETURNS STRING returns


rightmost x characters from ThisString
Example: RIGHT("ABCDEFGH", 3) returns "FGH"

MID(ThisString : STRING, x : INTEGER, y : INTEGER) RETURNS STRING


returns a string of length y starting at position x from ThisString
Example:
MID("ABCDEFGH", 2, 3) returns string "BCD"
LENGTH(ThisString : STRING) RETURNS INTEGER
returns the integer value representing the length of ThisString
Example:
LENGTH("Happy Days") returns 10
TO_UPPER(x : <datatype>) RETURNS <datatype>
<datatype> may be CHAR or STRING
returns an object of type <datatype> formed by converting all characters of x to upper case.
Examples:
• TO_UPPER("Error 803") returns "ERROR 803"
• TO_UPPER('a') returns 'A'
TO_LOWER(x : <datatype>) RETURNS <datatype>
<datatype> may be CHAR or STRING
returns an object of type <datatype> formed by converting all characters of x to lower case.
Examples:
• TO_LOWER("JIM 803") returns "jim 803"
• TO_LOWER('W') returns 'w'
NUM_TO_STR(x : <datatype1>) RETURNS <datatype2>
returns a string representation of a numeric value.
<datatype1> may be REAL or INTEGER, <datatype2> may be CHAR or STRING
Example: NUM_TO_STR(87.5) returns "87.5"

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


Page | 534
STR_TO_NUM(x : <datatype1>) RETURNS <datatype2>
returns a numeric representation of a string.
<datatype1> may be CHAR or STRING, <datatype2> may be REAL or INTEGER
Example: STR_TO_NUM("23.45") returns 23.45
IS_NUM(ThisString : <datatype>) RETURNS BOOLEAN
returns TRUE if ThisString represents a valid numeric value.
<datatype> may be CHAR or STRING
Example: IS_NUM("-12.36") returns TRUE
ASC(ThisChar : CHAR) RETURNS INTEGER
returns an integer value (the ASCII value) of character ThisChar
Example: ASC('A') returns 65, ASC('B') returns 66, etc.

CHR(x : INTEGER) RETURNS CHAR


returns the character whose integer value (the ASCII value) is x
Example: CHR(65) returns 'A', CHR(66) returns 'B', etc.

String Operator

concatenates (joins) two strings.


& Example: "Summer" & " " & "Pudding" evaluates to "Summer Pudding"
The operator may also be used to concatenate a CHAR with a STRING

Numeric Functions
INT(x : REAL) RETURNS INTEGER
returns the integer part of x
Example: INT(27.5415) returns 27

RAND(x : INTEGER) RETURNS REAL


returns a real number in the range 0 to x (not inclusive of x).
Example: RAND(87) may return 35.43

Arithmetic Operators
An error will be generated if an operator is used with a value or values of an incorrect type.
finds the remainder when one number is divided by another.
MOD
Example: 10 MOD 3 evaluates to 1
finds the quotient when one number is divided by another.
DIV
Example 10 DIV 3 evaluates to 3

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/


COMPUTER SCIENCE WITH INQILAB PATEL
Page | 535
Boolean Operators

performs a logical AND on two Boolean values.


AND
Example: TRUE AND FALSE evaluates to FALSE

performs a logical OR on two Boolean values.


OR
Example: TRUE OR FALSE evaluates to TRUE

performs a logical NOT on a Boolean value.


NOT
Example: NOT TRUE evaluates to FALSE

Date Functions
Date format is assumed to be DD/MM/YYYY unless otherwise stated.
DAY(ThisDate : DATE) RETURNS INTEGER
returns the current day number from ThisDate
Example: DAY(04/10/2003) returns 4

MONTH(ThisDate : DATE) RETURNS INTEGER


returns the current month number from ThisDate
Example: MONTH(04/10/2003) returns 10

YEAR(ThisDate : DATE) RETURNS INTEGER


returns the current year number from ThisDate
Example: YEAR(04/10/2003) returns 2003

DAYINDEX(ThisDate : DATE) RETURNS INTEGER


returns the day index number from ThisDate where Sunday = 1, Monday = 2 etc.
Example: DAYINDEX(09/05/2023) returns 3

SETDATE(Day, Month, Year : INTEGER) RETURNS DATE


returns a value of type DATE with the value of <Day>/<Month>/<Year>
Example: SETDATE(26, 10, 2003) returns a date corresponding to 26/10/2003

TODAY() RETURNS DATE returns a value of type DATE


corresponding to the current date.

+92 300 2724734 /inqilabpatel https://www.inqilabpatel.com/

You might also like