0% found this document useful (0 votes)
13 views71 pages

4.3 Further Programming

The document outlines the Cambridge International AS & A Level Computer Science syllabus for 2021-2023, focusing on further programming concepts and paradigms. It covers various programming paradigms including low-level, imperative, object-oriented, and declarative programming, along with file processing and exception handling. Additionally, it provides insights into memory addressing modes and the execution of instructions in low-level programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views71 pages

4.3 Further Programming

The document outlines the Cambridge International AS & A Level Computer Science syllabus for 2021-2023, focusing on further programming concepts and paradigms. It covers various programming paradigms including low-level, imperative, object-oriented, and declarative programming, along with file processing and exception handling. Additionally, it provides insights into memory addressing modes and the execution of instructions in low-level programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A2 LEVE LS 9618

20 Further
COMPUTER SCI ENCE Programming
Compiled By Engr. Shahzadah Ashraf BandaShah

[All Variants Included + Pre-released


Material + Marking Schemes + Free
Pages To Prepare Your Notes]

STUDENTS NAME:

_____________________________________________

[Link] 0333 2076121


SCHOOL NAME: @[Link]

_____________________________________________

Follow On Facebook :
DATE ISSUED: [Link]
[Link]
_____________________________________________
For More Resources:
[Link]
CONTACT NUMBER:

_____________________________________________

Coming Up CSWS21
Computer Science
Workshop 2021
Cambridge International AS & A Level Computer Science 9618 syllabus for 2021, 2022 and 2023. Subject content

20 Further Programming
20.1 Programming Paradigms
Candidates should be able to: Notes and guidance
Understanding what is meant by a programming
paradigm
Show understanding of the characteristics of a Low-level Programming:
number of programming paradigms:
• understanding of and ability to write
• low-level low-level code that uses various addressing
modes: immediate, direct, indirect, indexed and
relative
• Imperative (Procedural) Imperative (Procedural) programming:
• Assumed knowledge and understanding of
Structural Programming (see details in AS content
section 11.3)
• understanding of and ability to write imperative
(procedural) programming code that uses
variables, constructs, procedures and functions.
See details in AS Content
• Object Oriented Object-Oriented Programming (OOP):
• understanding of the terminology associated with
OOP (including objects, properties/attributes,
methods, classes, inheritance, polymorphism,
containment (aggregation), encapsulation,
getters, setters, instances)
• understanding of how to solve a problem by
designing appropriate classes
• understanding of and ability to write code that
demonstrates the use of OOP
• Declarative Declarative programming:
• understanding of and ability to solve a problem
by writing appropriate facts and rules based on
supplied information
• understanding of and ability to write code that
can satisfy a goal using facts and rules

20.2 File Processing and Exception Handling


Candidates should be able to: Notes and guidance
Write code to perform file-processing operations Open (in read, write, append mode) and close a file
Read a record from a file and write a record to a file
Perform file-processing operations on serial,
sequential, random files
Show understanding of an exception and the Know when it is appropriate to use exception handling
importance of exception handling Write program code to use exception handling

[Link]/alevel
20.1 Programming Paradigms
Programming paradigms are simply methods of programming. Initially, computers were programmed
using binary language. This was difficult and led to many errors that were difficult to find. Programs
written in binary are said to be written in machine code, this is a very low-level programming paradigm.

To make programming easier, assembly languages were developed. These replaced machine code
functions with mnemonics and addresses with labels. Assembly language programming is also a low-
level paradigm although it is a second generation paradigm. The figure below shows an assembly
language program that adds together 2 numbers and stores the result.

Although this assembly language is an improvement over machine code, it is still prone to errors and
code is difficult to debug, correct and maintain.

The next advance was the development of procedural languages. These are third generation languages
and are also known as high-level languages. These languages are problem oriented as they use terms
appropriate to the type of problem being solved. For example, COBOL (Common Business Oriented
Language) uses the language for business. It uses terms like, file, move, and copy.

FORTRAN (FORmula TRANslation) and ALGOL (ALGOrithmic Language) were developed mainly for
scientific and engineering problems. Although one of the ideas behind the development of ALGOL was
that it was an appropriate language to define algorithms. BASIC (Beginners All-Purpose Symbolic
Instruction Code) was developed to enable more people to write programs. All these languages follow
the procedural paradigm. That is, they describe, step by step, exactly the procedure that should be
followed to solve a problem.

The problem with procedural languages is that it can be difficult to reuse code and to modify solutions
when better methods of solution are developed.

In order to address these problems, object-oriented languages (like Eiffel, Smalltalk, and Java) were
developed.

In these languages, data and methods of manipulating the data, are kept as a single unit called an
“object”. The only way that a user can access the data is via the object’s methods. This means that, once
an object is fully working, it cannot be corrupted by the user. It also means that the internal workings of
an object may be changed without affecting any code that uses the object.

Page 3 of 53
Take the real world for example, it is full of objects not just individual values like in procedural languages.
For instance, my car registration number W123ARB, is an object. Ahmed’s car registration number
S123AHM is another object. Both of these objects are cars and all cars have similar attributes. All cars
should have a registration number, a certain engine capacity, certain color, and so on. So my car and
Ahmed’s car are instances of a class called “car”. In order to model the real world, the
Object-oriented programming (OOP) paradigm was developed. Unfortunately, OOP requires a large
amount of memory and in the 1970s, memory was expensive and CPUs still lacked power. This slowed the
development of OOP. However, as memory became cheaper and CPUs more powerful, OOP became
more popular. By the 1980s Smalltalk, and later Eiffel, had become well established. These were true
object-oriented languages. C++ also includes classes although the programmer does not have to use
them. This means that C++ can be used either as a standard procedural language or an object-oriented
language. Although OOP languages are procedural in nature, OOP is considered to be a newer
programming paradigm.

The following is an example, using Java, of a class that specifies a rectangle and the methods that can be
used to access and manipulate the data.

class Shapes {
/* Shapes Version 1 by Roger Blackford July 2001
----------------------------------------------------------
This illustrates the basic ideas of OOP
*/
// Declare three object variables of type Rectangle
small, medium, large;
// Create a constructor where the initial work is done
Shapes ( ) {
// Create the three rectangles
small = new Rectangle(2, 5);
medium = new Rectangle(10, 25);
large = new Rectangle(50, 100);
//Print out a header
[Link]("The areas of the rectangles are:\n");

Page 4 of 53
//Print the details of the rectangles
[Link]( );
[Link]( );
[Link]( );
}//end of constructor Shapes.
//All programs have to have a main method
public static void main(String [ ] args) {
//Start the program from its constructor
new Shapes ( );
}//end of main method.

}//end of class Shapes.

class Rectangle {

//Declare the variables related to a rectangle


int length;
int width;
int area;
//Create a constructor that copies the initial values into the object's variables Rectangle (int w, int l) {
width = w;
length = l;
//Calculate the area area = width * length;
}//end of constructor Rectangle

//Create a method to output the details of the rectangle void


write ( ) {

[Link]("The area of a rectangle " + width + " by " + length + " is " +area);
}//end of write method.

}//end of constructor

