Page | 1
Page | 2
Message from Head Mistress
Dear Students, The O level Computer
Science 2210 resource has been compiled
for you all with a lot of effort by your
teacher Sir Inqilab Patel. Not only this
book is a very comprehensive CAIE topic-
wise resource, but it will immensely help
you to revise your CS 2210 concepts for
your CAIE Examinations. I wish you all the
very best and hope that you will use it to gain sufficient practice for P2. I would like to
thank Mr. Inqilab for his unwavering efforts for our students.
With Best Wishes,
Sana Fatima
Headmistress Senior Section
About the developer of this work
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.
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
Page | 3
Page | 4
5 | Page
General Guidance
Paper 2 advice
When drawing logic gate diagrams repeat the process backwards to make sure your answer is correct. For example
draw the diagram for the statement, then write the statement or your diagram and check that they match.
Make sure you have answered the algorithm questions in the way they want the answer. If the question asks for a
flowchart, make sure you draw a flowchart. If a question asks for a description, then only drawing a flowchart or writing
code will not be acceptable.
Split your time appropriately between the scenario question at the end of the paper and the rest of the questions. You
should spend approximately 30 minutes on the scenario question. Do not got too much over this otherwise you may
not have enough time for the rest of the exam paper.
If you get stuck on an algorithm, don't spend a long time trying to fix it. Move on and you can always come back later
after you've answered the other questions, in that time away you might be able to look at it afresh.
Test run any algorithms you write. Use some sample data and work through each line of your algorithm to make sure
it works. If it doesn't, then you should be able to find out where the problem is.
Check your spelling and case (lower or upper) especially with any database questions, e.g. queries. Spelling and case
must be exact, if in the database table it is called HOUSE, then writing house is inaccurate. After you have answered
each question check the words you have used against those in the question.
If a question asks for an example, make sure you give one as there will be at least 1 mark available for this.
Learner’s Guide: Paper 2:
7 Algorithm design and problem-solving
7 Algorithm design and problem-solving R A G
1 Understand the program development life cycle, limited to: analysis, design, coding and testing
a. Understand that every computer system is made up of sub-systems, which are made up of
further sub-systems
2
b. Understand how a problem can be decomposed into its component parts
c. Use different methods to design and construct a solution to a problem
3 Explain the purpose of a given algorithm
4 Understand standard methods of solution
a. Understand the need for validation checks to be made on input data and the different types
of validation check
5
b. Understand the need for verification checks to be made on input data and the different
types of verification check
6 Suggest and apply suitable test data
7 Complete a trace table to document a dry-run of an algorithm
8 Identify errors in given algorithms and suggest ways of correcting these errors
Write and amend algorithms for given problems or scenarios, using: pseudocode, program
9
code and flowcharts
Page | 6
8 Programming
8.1 Programming concepts R A G
1 Declare and use variables and constants
2 Understand and use the basic data types
3 Understand and use input and output
a. Understand and use the concept of sequence
b. Understand and use the concept of selection
c. Understand and use the concept of iteration
4
d. Understand and use the concepts of totalling and counting
e. Understand and use the concept of string handling
f. Understand and use arithmetic, logical and Boolean operators
5 Understand and use nested statements
a. Understand what is meant by procedures, functions and parameters
6 b. Define and use procedures and functions, with or without parameters
c. Understand and use local and global variables
7 Understand and use library routines
8 Understand how to create a maintainable program
8.2 Arrays R A G
1 Declare and use one-dimensional (1D) and two-dimensional (2D) arrays
2 Understand the use of arrays
3 Write values into and read values from an array using iteration
8.3 File handling R A G
1 Understand the purpose of storing data in a file to be used by a program
2 Open, close and use a file for reading and writing
9 Databases
9 Databases R A G
1 Define a single-table database from given data storage requirements
2 Suggest suitable basic data types
Understand the purpose of a primary key and identify a suitable primary key for a given
3
database table
Read, understand and complete structured query language (SQL) scripts to query data stored
4
in a single database table
10 Boolean logic
10 Boolean logic R A G
1 Identify and use the standard symbols for logic gates
2 Define and understand the functions of the logic gates
a. Use logic gates to create given logic circuits from
a:ii) problem statement
iii) logic expression iv) truth table
b. Complete a truth table from
a:i) problem statement
3 ii) logic expression
iii) logic circuit
c. Write a logic expression from
a:i) problem statement
ii) logic circuit
iii) truth table
Page | 7
7.1 System Development Life Cycle
Program Development Life Cycle Identification, abstraction, decomposition
The program development life cycle is a of the problem and identification of
process for planning, creating, testing, and requirements.
deploying an information system. The This stage involves the process of gathering
systems development life cycle concept and interpreting facts, diagnosing problems,
applies to a range of hardware and software and recommending improvements to the
configurations, as a system can be composed system. Project goals will be further aided by
of hardware only, software only, or a analysis of end-user information needs and
combination of both. the removal of any inconsistencies and
The purpose of a program development incompleteness in these requirements.
lifecycle Problem is defined and requirement
In order to develop a successful program or specification is prepared.
suite of programs that is going to be used by A series of steps followed by the developer
include:
others to perform a specific task or solve a
i. Collection of facts: Obtain end user
given problem, the development needs to be
requirements through documentation, client
well ordered and clearly documented, so that
interviews, observation, and questionnaires.
it can be understood and used by other
ii. Scrutiny of the existing system: Identify pros
developers.
and cons of the current system in-place, so
Stages of System Development Life Cycle
as to carry forward the pros and avoid the
Following are the steps of system
cons in the new system.
development life cycle:
iii. Analysis of the proposed system: Find
solutions to the shortcomings described in
Analysis step two and prepare the specifications
using any specific user proposals.
2. Design
Testing Shown by decomposition using structure
Design 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,
Coding
constants, arrays and other data
structures are decided.
ii. Algorithm flowchart and/or pseudo code is
1. Analysis:
designed.
Page | 8
iii. Structure chart and state-transition • the time required to develop the program is
diagrams are also designed. reduced so the program can be delivered to
3. Coding the customer more quickly
Writing program code and performing iterative • the program is smaller in size so takes up
testing. less space in memory and download times
In this stage the program or set of programs is are shortened
written using a suitable programming • customer satisfaction is greater as their
language. requirements are met without any extraneous
When you have designed your solution, you features.
might need to choose a suitable high-level Q 7.3) Define Decomposition.
programming language. If you know more Decomposition – the process of breaking a
than one programming language, you have to complex problem into smaller parts.
weigh up the pros and cons of each one. Each problem can be decomposed into input,
Looking at Chapter 14, you need to decide process, output and store.
which programming language would best suit For example, to calculate sum of two numbers
the problem you are trying to solve and which program can be decomposed as follows:
language you are most familiar with. Stage Pseudo code
4. Testing INPUT Num1
INPUT
Testing program code using test data. INPUT Num2
The program is run many times with different PROCESS Sum Num1 + Num2
sets of test data, to test that it does everything OUTPUT OUTPUT Sum
it is supposed to do in the way set out in the Q 7.4) Give reason/benefits for
program design. decomposition (breaking down a problem).
Program code is easier to implement.
Q 7.1) Define Abstraction.
Different people can be assigned to work on
Abstraction – the process of extracting
different modules
information that is essential, while ignoring
Program code is easier to test and debug.
what is not relevant, for the provision of a
Modules are re-usable.
solution.
7.2 System & Sub-System
Q 7.5) What is system and sub-system?
Q 7.2) Describe need for and benefits of using
A system is a set of rules, an arrangement of
abstraction, and the purpose.
things, or a group of related things that work
Abstraction involves filtering out information
together to perform a function.
that is not necessary to solve a problem.
A system is made up of a number of
Abstraction gives us the power to deal with
subsystems. Each subsystem can be further
complexity.
divided into subsystems and so on until each
The benefits of abstraction:
Page | 9
sub-system just performs a single action.
Computer system is often divided up into sub- Q 7.9) Define flowchart and draw symbols
systems. This division can be shown using top- A flowchart is a graphical representation of
down design to produce structure diagrams algorithm.
that demonstrate the modular construction of The following are recognised flowchart
the system. symbols:
Q 7.6) What is meant by computer system?
A COMPUTER SYSTEM is made up of Terminator used at START
and END of the flowchart
hardware, software & data, communications
and people; each computer system can be
divided up into a set of sub-systems. Each Process Box: Rectangle
subsystem can be further divided into sub-
systems and so on until each sub-system just Input / Output Box:
Parallelogram
performs a single action.
Q 7.7) Define Top-Down Design
Top-down design is the breaking down of a Decision Box (IF and
CASE Selection, Loops)
computer system into a set of subsystems, Rhombus
then breaking each sub-system down into a
set of smaller sub-systems, until each sub-
system just performs a single action. Function / Procedure CALL
Q 7.8) State different methods to design a
solution (algorithm).
Algorithm is a step by step, design of
solution. To design a solution following
methods are used:
a. Flowchart: graphical representation of
algorithm
b. Pseudo code: is a simple method of
showing an algorithm, using English-like
words and mathematical operators that
are set out to look like a program.
c. Structure chart: shows the design of a
computer system in a hierarchical way.
Page | 10
Q 7.10) Describe Structure Diagrams functions.
The STRUCTURE DIAGRAM shows the Saves development time, no need to write it
design of a computer system in a hierarchical again.
way, with each level giving a more detailed Pre-compiled and well tested, more reliable,
breakdown of the system into sub-systems. 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 15) What is meant by Procedure?
A Procedure is a sub-routine that doesn’t
have to returns a value.
Q 16) Differentiate terms Parameter and
Q 7.11) A structure chart is often used in Argument.
modular program design. A parameter is a variable in a method
State four features of structure diagram: definition. While the arguments are the data
Feature 1: Sequence of operation that are passed.
Feature 2: Selection of modules Algorithm
Feature 3: Repetition
Q 1) What are data types? Why they are
Feature 4: Parameters
needed?
Q 7.12) Define Library routines A data type is a classification that specifies
A LIBRARY ROUTINE is a set of which type of data a variable has and what type
programming instructions for a given task that of operations can be applied to it.
is already available for use. It is pre-tested It tells the compiler or interpreter how the
and usually performs a task that is frequently programmer intends to use the data. Most
required. programming languages support various
types of data, including integer, real, character
Q 7.13) Define Sub-routines
or string, and Boolean.
A SUB-ROUTINE is a set of programming
Q 2) What are atomic data types?
instructions for a given task that forms a
The built in data types are called Atomic
subsystem, not the whole system. Sub-
Data Types. For example, Integer, Real,
routines written in high-level programming
Boolean, String, Char, Date etc.
languages are called ‘procedures’ or
Q 3) Describe different data types with
‘functions’ depending on how they are used.
examples.
Q 7.14) State advantages of built-in 1. INTEGER: A whole number (without
Page | 11
fractional part) can be positive or negative • - : Subtraction
and used in calculations. • * : Multiplication
For example, COUNT which never requires • / : Division
fractional part and may store 56, 89, 1 • MOD : Division to calculate remainder
2. REAL: A number capable of containing a • DIV : Integer division
fractional part can be positive or negative • ^ : Exponent
and used in calculations.
For example, Weight may contain fractional
Q) What are logic operators? What are their
Part like 56.8, 89.0, 1.2
operands?
3. CHAR: A single character (may be letter,
The only logic operators used are AND, OR
special character or number but number
and NOT. The operands and results of these
cannot be used in calculation).
operations are always of data type
For example, ‘A’, ‘$’, ‘5’
BOOLEAN.
4. STRING: A sequence of alphanumeric and
special characters but number cannot be
Q) Describe Counting and Totalling.
used in calculation.
Counting is used to find how many items are
For example, “Inqilab Patel”, “0300-2724734”,
there by incrementing by 1 during each time
“House No 56 Block 2, PECHS Karachi”
loop is executed.
5. BOOLEAN: A data type with two possible
It is sometimes necessary to count how many
values
times something happens.
For example, TRUE and FALSE or YES or NO
To count up or increment by 1, we can use
6. DATE: To store a calendar date
statements such as:
For example, 16/04/2010
Count ← Count + 1
(new) (old)
Q) Differentiate variable and constant.
i.e, INCREMENT (old) Count by 1 to get (new)
Variable is memory location where a value can
Count
be stored. The values stored in a variable are
TOTALLING is used to calculate running total.
changed during execution.
We can use a variable such as Total or Sum to
Constant is a memory location that stores
hold the running total and assignment
values, but values once stored cannot be
statements such as:
changed during program execution.
Total ← Total + Number
(new) (old)
Q 5) What are Arithmetic operators?
i.e. ADD Number to (old) Total to obtain (new)
Standard arithmetic operator symbols are
Total
used:
Q) What is a program?
• + : Addition
A program is a sequence of instructions or
Page | 12
programming language statements written to flow path on the basis of given condition.
make a computer perform certain tasks. It also decides which statement(s) are to be
executed depending upon the result of a given
Q 9) What are basic Control Constructs:
condition.
Following are the basic constructs of
Q) Explain different types of selection
algorithm and program which controls
statements.
execution of statements:
IF and CASE selections are two different types
1. Sequence
of selection statements
2. Assignment
IF statements are used when there are one or
3. Selection
two options.
4. Iteration
When there is only one option IF statements
Q) Describe what is meant by sequence. without an ELSE clause is written as follows:
Sequence: One statement is being executed IF Number>Largest THEN
after another in the order they are written. LargestNumber
In following example statement number ‘i’ will ENDIF
be executed at 1st and then ‘ii’ then ‘iii’ and at When there are two options IF statements with
last statement number ‘iv’ will be executed: an ELSE clause is written as follows:
I. INPUT Num1 IF Marks>=50 THEN
II. INPUT Num2 Result “Pass”
III. Total Num1 + Num2 ELSE
IV. PRINT Total Result “Fail”
ENDIF
Q 11) Describe Assignment with example CASE statements is a conditional statement
statements. to deal with many possible outcomes.
Assignment: Storing values in a variable is CASE statements allow one out of several
known as assignment. branches of code to be executed, depending
The assignment operator is ←. on the value of a variable.
Assignments should be made in the following In case selection number of statements are
format: <identifier> ← <value> reduced so code become more simplified.
For example: CASE statements are written as follows:
Counter ← 0 CASE Marks OF
Counter ← Counter + 1 >=80: Grade “Distinction”
TotalToPay ← NumberOfHours * HourlyRate >=60: Grade “Merit”
>=40: Grade “Pass”
Q) What is meant by Selection/Conditional? OTHERWISE : : Grade “Fail”
Selection (Condition) determines program ENDCASE
Page | 13
Q 13) What is meant by Loop (Repetition or A conditional loop.
iteration)? Condition is given at the end of loop.
Iteration (Loop or Repetition) is a control It is executed only when the condition is false.
structure, used to execute a set of instructions It is executed at least once.
multiple times. REPEAT
INPUT Num
There are following three types of loops:
UNTIL Num>0
1. Count-controlled loop Difference between Loop structures
FOR … WHILE … REPEAT …
2. Pre-condition loop
TO… NEXT ENDWHILE UNTIL
3. Post-condition loop
Q 18) Describe Count Controlled Loop. Count- Pre-Condition Post
Count-controlled (FOR) loops Controlled Loop Condition
It executes a set number of time. loop Loop
For example to input 5 numbers: Number of Executed Executed
FOR Count 1 TO 5 repetition is when when
INPUT Num already condition is condition is
NEXT Count known TRUE FALSE
Q 19) What are pre-condition (WHILE) loops? Executed a May not be Executed at
Pre-Condition (WHILE) Loop set number executed least ONCE
A conditional loop. of times even ONCE
Condition is given at start of the loop.
Works when condition is TRUE
May not be executed even once if, on the first
test, the condition evaluates to FALSE.
Example: To input a series of numbers and
calculate total and stops if a –ve number is
entered:
The condition is checked at the beginning of
the loop. If condition is true loop statements are
executed again and again.
Total0
INPUT Num
WHILE Num>0 DO
Total Total + Num
INPUT Num
END WHILE
Q 20 What are post condition loop?
Post-condition (REPEAT UNTIL) loop is:
Page | 14
String Handling Operations: Q) Write a program to input a name and print each
Following are the string handling sub-rotuines: character in separate line.
LENGTH(<identifier>) DECLARE Name: STRING
Returns the integer value representing the length of
DECLARE ThisChar: CAHR
string. The identifier should be of data type string.
DECLARE Count: INTEGER
LCASE(<identifier>)
INPUT Name
Returns the string/character in lower case. The
FOR Count 1 TO LENGTH(Name)
identifier should be of data type string or char.
ThisChar SUBSTRING(Name, Count, 1)
UCASE(<identifier>)
Returns the string/character in upper case. The OUTPUT ThisChar
identifier should be of data type string or char. NEXT Count
SUBSTRING(<identifier>,<start>, Worked Example: 1b S23 P22
<length>)
11 The variables P and Q are used to store data in a
Returns a string of length, length starting at position
program. P stores a string. Q stores a character.
start. (a) Write pseudocode statements to declare variables
The identifier should be of data type string, length and P and Q, store “The World” in P and store ‘W’ in Q
DECLARE P: STRING
start should be positive and data type integer.
DECLARE Q: CHAR
0a Specimen Paper 2a P “The World”
12 The variables X, Y and Z are used to store Q ‘W’ [2]
data in a program: (b) Write a pseudocode algorithm to :
Convert P to upper case
• X stores a string
Find the position of Q in the string P (the first
• Y stores a position in the string (e.g. 2) character in this string is in position 1)
• Z stores the number of characters in X. Store the position of Q in the variable
Position.
(a) Write pseudocode statements to declare the
P UCASE(P)
variables X, Y and Z. Found FALSE
DECLARE X: STRING Position 1
WHILE Found=FALSE AND Position<LENGTH(P) DO
DECLARE Y, Z: INTEGER [3]
IF Q= SUBSTRING(P, Position, 1)
(b) Write pseudocode statements to: Found TRUE
OUTPUT Position
• store the string "Programming is fun" in X
ELSE
• find the length of the string and output it Position Position + 1
• extract the word fun from the string and ENDIF
ENDWHILE
output it.
IF Found = FALSE THEN
X “Programming is fun” OUTPUT “Character not found”
Z LENGTH(X) ENDIF
OUTPUT Z
OUTPUT SUBSTRING(X, 16,3) [6]
Page | 15
W23 P22 A validation check is a rule that is built into a
The string operation SUBSTRING(Quote, Start, database to check that the data entered is:
Number) returns a string from Quote, beginning at • Sensible
position Start, that is Number characters long.
• Reasonable
The first character in Quote is in position 1.
• Within acceptable boundaries
Write pseudocode statements to:
• Complete
• store the string "Learning Never Exhausts The Mind"
in Quote It does NOT mean that the data is actually
• extract and display the words "The Mind" from the correct, that requires verification.
string
• output the original string in lower case. [5] Q 3) Describe different types of validation
DECLARE Quote:STRING checks.
DECLARE Start, Number: INTEGER 1 Type Checks – Checks that the data
Quote "Learning Never Exhausts The Mind"
entered is of a given data type.
Start 25
For example, string data entered in integer
Number 8
field or variable will be rejected.
OUTPUT SUBSTRING(Quote, Start, Number)
2 Range checks - these are used to limit the
OUTPUT LCASE(Quote)
range of data a user can enter. The 'day' part
Validation and Verification
of a date must be in the range 1 to 31. An
Q 1) Define Data verification.
exam grade should be in the range 'A'...'E' or
Verification is performed to ensure that the
'U'.
data entered exactly matches the original
3 Limit Check - Similar to Range Check but
source. Verification means checking the
the rule involves only one limit.
input data with the original data to make sure
For example, >=0 means reject negative
that there have been no transcription errors
numbers. Date of birth must not be later than
(transcription means copying the data).
a date.
Verification methods include:
4 Character Check - Checks that when a
At the time of entry At the time of
string of characters is entered it does not
transmission
contain any invalid characters or symbols.
Double entry Parity check
For example, a name would not contain digit
Screen/visual check Checksum.
or special character.
ARQ
5 Format Check - Checks the data is in the
Echo Check
right format. Values must conform to a specific
Q 2) What is validation?
pattern, for example, two letters followed by six
Validation is an automatic computer check to
digits followed by a single letter.
ensure that the data entered is sensible and
A candidate number, PK-500-1234 or National
reasonable. It does not check the accuracy of
Insurance number is in the form LL 99 99 99 L
data.
Page | 16
where L is any letter and 9 is any number. for be done to prove that the solution works
Date dd/mm/yyyy or mm/dd/yyyy correctly.
6 Presence checks - these simply check that For example, here is a set of normal test data
an entry has been made in a particular field for an algorithm to record the percentage
i.e. a null value (empty field) is not permitted. marks from 10 end-of-term examinations for a
7 Length Checks - ensures that such data is student and find their average mark:
either an exact length or does not exceed a Normal test data: 50, 50, 50, 50, 50,
specified number of characters. 50, 50, 50, 50, 50
8 Lookup - A lookup check takes the value Expected result: 50
entered and compares it against a list of
values in a separate table. 2. Abnormal/Erroneous Data is the data
9 Check digits - The last one in a code are u that should cause the system to tell the
sed to check the other digits are correct. user that there is a problem with data
Bar code readers in supermarkets use check entered into the system.
digits. This test data should be rejected as the
length check – e.g. only 30 characters in values are not suitable.
name field This type of test data is called ERRONEOUS
character check – e.g. name doesn’t contain or ABNORMAL TESTDATA; it should be
numeric chars rejected by the solution.
range check – e.g. day of month in date is For example to input positive numbers:
between 1 and 31 Erroneous/abnormal data:–12, eleven
format check – e.g. date in the form xx/yy/zz Expected results: these values should be
check digit – e.g. end digit on bar code to rejected
check if it is valid 3. Extreme Data are the largest and smallest
type check – e.g. integer, real values that normal data can take.
presence check = field is not left blank Extreme data: 0, 100
Test Data Expected results: these values should be
Test data is the data that is used in testing of a accepted
software system. 4. Boundary Data is used to establish where
In order to test a software application, we need the largest and smallest values occur. For
to enter some data for testing most of the example, for percentage marks in the
features. Any such specifically identified data range 0 to 100, the algorithm should be
which is used in tests is known as test data. tested with the following boundary data; at
There are following three types of test data: each boundary two values are required,
1. Normal Data is the data a computer one value is accepted and the other value
system should work on. Testing needs to is rejected.
Page | 17
Boundary data for 0 is –1, 0 and for 100 is ........................................ [1]
100, 101 (b)
Expected results: –1 and 101 are rejected, 0 INPUT x
and 100 are accepted IF x = "" THEN
Rogue Values A value that stops input is OUTPUT "Invalid"
ENDIF
called Rogue Value.
A rogue value lets the computer know that a
....................................... [1]
sequence of input values has come to an end.
(c)
Q) Each of the following algorithms performs data
INPUT x
validation.
IF NOT(x = "Red" OR x = "Yellow" OR x = "Blue")
State the type of validation check that each of the
THEN
algorithms performs.
OUTPUT "Invalid"
(a)
ENDIF
INPUT x
IF x < 0 OR x > 10 THEN
....................................... [1]
OUTPUT "Invalid"
ENDIF
Page | 18
Arrays Files, ADT
Data type – a classification attributed to an Each element in the array is identified using
item of data, which determines the types of its subscript or index number. The largest
value it can take and how it can be used. and smallest index numbers are called the
Identifier – a unique name applied to an item upper bound and lower bound of the array.
of data. For illustration, let's take array declaration to
Linear search – a method of searching in store marks of 10 students.
which each element of an array is checked in Marks[10] Marks[1:10] Marks[0:9]
order.
Bubble sort – a method of sorting data in an Q) Describe The terms associated with
array into alphabetical or numerical order by Arrays
comparing adjacent items and swapping them Name: The identifier of the array is called Array
if they are in the wrong order. Name. E.g. StudentName[]
File – a collection of data stored by a Element: Each data item stored in array is
computer program to be used again. called element. Array can store only single
Arrays types of elements.
Arrays are data structure used to store Size: The number elements the array can
multiple data items of same data type store. E.g. StudentName[1:30] can store 30
(homogenous) under one identifier name. names while StudentName[30] can store 31
Square brackets are used to indicate the names as by default it is 0 to 30.
array index. Index: The position of each element is
referred as Index Number. In the above
Page | 19
diagram , ndex of 90 in 1D array is [3], while NOT Gate: X=1 if Input A is 0. Inverter
in 2D is [3,1]. AND Gate: X =1 if BOTH input are 1
Type: Data type of all elements in a single OR Gate: X=1 if Either input is 1
array have same data types. NAND Gate: X=0 if BOTH input are 1
Dimension: Dimension is the organisational NOR Gate: X =0 if EITHER input is 1
structure of array. It may be 1D that has single XOR Gate: X=1 if Either input is 1 BUT NOT
index or 2D that has two indexes. BOTH. Or when BOTH input are DIFFERENT.
Lower Bound – the smallest index number
Upper Bound – the largest index number AND Gate: “The only time the output will be 1
Q 2) The following diagram shows four data is when both inputs are 1.”
structures and four descriptions. [3] NOR Gate: “The only time the output will be 1
Draw a line to connect each data structure to is when both inputs are 0.”
the correct description. NAND Gate: “The only time the output will be
Data Description 0 is when both inputs are 1.”
structure Q 2) Draw and describe XOR gate. [5]
Constant A collection of related data
A value that can change
Array XOR Gate gives output only when BOTH input
whilst a program is running
are different.
A value that never changes If A = 1 OR B = 1 BUT NOT BOTH then output
Table
whilst a program is running will be 1.
IF BOTH input are 0 then output will be 0.
A series of elements of the IF BOTH input are 1 then output will be 0.
Variable
same data type IF BOTH input are same output will be 0.
Binary Logic
Q 1) Describe each logic gate.
Page | 20
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 <<write size of array here e.g 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
Page | 21
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
MaxIndex <<write size of array here e.g 30>>
INPUT SearchData
Found FALSE
FOR Index 1 TO MaxIndex
IF SearchData = Marks[Index]
THEN
Found TRUE
OUTPUT “Found at “, Index
ENDIF
NEXT Index
IF Found = FALSE THEN OUTPUT “not found.” ENDIF
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.
Page | 22
DELCARE Swapped: BOOLEAN
DECLARE MaxIndex, UpperBound: INTEGER
DELCARE Temp: INTEGER
Swapped TRUE
MaxIndex <<write size of array here e.g 30>>
FOR Round = 1 TO (MaxIndex-1)
FOR Index = 1 TO (MaxIndex-Round)
IF Data[Index] > Data[Index+1] THEN
Temp = Data[Index]
Data[Index] = Data[Index+1]
Data[Index+1] = Temp
ENDIF
NEXT Index
NEXT Round
Page | 23
File Handling
Q 1) Why files are needed?
When a program is being executed data is stored in variables, constants, arrays etc. These data
structures use RAM, making them temporary, when program is closed Files stored data in
secondary storage devices. 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.
Q 2) Describe File Handling
Text files consist of lines of text that are read or written consecutively as strings.
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.
Q 3) Explain different file modes
The following file modes are used:
READ - for data to be read from the file
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.
APPEND for data to be added to the existing file, if the file is not existing then it will be created.
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>
Page | 24
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”
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 data from one file and store in another file
If a file is already created, data from it can be read and stored in another file.
Both files are opened, one in READ mode and the other in WRITE mode.
Data is read from one file into a variable and then the variable is written in the other file.
And then both the files are closed.
Syntax to add data from one file to another:
OPENFILE <Source file name> FOR READ
OPENFILE <Destination file name> FOR WRITE
READFILE <Source File Name>, <String variable>
WRITEFILE <Destination File name>, <String variable>
CLOSEFLE <Source file name>
CLOSEFLE <Destination file name>