As P2 Fundamental Problem-Solving and Programming Skills V24 Compress
As P2 Fundamental Problem-Solving and Programming Skills V24 Compress
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
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 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.
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
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
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.
Draw a structure chart to show the relationship between the three modules and the
parameters passed between them. [5]
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]
Draw a structure chart to show the relationship between the three modules and the
parameters passed between them. [5]
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.
(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
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 )
(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]
(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]
(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]
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.
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”
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
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.
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.
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
(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.
(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]
String Operator
Numeric Functions
INT(x : REAL) RETURNS INTEGER
returns the integer part of x
Example: INT(27.5415) returns 27
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
(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
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
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))
(ii) Write expression 4 from the table in part (c)(i) in its simplest form.
…………… ..................................................................................................................................... [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
(b) Write the pseudocode equivalent of the structured English. Use the identifiers from the
table in part (a). [6]
Problem 2: Input daily wages and number of day worked and output monthly pay.
02 INPUT Num1
04 INPUT Num2
06 OUPUT (Result)
Would this work if we swapped INPUT and OUTPUT statements in Line 01 and Line 02?
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.
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
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.
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.
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.
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
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.
(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]
(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
(b) The selection statement (lines 03 – 08) could have been written with more simplified logic.
Rewrite this section of the algorithm in pseudocode.
.....................................................................................................................................................
..............................................................................................................................................[3]
(b) Show how you could improve the algorithm written in pseudo code by writing an alternative type of
conditional statement in pseudo code. [3]
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
Problem 1: Input daily wages and number of day worked and output monthly pay for 100
employees.
Problem: Input marks of 30 students in a class output result of each student. Passing marks is 40
problem: To input and add a series of positive numbers in total. Continue this process for
input of positive numbers
WHILE
Differences between
Pre-Condition Post Condition
(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]
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
..................................................................................................................
......................... ..................................................................................................................
..................................................................................................................
..................................................................................................................
..................................................................................................................
......................... ..................................................................................................................
..................................................................................................................
..................................................................................................................
(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]
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 the equivalent pseudocode using a pre-condition loop, for this part of the amended
flowchart.
E 15 .................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
.................................................................
(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 ...............................................................................................................................................
...............................................................................................................................................
(ii) Identify the type of programming statement that assigns a data type to a variable.
..................................................................................................................................... [1]
(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]
(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]
CALL a Procedure:
Executing a procedure is known as CALL.
Pseudo code Python
CALL <Procedure identifier>() <Procedure identifier>()
CALL TestOutput() TestOutput():
CALL a Function:
As a function always returns a value so we need to store returning value in a variable on
function CALL.
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
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
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.
(i) Give the maximum number of inputs the user could be prompted to make. [1]
................................. ......................................................................................
............
................................. ......................................................................................
......................................................................................
................................. ......................................................................................
............
................................. ......................................................................................
......................................................................................
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]
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:
................................. ......................................................................................
.............
................................. ......................................................................................
......................................................................................
................................. ......................................................................................
.............
................................. ......................................................................................
......................................................................................
(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]
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................[6]
(iv) Give a reason why the use of library routines helps to minimise the risk of errors when
writing a program. [1]
(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
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
........................................................................................................................................................[ 6]
(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]
(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]
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]
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]
(ii) Stub testing is a technique often used in the development of modular programs.
Describe the technique. [3]
(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]
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]
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
Test 2 – Boat is returned during the hour after the rental starts
Start time value ....................................... Duration value .......................................
Expected new time value ....................................... [2]
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]
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
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
...........................................................................................................................................
.......................................................................................................................................[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]
(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]
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
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.
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.
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:
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
..........................................................................................................................................[1]
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]
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.................................................................. [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]
................................................................................................................
.............................................................................................................. 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]
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
......................................................................................................[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]
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.
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
...................................................................................................................................................................
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
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.
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)
(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.
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.
(ii) State the value returned when the function is called using the expression shown. Justify
your answer.
Value .................................................................................................................................
Justification .......................................................................................................................
...........................................................................................................................................
........................................................................................................................................... [2]
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
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
.............................................................................................................................................
[7]
Test 2 – Boat is returned during the hour after the rental starts
Start time value ....................................... Duration value
.......................................
Expected new time value .......................................
[2]
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.
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
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
............................................................................ [8]
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
.......................................................................................................................................[1]
(iv) Give the ‘file mode’ available in the programming language which will be used to address
this issue.
.......................................................................................................................................[1]
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().
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
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
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
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.
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
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
• 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
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
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
……………………………………………………………………………………………………………
….…………………………………………………………………………………………………………
…….………………………………………………………………………………………………………
……….
(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.
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]
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
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
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
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
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.
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
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]
(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).
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
1a 9618 21 P21
a) Write an algorithm that inputs a text string and output each letter in a separate line.
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).
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 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.
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
.....................................................................................................................................................
..................................................................................................................................... [8]
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.
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
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.
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.
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.
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.
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.
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
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
Code
editor
Document Debugger
IDE
Compiler/
Test
Interpreter
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]
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]
(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]
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.
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
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
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:
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
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().
.....................................................................................................................................................
(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.
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
...................................................................................................................................................
3B 9618 s22p22
String Operator
Numeric Functions
INT(x : REAL) RETURNS INTEGER
returns the integer part of x
Example: INT(27.5415) returns 27
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
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