This example contains two classes. The first is called Shapes and is the main part of the program. It is
from here that the program will run. The second class is called Rectangle and it is a template for the
description of a rectangle.

Page 5 of 53
The class Shapes has a constructor called Shapes, which declares two objects of type Rectangle. This is a
declaration and does not assign any values to these objects. In fact, Java simply says that, at this stage,
they have null values. Later, the new statement creates actual rectangles.

Here small is given a width of 2 and a length of 5, medium is given a width of 10 and a length of 25 and
large is given a width of 50 and a length of 100.

When a new object is to be created from a class, the class constructor, which has the same name as the
class, is called by invoking the new operator. The class Rectangle has a constructor that assigns values
to width and length and then calculates the area of the rectangle.

The class Rectangle also has a method called write( ). This method has to be used to output the details
of the rectangles.

In the class Shapes, its constructor then prints a heading and the details of the rectangles. The latter is
achieved by calling the write method. Remember, small, medium and large are objects of the Rectangle
class. This means that, for example, [Link]( ) will cause Java to look in the class called Rectangle for
a write method and will then use it. More details of Object-oriented programming will be given later.

Low Level Programming


The figure below shows the minimum number of registers needed to execute instructions. Remember
that these are used to execute machine code instructions not high-level language instructions.

Page 6 of 53
 The Program Counter (PC) is used to keep track of the location of the next instruction to be
executed. This register is also known as the Sequence Control Register (SCR).
 The Memory Address Register (MAR) holds the address of the instruction or data that is to be
fetched from memory.
 The Current Instruction Register (CIR) holds the instruction that is to be executed, ready for
decoding.
 The Memory Data Register (MDR) holds data to be transferred to memory and data that is being
transferred from memory, including instructions on their way to the CIR. Remember that the
computer cannot distinguish between data and instructions. Both are held as binary numbers.
How these binary numbers are interpreted depends on the registers in which they end up.
The MDR is the only route between the other registers and the main memory of the
computer.
 The accumulator is where results are temporarily held and is used in conjunction with a working
register to do calculations.
 The index register is a special register used to adjust the address part of an instruction.

The question to ponder upon is how to these registers actually execute instructions. In order to do this,
we shall assume that a memory location can hold both the instructions code and the address part of
the instruction. For example, a 32-bit memory location may use 12 bits for the instruction code and
20 bits for the address part. This will allow us use up 212 = 4096 instruction codes and 220 = 1,048,576
memory addresses.

To further simplify things, we shall use mnemonics for instructions such as:

We shall also use decimal numbers rather than binary for the address part of an instruction.

Page 7 of 53
Suppose four instructions are stored in locations 300, 301, 302, and 303 as shown in the following table
and that the PC contains the number 300.

The fetch part of the instruction is:

The instruction is now decoded (not shown in the table) and is interpreted as ‘load the contents of the
location whose address is given into the accumulator’

Next is the execution phase. As the contents of an address are needed, the address part of the
instruction is copied into the MAR, in this case 400.

Now use the MAR to find the value required and copy it into the MDR

Page 8 of 53
Finally copy the contents of the MDR to the accumulator.

Now use the same steps to fetch and execute the next instruction. Note that the PC already
contains the address of the next instruction.

Note that all the data moves between memory and the MDR via the data bus. All the addresses
use the address bus.

Page 9 of 53
The figure below shows that the outcome of the execute instruction may vary depending on the
instruction. For example, STA n (store the contents of the accumulator in the location with address n).

This process works fine but only allows for the sequential execution of instructions. This is because the
PC is only changed by successively adding 1 to it. How can we arrange to change the order in which
instructions are fetched? Consider these instructions.

Supposed the PC contains number 300, after the instruction ADD 500 has been fetched and executed, the
PC will hold the number 301. Now the instruction JLZ 300 will be fetched in the usual way and the PC
incremented to 302. The next step is to execute this instruction. The steps are shown below.

Page 10 of 53
Fetch next instruction (See Fig 3.5.i.2)

No

Yes

Copy address part of CIR to the PC

Memory Addressing Modes


There are many ways to locate data and instructions in memory and these methods are called ‘memory
address modes’

Memory address modes determine the method used within the program to access data either from within
the CPU or from the external RAM. Some memory addressing modes can control the program flow.

The five memory address modes are:

 Direct
 Indirect
 Immediate
 Indexed
 Relative

Immediate Addressing
Immediate addressing means that the data to be used is hard-coded into the instruction itself.

This is the fastest method of addressing as it does not involve main memory at all.

For example, you want to add ‘2’ to the content of the accumulator.

Page 11 of 53
The instruction is:

ADC 2

Nothing has been fetched from memory; the instruction simply adds 2 to the accumulator
immediately.

Immediate addressing is very useful to carry out instructions involving constants (as opposed to
variables). For example, you might want to use the ‘PI’ as a constant 3.14 within your code.

Direct Addressing
This is a very simple way of addressing memory – direct addressing means the code refers directly to a
location in memory.

For example:

SUB (3001)
In this instance, the value held at absolute location 3001 in RAM is subtracted from the accumulator.

The good thing about direct addressing is that it is fast (but not as fast as immediate addressing) the bad
thing about direct addressing is that the code depends on the correct data always being present at the
same location.

It is generally a good idea to avoid referring to absolute memory addresses in order to have
‘re- locatable code’ i.e. code that does not depend on specific locations in memory.

You could use direct addressing on computers that are only running a single program.

Indirect Addressing
Indirect addressing means that the address of the data is held in an intermediate location so that the
address is first ’looked up’ and then used to locate the data itself.

Many programs make use of software libraries that get loaded into memory at run time by the
loader. The loader will most likely place the library in a different memory location each time.

So how does a programmer access the subroutines within the library if he does not know the
starting address of each routine?

Page 12 of 53
By Indirect Addressing!

1) A specific block of memory will be used by the loader to store the starting address of every
subroutine within the library. This block of memory is called ‘vector table’. A vector table holds
addresses rather than data. The application is informed by the loader of the location of the
vector table itself.
2) In order for the CPU to get to the data, the code first of all fetches the content at RAM location
5002 which is part of the vector table.
3) The data it contains is then used as the address of the data to be fetched, in this case,
the data is at location 9000.

A typical assembly language instruction would look like:

MOV A, @5002

This looks to location 5002 for an address. That address is then used to fetch data and load it into the
accumulator. In this instance, it is 302.

Indexed Addressing
Indexed addressing means that the final address for the data is determined by adding an offset to a base
address.

Very often, a chunk of data is stored as a complete block of memory.

Page 13 of 53
For example, it makes sense to store arrays as contiguous blocks in memory (contiguous means being
next to something without a gap). This array has a ‘base address’ which is the location of the first
element, then an ‘index’ is used that adds an offset to the base address in order to fetch any other
element within the array.

Indexed addressing is fast an excellent for manipulating data structures such as arrays as all you need to
do is set up a base address then use the index in your code to access individual elements.

Another advantage of indexed addressing is that if the array is re-located in memory at any point, then
only the base address needs to be changed. The code making use of the index can remain exactly the
same.

