20 Further Programming
20 Further Programming
20 Further programming
Key terms
Programming paradigm – a set of programming Method – a programmed procedure that is defined as
concepts. part of a class.
Low-level programming – programming instructions Encapsulation – process of putting data and methods
that use the computer’s basic instruction set. together as a single unit, a class.
Imperative programming – programming paradigm in Object – an instance of a class that is self-contained
which the steps required to execute a program are set and includes data and methods.
out in the order they need to be carried out. Property – data and methods within an object that
Object-oriented programming (OOP) – a programming perform a named action.
methodology that uses self-contained objects, which Instance – An occurrence of an object during the
contain programming statements (methods) and data, execution of a program.
and which communicate with each other.
Data hiding – technique which protects the integrity of
Class – a template defining the methods and data of a an object by restricting access to the data and methods
certain type of object. within that object.
Attributes (class) – the data items in a class.
498
499
234 11
235 0
Give the value stored in the accumulator (ACC) and the index register (IX)
after each of these instructions have been executed and state the mode of
addressing used.
Address Opcode Operand
500 LDM #230
501 LDD 230
502 LDI 230
503 LDR #1
504 LDX 230
505 CMP #0
506 JPE 509
507 INC IX
508 JMP 504
509 JMP 509
// this stops the program, it executes the same
instruction until the computer is turned off!
Class
A class is a template defining the methods and data of a certain type
of object. The attributes are the data items in a class. A method is a
programmed procedure that is defined as part of a class. Putting the data
and methods together as a single unit, a class, is called encapsulation. To
ensure that only the methods declared can be used to access the data within
a class, attributes need to be declared as private and the methods need to be
declared as public.
For example, a shape can have name, area and perimeter as attributes and
the methods set shape, calculate area, calculate perimeter.
This information can be shown in a class diagram (Figure 20.1).
class name Shape
Name : STRING
attributes declared as private Area : REAL
Perimeter : REAL
SetShape ()
attributes declared as public
calculateArea ()
calculatePerimeter ()
▲ Figure 20.1 Shape class diagram
501
Python
class employee:
def __init__ (self, name, staffno):
self.name = name
class definition self.staffno = staffno
def showDetails(self):
print("Employee Name " + self.name)
print("Employee Number " , self.staffno)
object myStaff = employee("Eric Jones", 72)
myStaff.showDetails()
VB
Module Module1
Public Sub Main()
object Dim myStaff As New employee("Eric Jones", 72)
myStaff.showDetails()
End Sub
class employee:
Dim name As String
Dim staffno As Integer
Public Sub New (ByVal n As String, ByVal s As Integer)
name = n
staffno = s
End Sub
Class
definition
Public Sub showDetails()
Console.Writeline("Employee Name " & name)
Console.Writeline("Employee Number " & staffno)
Console.ReadKey()
End Sub
End Class
End Module
502
Python
class employee:
def __init__(self, name, staffno):
attributes are private self.__name = name
self.__staffno = staffno
method is public
def showDetails(self):
use of __ denotes print("Employee Name " + self.__name)
private in Python print("Employee Number " , self.__staffno)
503
End Sub
Methods are public Public Sub showDetails()
Console.Writeline("Employee Name " & name)
Console.Writeline("Employee Number " & staffno)
Console.ReadKey()
End Sub
End Class
Java
// Java employee OOP program
class employee {
Attributes are private private String name;
private int staffno;
employee(String n, int s){
name = n; Constructor to set attributes
staffno = s;
}
Methods are public public void showDetails (){
System.out.println("Employee Name " + name);
System.out.println("Employee Number " + staffno);
}
}
public class MainObject{
public static void main(String[] args) {
employee myStaff = new employee("Eric Jones", 72);
myStaff.showDetails();
}
}
504
Inheritance
Inheritance is the process by which the methods and data from one class, a
superclass shape
derived classes
Multiple inheritance is where a derived class inherits from more than one
superclass (Figure 20.3).
superclass 1 superclass 2
derived class
505
VB
'VB Employee OOP program with inheritance
Module Module1
Public Sub Main()
Dim permanentStaff As New fullTime("Eric Jones", 72, 50000.00)
permanentStaff.showDetails()
Dim temporaryStaff As New partTime("Alice Hu", 1017, 45)
temporaryStaff.showDetails()
End Sub
506
507
name = n;
staffno = s;
}
public void showDetails (){
System.out.println("Employee Name " + name);
System.out.println("Employee Number " + staffno);
}
}
class partTime extends employee { derived class partTime
private boolean fullTimeStaff = false;
private int hoursWorked;
partTime (String n, int s, int h){
super (n, s);
hoursWorked = h;
}
public int getHoursWorked () {
return hoursWorked;
}
}
class fullTime extends employee { derived class fullTime
private boolean fullTimeStaff = true;
private double yearlySalary;
fullTime (String n, int s, double y){
super (n, s);
yearlySalary = y;
}
public double getYearlySalary () {
return yearlySalary;
}
}
508
Figure 20.4 shows the inheritance diagram for the base class employee and
the derived classes partTime and fullTime.
all employees have employee
these attributes name : STRING
staffNo : INTEGER only full time
employees have
fullTimeStaff : BOOLEAN
all employees have these attributes
showDetails () and methods
these methods
partTime fullTime
only part time employ-
ees have these attrib- hoursWorked : INTEGER yearlySalary : REAL
utes and methods getHoursWorked () GetYearlySalary ()
▲ Figure 20.4 Inheritance diagram for employee, partTime and fullTime
ACTIVITY 20D
Write a short program to declare a class, student, with the private
attributes name, dateOfBirth and examMark, and the public method
displayExamMark.
Declare the derived classes fullTimeStudent and partTimeStudent.
Declare objects for each derived class, with a name and exam mark of your
choice, and use your method to display the exam marks for these students.
509
20 class shape:
def __init__(self):
self.__areaValue = 0
self.__perimeterValue = 0
def area(self): original method in shape class
20 Further programming
VB
'VB shape OOP program with polymorphism
Module Module1
Public Sub Main()
Dim myCircle As New circle(20)
myCircle.area()
Dim myRectangle As New rectangle(10,17)
510
511
}
}
class rectangle extends shape {
private double length;
private double breadth;
rectangle(double l, double b){
length = l;
breadth = b;
}
public void area (){ redefined method in rectangle class
areaValue = length * breadth;
System.out.println("Area " + areaValue);
}
}
class circle extends shape {
private double radius;
circle (double r){
radius = r;
}
public void area (){ redefined method in circle class
areaValue = radius * radius * 3.142;
System.out.println("Area " + areaValue);
}
}
public class MainShape{
public static void main(String[] args) {
circle myCircle = new circle(20);
myCircle.area();
rectangle myRectagle = new rectangle(10, 17);
myRectagle.area();
}
}
512
VB
Module Module1
Public Sub Main()
Dim myGreeting As New greeting
myGreeting.hello() method used with no parameters
myGreeting.hello("Christopher")
Console.ReadKey() method used with one parameter
End Sub
Class greeting
Public Overloads Sub hello()
Console.WriteLine("Hello")
End Sub
Public Overloads Sub hello(ByVal name As String)
Console.WriteLine("Hello " & name)
513
20 End Class
End Module
Java
class greeting{
public void hello(){
20 Further programming
System.out.println("Hello");
}
public void hello(String name){
System.out.println("Hello " + name);
}
}
class mainOverload{
public static void main(String args[]){
greeting myGreeting = new greeting();
myGreeting.hello(); method used with no parameters
myGreeting.hello("Christopher");
} method used with one parameter
}.
ACTIVITY 20F
Write a short program to declare the class greeting, with the public
method hello, which can be used without a name, with one name or with a
first name and last name.
Declare an object and use the method to display each type of greeting.
Containment
Containment, or aggregation, is the process by which one class can contain
other classes. This can be presented in a class diagram.
When the class ‘aeroplane’ is defined, and the definition contains references to
the classes – seat, fuselage, wing, cockpit – this is an example of containment.
aeroplane
▲ Figure 20.5
crew passenger
firstName : STRING firstName : STRING
lastName : STRING lastName : STRING
role : STRING seatNumber : STRING
: :
: :
showCrewDetails () showPassengerDetails ()
: :
: :
▲ Figure 20.6
ACTIVITY 20G
Draw a containment diagram for a course at university where there are up
to 50 lectures, three examinations and the final mark is the average of the
marks for the three examinations.
Object methods
In OOP, the basic methods used during the life of an object can be divided into
these types: constructors, setters, getters, and destructors.
A constructor is the method used to initialise a new object. Each object is initialised
when a new instance is declared. When an object is initialised, memory is allocated.
515
20
construct a new employee object.
Constructor Language
def __init __(self, name, staffno): Python
self. __name = name
self. __staffno = staffno
Public Sub New (ByVal n As String, ByVal s As Integer) VB
20 Further programming
name = n
staffno = s
End Sub
▲ Table 20.1
▲ Table 20.2
Setter Language
def setName(self, n): Python
self. __ name = n
Public Sub setName (ByVal n As String) VB
name = n
End Sub
public void setName(String n){ Java
this.name = n;
}
▲ Table 20.3
Getter Language
def getHoursWorked (self): Python
return(self. __ hoursWorked)
Public Function getHoursWorked () As Integer VB
Return (hoursWorked)
public int getHoursWorked () { Java
return hoursWorked;}
▲ Table 20.4
516
20
is destroyed the memory is released so that it can be reused. Both Java and
VB use garbage collection to automatically destroy objects that are no longer
used so that the memory used can be released. In VB garbage collection can be
invoked as a method if required but it is not usually needed.
For example, in any of the Python programs above, this could be used as a
destructor:
def __del__(self)
Destructor Language
def __del __(self): Python
print ("Object deleted")
Protected Overrides Sub Finalize() VB – only if required,
Console.WriteLine("Object deleted") automatically called at
end of program
Console.ReadKey()
Java – not used
▲ Table 20.5
20
values in ascending order are set out in Tables 20.6–9 below. If you are unsure
how the binary tree works, review Chapter 19.
self.item = item
Public Class Node VB with a recursive definition of node
Public item As Integer to allow for a tree of any size
Public left As Node
Public right As Node
Public Function GetNodeItem()
Return item
End Function
End Class
class Node Java with a recursive definition of
{ node to allow for a tree of any size
int item;
Node left;
Node right;
GetNodeItem(int item)
{
this.item = item;
}
}
▲ Table 20.6
519
▲ Table 20.8
520
ACTIVITY 20H
In your chosen programming language, write a program using objects and
recursion to implement a binary tree. Test your program by setting the root
of the tree to 27, then adding the integers 19, 36, 42 and 16 in that order.
20
facts and rules. For example, the fact that France is a country would be written
in predicate logic as:
country(france).
Note that all facts in Prolog use lower-case letters and end with a full stop.
Another fact about France – the language spoken in France is French – could be
written as:
20 Further programming
language(france,french).
These facts are used to set up a knowledge base. This knowledge base can be
consulted using queries.
For example, a query about countries that speak a certain language, English,
could look like this:
language(Country,english)
The results are usually shown in the order the facts are stored in the knowledge base.
A query about the languages spoken in a country, Switzerland, could look like this:
language(switzerland,Language).
20
result is found when the goal is satisfied using the facts and rules available.
ACTIVITY 20I
Use the facts above to write queries to find out which language is spoken
in England and which country speaks Japanese. Take care with the use of
capital letters.
The results for the country Switzerland query would look like this in
SWI-Prolog:
prompt ?– 1anguage(switzerland,Language).
Language = french ; press ; to get the next result
Language = german ;
Language = italian.
Most knowledge bases also make use of rules, which are also written using
predicate logic.
Here is a knowledge base for the interest paid on bank accounts. The facts
about each account include the name of the account holder, the type of
account (current or savings), and the amount of money in the account. The
facts about the interest rates are the percentage rate, the type of account and
the amount of money needed in the account for that interest rate to be paid.
bankAccount(laila,current,500.00).
bankAccount(stefan,savings,50).
bankAccount(paul,current,45.00).
bankAccount(tasha,savings,5000.00).
facts
interest(twoPercent,current,500.00).
interest(onePercent,current,0).
interest(tenPercent,savings,5000.00).
interest(fivePercent,savings,0).
savingsRate(Name,Rate) :-
rule for the rate of
bankAccount(Name,Type,Amount), interest to be used
interest(Rate,Type,Base),
Amount >= Base.
523
20 savingsRate(stefan,X).
ACTIVITY 20J
Carry out the following activities using the information above.
1 Write a query to find out the interest rate for Laila’s bank account.
2 Write a query to find who has savings accounts.
3 a) Set up a savings account for Robert with 300.00.
b) Set up a new fact about savings accounts allowing for an interest rate
of 7% if there is 2000.00 or more in a savings account.
ACTIVITY 20K
1 Explain the difference between the four modes of addressing in a
low-level programming language. Illustrate your answer with assembly
language code for each mode of addressing.
2 Compare and contrast the use of imperative (procedural) programming
with OOP. Use the shape programs you developed in Activities 20B and
20E to illustrate your answer with examples to show the difference in the
paradigms.
3 Use the knowledge base below to answer the following questions:
language(fortran,highLevel).
language(cobol,highLevel).
language(visualBasic,highLevel).
language(visualBasic,oop).
language(python,highLevel).
language(python,oop).
language(assembly,lowLevel).
language(masm,lowLevel).
translator(assembler,lowLevel).
translator(compiler,highLevel).
524
Key terms
Read – file access mode in which data can be read from Close – file-processing operation; closes a file so it can
a file. no longer be used by a program.
Write – file access mode in which data can be written Exception – an unexpected event that disrupts the
to a file; any existing data stored in the file will be execution of a program.
overwritten. Exception handling – the process of responding to an
Append – file access mode in which data can be added exception within the program so that the program does
to the end of a file. not halt unexpectedly.
Open – file-processing operation; opens a file ready to
be used in a program.
525
TYPE
TstudentRecord
20 Further programming
526
ENDIF
CLOSEFILE(studentFile)
20
UNTIL studentRecord.name = ""
OUTPUT "The file contains these records: "
OPEN studentFile FOR READ
counter ← 1
If a sequential file was required, then the student records would need
to be input into an array of records first, then sorted on the key field
registerNumber, before the array of records was written to the file.
Here are programs in Python, VB and Java to write a single record to a file.
Python
import pickle Library to use binary files
class student:
def __init __(self):
self.name = ""
self.registerNumber = 0
self.dateOfBirth = datetime.datetime.now()
self.fullTime = True
studentRecord = student()
studentFile = open('students.DAT','w+b') Create a binary file to store the data
print("Please enter student details")
studentRecord.name = input("Please enter student name ")
studentRecord.registerNumber = int(input("Please enter student's register number "))
year = int(input("Please enter student's year of birth YYYY "))
month = int(input("Please enter student's month of birth MM "))
day = int(input("Please enter student's day of birth DD "))
527
VB
Option Explicit On
Imports System.IO Library to use Input and Output
Module Module1
Public Sub Main()
Dim studentFileWriter As BinaryWriter
Dim studentFileReader As BinaryReader
Dim studentFile As FileStream
Dim year, month, day As Integer Create a file to store the data
528
studentFile.Close()
Java
( Java programs using files need to include exception handling – see Section 20.2.2
later in this chapter.)
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.Date;
import java.text.SimpleDateFormat;
class Student {
private String name;
private int registerNumber;
private Date dateOfBirth;
529
}
public String toString() {
return name + " " + registerNumber + " " + dateOfBirth + " " + fullTime;
}
}
public class StudentRecordFile {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("Please Student details");
System.out.println("Please enter Student name ");
String nameIn = input.next();
System.out.println("Please enter Student's register number ");
int registerNumberIn = input.nextInt();
System.out.println("Please enter Student's date of birth as YYYY-MM-DD ");
String DOBIn = input.next();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date dateOfBirthIn = format.parse(DOBIn);
System.out.println("Please enter true for full-time or false for part-time ");
boolean fullTimeIn = input.nextBoolean();
Student studentRecord = new Student(nameIn, registerNumberIn, dateOfBirthIn,
fullTimeIn);
System.out.println(studentRecord.toString());
// This is the file that we are going to write to and then read from
File studentFile = new File("Student.txt");
// Write the record to the student file
// Note - this try-with-resources syntax only works with Java 7 and later
try (FileWriter studentFileWriter = new FileWriter(studentFile)) {
studentFileWriter.write(studentRecord.toString());
}
// Print all the lines of text in the student file
try (Scanner studentReader = new Scanner(studentFile)) {
530
ACTIVITY 20L
In the programming language of your choice, write a program to
n input a student record and save it to a new serial file
n read a student record from that file
n extend your program to work for more than one record.
531
532
Note that you can directly append a record to the end of a file in a
▲ Table 20.12
ACTIVITY 20M
In the programming language of your choice, write a program to
n input a student record and append it to the end of a sequential file
n find and output a student record from a sequential file using the key field
to identify the record
n extend your program to check for record not found (if required).
533
20 SEEK <filename>,<address>
GETRECORD <filename>,<recordname>
534
535
20 » programming errors
» user errors
» hardware failure.
Error handling is one of the most important aspects of writing robust programs
that are to be used every day, as users frequently make errors without realising,
and hardware can fail at any time. Frequently, error handling routines can take
a programmer as long, or even longer, to write and test as the program to
20 Further programming
Here are programs in Python, VB and Java to catch an integer division by zero
exception.
Python
def division(firstNumber, secondNumber):
try: integer division //
myAnswer = firstNumber // secondNumber
print('Answer ', myAnswer)
except:
print('Divide by zero')
division(12, 3)
division(10, 0)
VB
Module Module1
Public Sub Main()
division(12, 3)
division(10, 0)
Console.ReadKey()
End Sub
Sub division(ByVal firstNumber As Integer, ByVal secondNumber As Integer)
Dim myAnswer As Integer
Try integer division \
myAnswer = firstNumber \ secondNumber
Console.WriteLine("Answer " & myAnswer)
536
Java
ACTIVITY 20N
In the programming language of your choice, write a program to check that a
value input is an integer.
ACTIVITY 20O
In the programming language of your choice, extend the file handling
programs you wrote in Section 20.2.1 to use exception handling to ensure
that the files used exist and allow for the condition unexpected end of file.
537
20 questions rules:
01 male(ahmed).
02 male(raul).
03 male(ali).
04 male(philippe).
05 female(aisha).
20 FURTHER PROGRAMMING
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).
returns
C = raul, philippe, gina
c) Use the variable M to write the goal to find the mother of Gina. [1]
538
FullTimeStudent PartTimeStudent
Address : STRING ...............................
............................... ...............................
............................... ...............................
............................... ...............................
Constructor () ...............................
showAddress () ...............................
............................... ...............................
............................... ...............................
539
20
iii) to create a new instance of FullTimeStudent with:
– identifier: NewStudent
– name: A. Nyone
– date of birth: 12/11/1990
– telephone number: 099111 [3]
Cambridge International AS & A Level Computer Science 9608
Paper 42 Q3 November 2015
20 FURTHER PROGRAMMING
3 a) When designing and writing program code, explain what is meant by:
– an exception
– exception handling. [3]
b) A program is to be written to read a list of exam marks from an existing text
file into a 1D array.
Each line of the file stores the mark for one student.
State three exceptions that a programmer should anticipate for this program. [3]
c) The following pseudocode is to read two numbers.
29
30 ENDTRY