Relative Addressing

Quite often a program only needs to jump a little bit in order to jump to the next instruction. Maybe just
a few memory locations away from the current instruction.

A very efficient way of doing this is to add a small offset to the current address in the program
counter. (Remember that the program counter always points to the next instruction to be executed).
This is called ‘relative addressing’

Definition:
Relative addressing means that the next instruction to be carried out is an offset number of
locations away, relative to the address of the current instruction.

Consider this bit of pseudo-code:

jump +3 if accumulator == 2
code executed if accumulator is NOT = 2
jmp +5 (unconditional relative jump to avoid the next line of code)
acc:
code executed if accumulator is = 2)
carryon:

Page 14 of 53
In the code above, the first line of code is checking to see if the accumulator has the value of 2 in it.
If it does, then the next relevant instruction is 3 lines away. This is called a conditional jump and it is
making use of relative addressing.

Another example of relative addressing can be seen in the jmp +5 instruction. This is telling the CPU to
effectively avoid the next instruction and go straight to the ‘carryon’ point.

Summary of Memory Nodes

Memory Modes
Types Comment
Immediate Apply a constant to the accumulator. No need to access main memory.

Direct or Absolute This is a very simple way of addressing memory - the code refers directly to a
Addressing location in memory. Disadvantage is that it makes relocatable code more
difficult.
Indirect Addressing Looks to another location in memory for an address and then fetches the
data that is located at that address. Very handy of accessing in-memory
libraries whose starting address is not known before being loaded into
memory
Indexed Addressing Takes a base address and applies an offset to it and fetches the data at that
address. Excellent for handling data arrays.
Relative Addressing Tells the CPU to jump to an instruction that is a relative number of locations
away from the current one. Very efficient way of handling program jumps
and branching.

Object Oriented Programming (OOP)

Earlier in the chapter, an example of OOP was discussed and now you know some languages that support
OOP. Java is an OOP language whose syntax is based on C++. All these languages have classes and derived
classes and use the concepts of inheritance, polymorphism, containment (aggregation).

Inheritance allows the re-use of code and the facility to extend the data and methods without affecting
the original code. In the following diagrams, we shall use a rounded rectangle to represent a class. The
name of the class will appear at the top of the rectangle, followed by the data in the middle, and finally,
the methods at the bottom.

Page 15 of 53
Consider the class Person that has data about a person’s name and address plus a method called
outputData( ) that outputs the name and address, getName( ) and getAddress( ) that return the name
and address respectively shown in the figure below.

Now we supoose we want a class data and methods as Person & Employees’ National Insurance rewrite
the contents of the class called Employee that inherits and adds on the extra data and Employee that
require the same also needs to store and output an number. Clearly, we do not wish to person. We can
do this by creating a all the details of the class Person methods needed.

This is shown in the figure below. Employee inherits the data and Person. Person is called the
super- the derived class from the person. An method provided by the Employee and where the arrow
signifies that method provided by the class class of Employee and Employee is object of type. Employee
can use those provided by Person.

Page 16 of 53
Notice that we now have 2 methods with the same name. How does the program determine which
one to use? If myPerson is an instantiation of the Person class, then:

[Link]( );

We will use the outputData( ) from the Person class. The statement:

[Link]( );

Will use the method outputData( ) from the Employee class if myEmp is an instantiation of the
Employee class.

The concept of a method having two different meanings is called polymorphism.

Now suppose we have two types of employee; one is paid hourly and the other is paid a salary. Both of
these require the data and methods of the classes Person and Employee but they also need to be
different from one another.

Page 17 of 53
How can an object of type Employee output the name and address as well as the N.I number? The
outputData( ) method in class Employee can refer to the outputData( ) method of its superclass. This is
done by writing a method, in the class Employee, of the form:

void outputData( ) {
[Link]( );
[Link]("The N.I. number is " + NINumber);
}//end of outputData method.

Here, [Link]( ) calls the outputData( ) method of the super-class and then outputs the N.I
number. Similarly, the other derived classes can call the methods of their super classes.

Association is a relationship between two objects. In other words, association defines the multiplicity
between 2 objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all
these words define an association between objects. Aggregation is a special form of association.

Aggregation is a special case of association. A directional association between objects. When an object
‘has-a’ another object, then you’ve got an aggregation between them. Direction between them specified
which object contains the other object.

For example, consider two classes Student class and Address class. Each student must have an address so
the relationship between student and address is a Has-A relationship. But if your consider its vice
versa, then it would not make sense as an Address does not necessarily need to have a Student. Below
example shows this theoretical explanation in a sample Java program.

Page 18 of 53
Student Has A Address

Code Output
123
Chaitanya
55
Agra
UP
India
Page 19 of 53
The above example shows the Aggregation between Student and Address classes. You can see that in
Student class, we have used the Address class to obtain the Student class.

Why do we need Aggregation?


To maintain code re-usability. To understand this, let’s consider the above example again. Suppose there
are two other classes College and Staff along with two classes Student and Address. In order to maintain
Student’s address, College Address and Staff’s address, we don’t need to use the same code over and over
again. We just have to use the reference of Address class while defining each of these classes like:

Student Has A Address (Has a relationship between student and address)

College Has A Address (Has a relationship between college and address)

Staff Has A Address (Has a relationship between staff and address)

Hence, we can improve code re-usability by using the Aggregation relationship.

Definitions

A class describes the variables and methods appropriate to some real-world entity.

An object is an instance of a class and is an actual real-world entity.

Inheritance is the ability of a class to use the variables and methods of a class from which the
new class is derived.

Aggregation is a directional association between two classes to help improve code re-usability.

Page 20 of 53
Declarative Programming
In declarative programming, the programmer can simply state what is wanted having declared a set of
facts and rules. We now look at how this works using examples of Prolog scripts. In order to do this, we
shall use the following facts.

female(jane).

female(anne).

female(sandip).

male(charnjit).

male(jaz).

male(tom).

parent(jane,mary).

parent(jane, rajinder).

parent(charnjit, mary).

parent(charnjit, rajinder).

parent(sandip, atif).

parent(jaz, atif).

Remember that variables must start with an uppercase letter; constants start with a lowercase letter.

Suppose we ask
male(X)
Prolog starts searching the database and finds male(charnjit) matches male(X) if X is given the value
charnjit. We say that X is instantiated to charnjit. Prolog now outputs:
X = charnjit
Prolog then goes back to the database and continues its search. It finds male(jaz) so outputs
X = jaz
And again continues its search. It continues in this way until the whole database has been searched.
The complete output is
X = charjit X = jaz
X = tom No
The last line means that there are no more solutions.

Page 21 of 53
The query male(X) is known as a goal to be tested. That is, the goal is to find all X that satisfy male(X). If
Prolog finds a match, we say that the search has succeeded and the goal is true. When the goal is true,
Prolog outputs the corresponding values of the variables.

Now we shall add the rule:

father(X,Y) :- parent(X,Y), male(X).

This rule states that X is the father of Y if (the :- symbol) X is a parent of Y AND (the comma) X is a
male.

The database now looks like this:

female(jane).
female(anne).
female(sandip).
male(charnjit).
male(jaz).
male(tom).
parent(jane,mary).
parent(jane, rajinder).
parent(charnjit, mary).
parent(charnjit, rajinder).
parent(sandip, atif).
parent(jaz, atif).
father(X, Y) :- parent(X, Y), male(X).

Suppose our goal is to find the father of rajinder. That is, our goal is to find all X that satisfy:
father(X, rajinder)
In the database and the rule the components female, male, parent and father are called predicates and
the values inside the parentheses are called arguments. Prolog now looks for the predicate father and
finds the rule:
father(X,Y) :- parent(X,Y), male(X)
In this rule, Y is instantiated to rajinder and Prolog starts to search the database for:
parent(X,rajinder)
This is the new goal, Prolog finds the match:
parent(jane, rajinder)
If X is instantiated to jane, Prolog now uses the second part of the rule:
male(X)

Page 22 of 53
With X = jane. That is, Prolog’s new goal is male(jane) which fails. Prolog does not give up at this stage
but backtracks to the match
parent(jane, rajinder)

And starts again, from this point in the database, to try to match the goal
parent(X, rajinder)
This time, Prolog finds the match:
parent(charnjit, rajinder)
With X instantiated to charnjit. The next step is to try to satisfy the goal
male(charnjit)

This is successful so
Parent(charnjitm rajinder) and male(charjit)
Are true. Thus father(charnjitm rajinder) is true and Prolog returns
X = charnjit

Prolog continues to see if there are any more matches. Since there aren’t any more matches, Prolog
outputs:

No

A powerful tool is Prolog is recursion. This can be used to create alternative versions for a rule. This is
demonstrated in the figure below and shows how ancestor is related to parent.

This shows that X is an ancestor of Y if X is a parent of Y. But it also shows that X is an ancestor of Y if X is
a parent of Z and Z is a parent of Y. It also shows that X is an ancestor of Y if X is a parent of Z , and Z is a
parent of W and W is a parent of Y. This can continue forever. Thus the rule is recursive. In Prolog we
require two rules that are written as:

Page 23 of 53
ancestor(X, Y) :- parent(X, Y).
ancestor(X, Y) :- parent(X, Z),
ancestor(Z, Y).

The first rule states that X is an ancestor of Y if X is a parent of Y. This is saying that a is an ancestor of b,
b is an ancestor of c and c is an ancestor of d.

The second rule is in two parts. Let us see how it works which represents the database

parent(a, b).
parent(b, c).
parent(c, d).
By setting the goal

Prolog finds the first rule and tries to match parent(a, c) with each predicate in the database. Prolog fails
but does not give up. It backtracks and looks for another rule for ancestor. Prolog finds the second rule
and tries to match

parent(a, Z).
It finds
Parent(a, b)
So instantiates Z to b.
This is now put into the second part of the rule to produce
ancestor(b, c).
This means that Prolog has to look for a rule for ancestor. It finds the first rule
ancestor(X, Y) :- parent(X, Y).
Thus Prolog looks for
parent(b, c)
and succeeds.

This means that with X = a, Y = c we have Z = b and the second rule succeeds. Therefore Prolog returns

Yes

Now try to trace what happens if the goals are


ancestor(a,d)
and
ancestor(c, b)

Page 24 of 53
You should find that the first goal succeeds and the second fails. This form of programming is based on
the mathematics of predicate calculus. Predicate calculus is a branch of mathematics that deals with
logic. All we have done in this Section is based on the rules of predicate calculus. Prolog stands for
Programming in LOGic and its notation is based on that of predicate calculus. In predicate calculus the
simplest structures are atomic sentences such as:

Mary loves Harry


Philip like Zak’

The words in italics are part of the names of relationships. We also have atomic conclusions such as:

Mary loves Harry if Harry loves Mary

John likes dogs if Jane likes dogs

Frank likes x if x likes computing

In the last atomic conclusion, x is a variable. The meaning of the conclusion is that Frank likes anything
(or anybody) that likes computing.

Joint conditions use the logical operators OR and AND, examples of which are

John likes x if x is female AND x is blonde

Mary loves Bill OR Mary loves Colin if Mary loves Don

The atomic formulae that serve as conditions and conclusions may be written in a simplified form.
In this form the name of the relation is written in front of the atomic formula. The names of the
relations are called predicate symbols. Examples are:

loves(Mary, Harry)

likes(Philip, Zak)

We use the symbol ← to represent if and have:

loves(Mary, Harry)  loves(Harry, Mary)

likes(John, dogs)  likes(Jane, dogs)

The AND is represented by a comma in the condition part of the atomic conclusion. For example:

likes(John, x) ← female(x), blonde(x)

The OR is represented by a comma in the conclusion. For example

female(x), male(x)  human(x)

Page 25 of 53
These examples show the connection between Prolog and predicate calculus. You do not need to
understand how to manipulate the examples you have seen any further than has been shown in this
Section.

As with the previous Section we include here the definitions of terms used in this Section. Remember,
they can be used when a question says ''State the meaning of the term …

Definitions
Backtracking is going back to a previously found successful match in order to continue a search.

Instantiation is giving a variable in a statement a value

Predicate logic is a branch of mathematics that manipulates logical statements that can be either
True or False.

A goal is a statement that we are trying to prove whether or not it is True or False.

Imperative Programming
This topic has been covered in detail in chapter 2.3

Page 26 of 53
20.2 File Processing and Exception Handling
In Visual Basic, records are known as structures.

A record is a value that contains other values, indexed by names and a Field is an element of a record.

Records are collections of data items (fields) stored about some object. They allow you to combine several
data items (or fields) into one variable. For example, at your institute they will have a database storing a
record for each student. This student record would contain fields such as Student ID, Name, and Date of
Birth. The following example that DOESN’T USE RECORDS might be adequate for entering the details for
one student:

Output

Page 27 of 53
But what if your institute has more than one student? We would then have to write:

It would take an awfully long time to declare them all, let alone writing data to them. So how do we solve
this? We need to combine 2 things we have learnt so far, the record and the array. We are going to make
an array of student records:

Page 28 of 53
In the code above, we took the concept of loops and arrays and we simply joined them to accommodate
adding records one after the other and also displaying the records that have been created.

The code above allows us to create records, but we would also want to write the records to a file and then
read the file to access the records later.

Opening & Closing Files


The first command to include in a program which needs to work with files is the Open
command. Open assigns the file to a numbered file handle , also called a channel, or
sometimes a buffer. The format of the command is:

Open “Filename” [For Mode] [AccessRestriction] [LockType] As #FileNumber

For example:

Open “[Link]” For Random Read Lock Read as #1

 [Link] is the name of the file in the disk directory.


 For Random means that access to the records can be random; if access is not specified then for
random is the default value.
 Read restricts access to Read-only – the user cannot write or change the records.
 Lock Read means that only the person reading the record can have access to it at any given time;
it is not shared among users.
 As #1 means the file is assigned file handle #1; for all processing in the program, it will always be
referred to as #1, and not its Filename.

Access Restriction a nd Lock Type are parameters that are used mostly with files in a
network environment. You use them when you want the file to be shared or not, and
you want to prevent certain users from changing or deleting things that they shouldn’t

For Mode in the Open statement indicated how the file will be used. There are 5 access modes:

 Input: open for sequential input; the file will be read sequentially starting from the beginning.
 Output: open for sequential output; records will be written sequentially starting at the beginning;
if the file does not exist, it is created; if it does exist, it is overwritten.
 Random: open for random read and write; any specific record can be accessed.
 Append: sequential output to the end of an existing file; if the file does not exist, it is created; it
does not overwrite the file.
 Binary: open for binary read and write; access is at byte level.

As mentioned earlier, if access mode is not specified in the Open statement, then
For Random is used by default.

Page 29 of 53
Once processing is finished, you need to close all the files that you have opened. The format for the close
statement is:

Close #FileNumber1 [, #FileNumber2] …

You can close any number of files with one close statement. Eg:

Close #1, #2, #3

If you only write “Close” then you can close all the open files.

Now suppose you have an Address Book which will store the details of people such as
First Name, Last Name, City, etc…

The form may look something like this:

Usually for sequential file access, records are written to a text file.
So the name and location of the text file should be specified in the
code.

Once the file has been created, we can use Notepad to look at it.
The entry in the form above has not been written. It gets written
only when you hit the Write button. Each field is stored as a
separate line in the file. When we read them, we read in the
same order as that in which they were written.

Page 30 of 53
The code to write to file is fairly straightforward. Once information has been entered into 7 TextBoxes, we use
a FOR … NEXT loop to execute the Write command. The reason for this is that the Write command outputs only
one field at a time. So, we have to do 7 writes to output the whole record. After the TextBoxes have been
written-out, we clear then to create the next record.

For random access, the command to write records is Put. Its format is:

Put #Filenumber, [RecordNumber], Variable

Record Number is optional and if omitted, variable is written in Next record position after Last Put or Get
statement.

The command to read records from a Random file is: Get. Its format is:

Get #FileNumber, [RecordNumber], Variable

If Record Number is omitted, next record is read from the file.

Page 31 of 53
Adding Data
Serial File
Adding data is simple – it is added to the end of the file:
OPEN File in WRITE MODE

GOTO End of File

WRITE NewData

CLOSE File

Sequential File
The addition of data to a sequential file is more complicated than in a serial file, because the record must be
inserted into the correct position – not just at the end of the file.

In practice, when a record is added to a sequential file, it is usual to create a new file and copy all the records
from the old file, but insert the new record in its correct position.

An algorithm for this is shown below:

OPEN a New File in WRITE MODE

OPEN Existing File in READ MODE

READ First Record in Existing File

REPEAT

IF key of Selected Record in Existing File < key of New Record THEN

COPY Selected Record into New File

ELSE

COPY New Record into New File

COPY Selected Record into new file

END IF

READ Next Record in Existing File

END REPEAT when new record has been copied


COPY ALL remaining records from Existing File into New File CLOSE
New File and Existing File

Page 32 of 53
Random File
Random Access Files – Key Concepts

 Used to access files faster as compared to sequential access files.


 Individual records of a random-access file can be accessed directly without searching other
records.
 Records are accessed by their record number.

Type emprecord

name1 As String * 10
age As Integer
End Type

Dim newemp As emprecord

Open "c:\[Link]" For Random As #1 Len = Len(newemp)

Dim recno As Integer

Dim temprec As emprecord

recno = Val(Trim([Link]))

temprec.name1 = Trim([Link])

[Link] = Val([Link])

Put #1, recno, temprec

Searching for & Retrieving Data


To retrieve data from a serial file, a program must examine the first record and then all
subsequent records until the desired one is found or until the end of the file has been reached.

Page 33 of 53
The following algorithm does this:

OPEN File in READ MODE

READ First Record

SET Variable Found = False

REPEAT

IF RequiredRecord = SelectedRecord THEN

SET Variable Found = True

ELSE

READ Next Record

END IF

END REPEAT when Found = True OR when EOF is reached

CLOSE File
Note that to be sure that a record does not exist in a serial file, every single record must be
examined.

Sequential File
Searching a sequential file is the same as searching a serial file, except that the search only has
to continue until a record with a higher Key field is reached – this would mean that the data is
not in the file.

OPEN File in READ MODE

READ First Record


SET Variables Found = False, Exists = True

REPEAT

IF RequiredRecord = SelectedRecord THEN

SET Variable Found = True

ELSE

READ Next Record

IF Key of RequiredRecord > Key of SelectedRecord THEN

Exists = False

Page 34 of 53
END IF

END IF

END REPEAT when Found = True OR Exists = False OR when EOF is reached

CLOSE File

Random File
Dim temprec As emprecord

Get #1, Val([Link]), temprec

[Link] = temprec.name1

[Link] = [Link]

Deleting Data
Serial & Sequential File
OPEN a NewFile in WRITE MODE

OPEN ExistingFile in READ MODE

READ First Record in ExistingFile

REPEAT

IF Key of SelectedRecord <> Key of RecordToDelete THEN

COPY SelectedRecord into NewFile

ELSE
DO NOT COPY SelectedRecord

END IF
READ Next Record in ExistingFile

END REPEAT when EOF is reached

CLOSE NewFile and ExisitingFile

DELETE ExistingFile

RENAME NewFile to Name of ExistingFile

Page 35 of 53
Random File
Unfortunately, VB6 Random Access files provide no direct mechanism for record deletion, primarily
because deletion leads to a rat's nest of other issues, such as file contraction (filling the empty space),
fragmentation (unused empty space), to name a couple. If you truly need to delete a record, about
the only option you have is to copy all the other records to a temporary file, delete the old file, and
rename the temp file to the "original" name - and, sadly, that's right from Microsoft. This is exactly
what we are doing in Sequential and Serial files above.

One thing you can do, which I'll admit up front isn't ideal, is to add a "deleted" field to your random -
access file, defaulting to 0, but changing to true, 1, or some other relevant value, to indicate that
the record is no longer valid.

Code Example:

Type SampleRecord
UserID As Long
lastName As String * 25
firstName As String * 25
Deleted As Boolean
End Type
'This logically deletes a record by setting
'Its "Deleted" member to True
Sub DeleteRecord(recordId As Long)
Dim targetRecord As SampleRecord
Dim fileNumber As Integer
fileNumber = FreeFile

Open "SampleFile" For Random As fileNumber Len = LenB(SampleRecord)

Get fileNumber, recordId, targetRecord

[Link] = True

Put #fileNumber, recordId, targetRecord

Close #fileNumber

End Sub

Page 36 of 53
Sub AddRecord(lastName As String, firstName As String)

Dim newRecord As SampleRecord


Dim fileNumber As Integer
Dim newRecordPosition As Long

[Link] = firstName
[Link] = lastName
[Link] = False
[Link] = 123 ' assume an algorithm for assigning this value

fileNumber = FreeFile
Open "SampleFile" For Random As fileNumber Len = LenB(SampleRecord)
newRecordPosition = LOF(fileNumber) / LenB(SampleRecord) + 1
Put #fileNumber, newRecordPosition, newRecord
Close #fileNumber

END Sub

Page 37 of 53
Exception Handling

An exception is a special condition that changes the normal flow of the program execution. That is,
when an event occurs that the compiler is unsure of how to deal with. Exceptions are the
programming languages way of throwing up its hands and saying, “I can’t deal with this situation, you
need to.”

There are a number of events that may seem awkward to the compiler of the programming language.
Here are the most common examples:

 Your code expects a value from an input that is currently null.


 Dividing by zero.
 Accessing an array index that is out of bounds. (Underflow, or Overflow)
 A string is entered where a number is required as input. (or any similar data-type mismatch
examples)
 Trying to access a file that isn’t at the location specified.

In all these instances, we are trying something that the language deems impossible, and an exception is
thrown.

Therefore, a good programmer should be more alert to the parts of the program that could trigger errors
and should write error handling code to help him/her in managing the errors. Writing error handling
code should be considered a good practice for programmers. However, there should not be too many
error handling codes in the program as it creates problems for the programmer to maintain and
troubleshoot the program later.

Error handling is an essential procedure in programming because it can help make the program error-
free. An error-free program can run smoothly and efficiently, and the user does not have to face all
sorts of problems such as program crash or system hang.

So in general, exception handling should be used whenever there is a possibility that an error may occur.

The Syntax for error handling in Visual Basic is “On Error GoTo program_label” where “program_label” is the
section of the code that is designed by the programmer to handle the error committed by the user. Once
an error is detected, the program will jump to the program_label section for error handling. It acts like a
bookmark in VB.

Page 38 of 53
Example:
The following code shows how to handle error ‘Division by Zero’.

The line ‘On Error GoTo error_handler’ is executed when there occurs an error in DIVISION. When we input
secondnum=0 then the ‘error_handler’ section of code is executed, simple!

It may be noticed that if there is no error, the error handling part of the code is NOT executed because of
the EXIT SUB present on line 8.

Java Try – Catch


Java Try - Block
The Java try block is used to enclose the code that might throw an exception, It must be used within the
method. Java try block must be followed by catch block.

Java Catch – Block


The Java catch block is used to handle the Exception. It must be used after the try block only.

You can use multiple catch blocks with a single try.

Take the following code for example.

Page 39 of 53
Output:

Exception in thread main [Link]:/ by zero

Because of the exception in the code above, the rest of the code after the exception will not be compiled,
the compiler will print an error message and terminate the faulty program.

We can easily resolve this issue by adding a try-catch block.

Output:
Exception in thread main [Link]:/ by zero rest of the code...

Now, as shown in the output above, the rest of the lines of code is executed

i.e. the statement is printed.

Page 40 of 53
Similarly in the language Python, there are different kinds of errors that you may face such as ValueError,
TypeError, NameError, IOError, EOFError, SyntaxError, etc…

EOF Error
Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF)
without reading any data.

Handling EOF Error

Keyboard Interrupt
Raised when the user hits the interrupt key (normally Control-C or Delete).

Handling Keyboard Interrupt

Page 41 of 53
Value Error
Raised when a built-in operation or function receives an argument that has the right type but an
inappropriate value, and the situation is not described by a more precise exception.

Handling of Value Error

Page 42 of 53
20.2 File Processing and Exception Handling

May/June 2015.P31/P32

3 (a) The following terms are used in object-oriented programming (OOP) and design.
Draw a line connecting each term to the appropriate definition. [6]
In the bottom box, state the term which matches the unused definition.

(b) A company’s website is maintained by several employees. The company has a number of
permanent employees whose job title is either ‘programmer’ or ‘web designer’.

An agency supplies the company with contract employees when there is a need for specialist
skills. Contract employees have the job title ‘graphic designer’ or ‘technical author’.

Page 1 of 26
Employees have recorded:

 Employee reference number


 Date first worked for company

Contract Employees have recorded:

 Agency they were supplied by


 Agreed hourly rate of pay
 Job role

Permanent employees have recorded:

 Salary grade
 Courses attended

Programmers have recorded:

 Programming languages used

Web designers have recorded:

 Mark-up languages used

This scenario is to be implemented using object-oriented programming. Complete the class diagram using
the classes:

Employee, Contract, Permanent, Programmer, Web Designer.

Show properties only for given data: [8]

Page 2 of 26
May/June 2015.P33
3 (a) An IT company works on two types of project; software projects and the installation of local
area networks. Software projects are either bespoke software for a particular client or off -the-shelf
software.

Projects have recorded

 Project ID
 Start Date
 Project Leader

Off-the-shelf software projects have recorded:

 Title
 Current State of Beta Testing
 N – not started
 O – ongoing
 C - completed
 Anticipated Retail Price
 Sales forecast for first year of sales (units)

Bespoke software projects have recorded:

 Customer Name
 Agreed Cost
 Agreed Delivery Date

Software projects have recorded:

 Programming Languages used


 Current state of alpha testing
 Coded using the same code as for beta testing

Networking projects have recorded:

 Client Name
 Agreed Cost

Page 3 of 26
This scenario is to be implemented using object-oriented programming. Complete the class diagram using
the classes: [8]

 Bespoke, Network, OffTheShelf, Project, Software.


 Show properties only for the given data.

(b) Terminology for object-oriented programming and design includes the following terms. Define
the following terms:

(i) Class [1]

(ii) Inheritance [1]

(c) Part of the pseudo code for the object-oriented programming is shown below.

CLASS PROJECT
PRIVATE ProjectID : STRING
<statements>
PROCEDURE set_ProjectID()
<statements>
ENDPROCEDURE
PROCEDURE get_ProjectID()
<statements>
ENDPROCEDURE
ENDCLASS

CLASS Network INHERITS Project


<statements>
ENDCLASS
// Main program …
DECLARE ThisNetworkProject: Network
<statements>
Explain the following terms w.r.t. Pseudo code:

(i) Instance [2]


(ii) Method [2]
(iii) Encapsulation [3]

Page 4 of 26
Oct/Nov 2015.P32
3 (a) The following table shows some assembly language instructions from the computer’s
instruction set.

The test program shown in memory locations 700 onwards is to be executed. Shown are:

 The first four instructions only of this program


 Other memory locations which contain data accessed by the program

Complete the trace table below for the first four program instructions. [4]

[4]

Page 5 of 26
May/June 2015.P41/P42
2 A declarative programming language is used to represent the knowledge base shown below:

01 capital_city(amman).
02 capital_city(beijing).
03 capital_city(brussels).
04 capital_city(cairo).
05 capital_city(london).
06 city_in_country(amman, jordan).
07 city_in_country(shanghai, china).
08 city_in_country(brussels, belgium).
09 city_in_country(london, uk).
10 city_in_country(manchester, uk).
11 country_in_continent(belgium, europe).
12 country_in_continent(china, asia).
13 country_in_continent(uk, europe).
14 city_visited(amman).
15 city_visited(beijing).
16 city_visited(cairo).

Three clauses have the following meaning:

(a) More facts are to be included.


The travel writer visited the city of Santiago which is the capital city of Chile, in the continent of South
America.

Write additional clauses to record this. [4]

17 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………
18 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………
19 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………

Page 6 of 26
20 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………

(b) Using the variable ThisCountry,


the goal country_in_continent(ThisCountry, europe)
returns
ThisCountry = belgium, uk

Write the result returned by the goal: [2]

city_in_country(ThisCity, uk)

ThisCity = .................................................................................................................. .........

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

(c) Complete the rule below to list the countries the travel writer has visited. [4]
countries_visited(ThisCountry)
IF .........................................................................................................................................
............................................................................................................................. ................
.................................................................................................................................. ...........
....................................................................................................................... ......................
………………………………………………………………………………………………………………………………….

4 A payroll program is to be written using an object-oriented programming language. An Employee


class is designed. Two subclasses have been identified:

 HourlyPaidEmployee who is paid a monthly wage calculated from their hourly


rate of pay and the number of hours worked during the month
 SalariedEmployee who is paid a monthly wage which is one 12th of their annual salary

(a) Draw an inheritance diagram for these classes [3]


(b) The design for the Employee class consists of:

 Properties

EmployeeName
EmployeeID
AmountPaidThisMonth

 Methods

SetEmployeeName
SetEmployeeID
CalculatePay

Page 7 of 26
Write program code for the class definition of the superclass Employee. [5]

(c) (i) State the properties and/or methods required for the subclass HourlyPaidEmployee. [4]
(ii) State the properties and/or methods required for the subclass SalariedEmployee. [2]

(d) Name the feature of object-oriented program design that allows the method CalculatePay to
be declared in the superclass Employee. [1]

Page 8 of 26
May/June 2015.P43
2 A declarative programming language is used to represent the knowledge base shown below:

01 dairy_product(cheese).
02 meat(beef).
03 meat(chicken).
04 meat(lamb).
05 made_with(burger, beef).
06 made_with(kofta, lamb).
07 made_with(quiche, cheese).
08 made_with(quiche, egg).
09 made_with(quiche, flour).

These clauses have the following meaning:

(a) More facts are to be included.


Laasi is made with the dairy products milk and yogurt.
Write additional clauses to record this. [4]

10 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………
11 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………
12 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………
13 ………………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………………

(b) Using the variable TypeOfMeat, the goal


meat(TypeOfMeat)
returns
TypeOfMeat = beef, chicken, lamb

Write the result returned by the goal: [2]

Page 9 of 26
made_with(quiche, Ingredient)

Ingredient =...............................................................................................................................

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

(c) Complete the rule to list the dishes made with meat. [4]
contains_meat(Dish)
IF................................................................................................................................................
................................................................................................................................................
................................................................................................................................................
................................................................................................................................................
.................................................................................................................................................

4 A sports club stores data about its members. A program is to be written using an object -oriented
programming language.

A Member class is designed. Two subclasses have been identified

 FullMember
 JuniorMember

(a) Draw an inheritance diagram for these classes. [3]


(b) The design for the member class consists of:

 Properties

MemberName
SubscriptionPaid
AmountPaidThisMonth

 Methods

SetMemberName
SetMemberID
SetSubscriptionPaid

Write program code for the class definition of the superclass Member. [5]

(c) Additionally a DateOfBirth property is required for the JuniorMember class.


(i) Write program code for the class definition for the subclass JuniorMember. [3]
(ii) Write program code to create a new instance of JuniorMember. Use identifier NewMember
with the following data: [3]
name Ahmed with member ID 12347, born on 12/11/2001, who has paid his subscription.

Page 10 of 26
Oct/Nov 2015.P41/P43
2 A declarative programming language is used to represent the following facts and rules:

01 male(ali).
02 male(raul).
03 male(ahmed).
04 male(philippe).
05 female(meena).
06 female(aisha).
07 female(gina).
08 parent(ali, raul).
09 parent(meena, raul).
10 parent(ali, ahmed).
11 parent(meena, ahmed).
12 parent(ali, aisha).
13 parent(meena, aisha).
14 father(A, B) IF male(A) AND parent(A, B).

These clauses have the following meaning:

(a) More facts are to be included.


Philippe and Gina are the parents of Meena.

Write the additional clauses to record this. [2]

15 ……………………………………………………………………………………………………………………………………………………
……………………………………………………………………………………………………………………………………………………
16 ……………………………………………………………………………………………………………………………………………………
……………………………………………………………………………………………………………………………………………………

Page 11 of 26
(b) Using the variable P, the goal
parent(P, raul)
returns
P = ali, meena

Write the result returned by the goal [2]


parent(ali, C)
C = .................................................................................................................................................................

(c) Use the variable F to write the goal to find the father of Ahmed. [1]

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

(d) Write the rule to show that Xis the mother of Y. [2]
mother(X, Y)
IF …………………………………………………………………………………………………………………………………………………………....

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

(e) W is a grandparent of Zif W is a parent of one of Z’s parents. Complete the following rule: [2]
grandparent(W, Z)

IF
......................................................................................................................................................................

(f) Complete the rule to show that Gis a grandfather of K. [2]


grandfather(G, K)
IF……………………………………………………………………………………………………………………………………………………………….

3 A lending library stocks two types of item for loan: books and CDs.

All stock items have a title, the date the item was acquired and whether the item is currently out
on loan. Books have an author and ISBN. CDs have an artist and play time in minutes.

The library needs a program to process data about the stock items. The program will use an object -
oriented programming language.

Page 12 of 26
(a) Complete the class diagram showing the appropriate properties and methods. [7]

(b) Write program code.

(i) For the class definition for the superclass StockItem. [3]
(ii) For the class definition for the subclass Book. [3]
(iii) To create a new instance of Bookwith: [3]

 Identifier NewBook
 Title “Computers”
 Author [Link]
 ISBN 099111
 Acquired on 12/11/2001
 Not out on loan

Page 13 of 26
Oct/Nov 2015 P42
2 A declarative programming language is used to represent the following facts and rules:

01 male(ahmed).
02 male(raul).
03 male(ali).
04 male(philippe).
05 female(aisha).
06 female(gina).
07 female(meena).
08 parent(ahmed, raul).
09 parent(aisha, raul).
10 parent(ahmed, philippe).
11 parent(aisha, philippe).
12 parent(ahmed, gina).
13 parent(aisha, gina).
14 mother(A, B) IF female(A) AND parent(A, B).

These clauses have the following meaning:

(a) More facts are to be included.


Ali and Meena are the parents of Ahmed.

Write the additional clauses to record this. [2]

15 ……………………………………………………………………………………………………………………………………………………………
……………………………………………………………………………………………………………………………………………………………
16 ……………………………………………………………………………………………………………………………………………………………
……………………………………………………………………………………………………………………………………………………………

Page 14 of 26
(b) Using the variable C, the goal
parent(ahmed, C)
returns
C = raul, philippe, gina

Write the result returned by the goal parent(P, gina) [1]

(c) Use the variable M to write the goal to find the mother of Gina. [1]
(d) Write the rule to show that F is the father of C.
father(F, C)
IF …………………………………………………………….………………………………………………………………….

(e) Write the rule to show that X is a brother of Y. [4]


brother(X, Y)
IF ……………………………………………………………………………………………………………………………………

3 A college has two types of student: full-time and part-time. All students have their name and date
of birth recorded.

A full-time student has their address and telephone number recorded.

A part-time student attends one or more courses. A fee is charged for each course. The number of
courses a part-time student attends is recorded, along with the total fee and whether or not the
fee has been paid.

The college needs a program to process data about its students. The program will use an object
oriented programming language.

(a) Complete the class diagram showing the appropriate properties & methods. [7]

Page 15 of 26
(b) Write program code:
(i) For the class definition for the superclass Student. [2]
(ii) For the class definition for the subclass FullTimeStudent. [3]
(iii) To create a new instance of FullTimeStudent with: [3]
 identifier: NewStudent
 name: A. Nyone
 date of birth: 12/11/1990
 telephone number: 099111
5 The table shows assembly language instructions for a processor which has one general purpose
register – the Accumulator (ACC)

Page 16 of 26
(a) (i) Dry-run this assembly language program using the trace table. [5]

(ii) Explain the role address 511 has in this assembly language program. [2]
(b) Using opcodes from the given table, write instructions to set the value at address 509
to 12. [2]

Page 17 of 26
May/June 2018.P41/P43

1 A declarative language is used to represent facts and rules about flights.

01 direct(edinburgh, paris).
02 direct(palma, rome).
03 direct(glasgow, palma).
04 direct(glasgow, vienna).
05 direct(glasgow, salzburg).
06
07 flies(paris, fly_jet).
08 flies(mumbai, british_air).
09 flies(palma, ciebe).
10 flies(vienna, fly_jet).
11 flies(salzburg, ciebe).
12
13 can_fly(X, Y) IF direct(X, Z) AND direct(Z, Y).

These clauses have the following meaning:

(a) More facts need to be included. [2]


There is a direct flight from London to Rome and British Air flies to Rome.
14 ………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………
15 ………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………
(b) Using the variable Q, the goal flies(Q, fly_jet). returns
Q = paris, vienna

Write the result returned by the goal [2]


flies(K, ciebe).

K = ……………………………………………………………………………………………………………………………………………………..

Page 18 of 26
(c) Use the variable M to write the goal to find where you can fly direct from Glasgow. [2]
(d) If an airline flies to an airport, that airline also flies every direct route out of that airport.
Write a rule to represent this condition. [3]
Flies(Y, X)
IF ………………………………………………………………………………………………………………………………………...
(e) State what the following goal returns. [1]
can_fly(glasgow, rome).

5 A computer game is being developed using object-oriented programming. The following image is
a screenshot from the game.

There are scenery elements and animated elements. The player’s character is one of the animated
elements. Each game element has the attributes:

Each game element has a method, GetDetails() that returns a string containing all the element’s
attributes. The player’s character is one of a number of animated elements. All animated elements
have the attributes:

Page 19 of 26
The player’s character can either move left or right, or jump.

(a) Complete the following class diagram for the game.


You do not need to include any additional get or set methods.

(b) Write program code to define the GameElementclass.

(c) The Scenery() class has two attributes, CauseDamage and DamagePoints.
If the attribute CauseDamage is TRUE, then the scenery element can cause damage. The method
GiveDamagePoints() checks whether the object can cause damage.

If the object can cause damage, the method returns the integer value of the DamagePoints
attribute.

Write program code for the Scenery class. [6]

Page 20 of 26
(d) A new scenery object, GiftBox, is to be created.

(i) The attributes of GiftBox are as follows:

Write program code to create an instance of GiftBox. [3]

(ii) An additional method, GetScenery(), returns all the attributes of the Scenery class. Write
program code for the GetScenery()method.

You should use the GetDetails() method that the Scenery class inherits from the GameElement
class. [3]

Page 21 of 26
20.2 File Processing and Exception Handling

Oct/Nov 2015.P41/P43

5 Data about sports club members are stored in a random file of records.

 Other member data are stored.


 A hashing function is used to calculate a record address.
 The random file initially consists of dummy records.
 Dummy records are shown by member ID set to 0.

FUNCTION Hash(MemberID : INTEGER) RETURNS INTEGER


Address ← MemberID MOD 100
RETURN Address
ENDFUNCTION

(a) New members with the following member IDs have joined the sports club:
1001, 3005, 4096, 2098, 7002
Indicate where each record should be stored by deleting the zero and writing the member
ID in the correct cell: [2]

Page 22 of 26
(b) (i) The program stores a new member’s data in the record variable NewMember. The field
MemberID stores the member ID.
Complete the Pseudo code. [4]
10 // generate record address
20 NewAddress ← …………………………………………………………………………………………………………………
30 // move pointer to the disk address for the record
40 SEEK……………………………………………………………………………………………………………………………………
50 PUTRECORD "MembershipFile",
(iii) A record with member ID 9001 is to be stored.
Explain the problem that occurs when record is saved [2]

(iv) Describe a method, without changing the function Hash, to handle the problem
identified in part (b)(iii). [2]
(v) Write pseudo code to implement the method you described in part (b)(iv).
Choose line numbers to indicate where your pseudo code should be inserted in the
pseudo code of part (b)(i). [4]

Page 23 of 26
Oct/Nov 2015.P42
6 A company keeps details of its stock items in a file of records, StockFile.
(a) A stock report program uses a variable of type StockItem declared as follows:
DECLARE ThisStockItem : Stockitem
The program reads each record in the file StockFile in turn.

The program outputs the fields ProductCode and NumberInStock for each record.

Write pseudo code for this.

Page 24 of 26
20.2 File Processing and Exception Handling

Oct/Nov 2015.P41/P43

5 Data about sports club members are stored in a random file of records.

 The key field of a member record is the member ID (range 1000 to 9999).
 Other member data are stored.
 A hashing function is used to calculate a record address.
 The random file initially consists of dummy records.
 Dummy records are shown by member ID set to 0.

FUNCTION Hash(MemberID : INTEGER) RETURNS INTEGER


Address ← MemberID MOD 100
RETURN Address
ENDFUNCTION
(b) (ii) Before records can be saved to the file MembershipFile, the file needs to be opened.
(b) (ii) Before records can be saved to the file MembershipFile, the file needs to be opened.

Complete the pseudo code [2]

01 TRY
02 OPENFILE ………………………………….……………………………………………….……. FOR RANDOM
03 EXCEPT
04 ……………….…………..……………………………………………………………………………………………….
05 END TRY

Page 25 of 26
Oct/Nov 2015.P42

6 A company keeps details of its stock items in a file of records, StockFile.


(b) Before records can be read from file StockFile, the file needs to be opened.
(i) Complete the pseudo code. [2]

01 TRY
02 OPENFILE ……………………………………….…………………………………………………………………………………
03 EXCEPT
04 ………..…………………………………………………………………………………………………………………………………
05 ENDTRY

(ii) Explain the reason for including lines 01, 03, 04, 05. [2]

Page 26 of 26

You might also like