Chapter 20 SB Answers
Chapter 20 SB Answers
Activity 20A
Address Opcode Operand ACC IX
500 LDM #230 #230
501 LDD 230 #231
502 LDI 230 #5
503 LDR #1 #1
504 LDX 230 #5,#7,#9,#11,#0
505 CMP #0
506 JPE 509
507 INC IX #2,#3,#4,#5
508 JMP 504
509 JMP 509
Cambridge International AS & A Level Computer Science Answers
Activity 20B
Pseudocode – without procedures and functions
DECLARE base, height, radius : INTEGER
DECLARE area : REAL
DECLARE CONSTANT Pi = 3.142
OUTPUT "Please enter base, height and radius"
INPUT base, height, radius
area = base * base
OUTPUT "Area of square is ", area
area = base * height
OUTPUT "Area of rectangle is ", area
area = base * base / 2
OUTPUT "Area of triangle is ", area
area = base * height
OUTPUT "Area of parallelogram is ", area
area = Pi * radius * radius
OUTPUT "Area of circle is ", area
Cambridge International AS & A Level Computer Science Answers
Cambridge International AS & A Level Computer Science Answers
area = circle(radius)
printArea ("circle", area)
Cambridge International AS & A Level Computer Science Answers
def square(side):
return side * side
def circle(circRad):
Pi = 3.142
return circRad * circRad * Pi
area = square(base)
printArea ("square", area)
area = circle(radius)
printArea ("circle", area)
Cambridge International AS & A Level Computer Science Answers
Console.ReadKey()
End Sub
End Module
Cambridge International AS & A Level Computer Science Answers
Console.ReadKey()
End Sub
Cambridge International AS & A Level Computer Science Answers
}
}
Cambridge International AS & A Level Computer Science Answers
area = square(base);
printArea("square", area);
area = rectangle(base, height);
printArea("rectangle", area);
area = triangle(base, height);
printArea("triangle", area);
area = base * height;
printArea("parallelogram", area);
area = circle(radius);
printArea("circle", area);
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20C
Python
#ACTIVITY 20C classes and objects
class student:
def __init__(self, name, dateOfBirth, examMark):
self.name = name
self.dateOfBirth = dateOfBirth
self.examMark = examMark;
def displayExamMark(self):
print("Student Name " + self.name)
print("Exam Mark " , self.examMark)
myStudent.displayExamMark()
VB
'ACTIVITY 20C classes and objects
Module Module1
Public Sub Main()
Dim myStudent As New student("Mary Wu", #10/12/2012#, 67)
myStudent.displayExamMark()
End Sub
Class student
Dim name As String
Dim dateOfBirth As Date
Dim examMark As Integer
Public Sub New(ByVal n As String, ByVal d As Date, ByVal e As
Integer)
name = n
dateOfBirth = d
examMark = e
End Sub
End Module
Cambridge International AS & A Level Computer Science Answers
Java
//ACTIVITY 20C classes and objects
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class student{
private String name;
private LocalDate dateOfBirth;
private int examMark;
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20D
Python
#ACTIVITY 20D classes, objects and inheritance
class student:
def __init__(self, name, dateOfBirth, examMark):
self.name = name
self.dateOfBirth = dateOfBirth
self.examMark = examMark;
def displayExamMark(self):
print("Student Name " + self.name)
print("Exam Mark " , self.examMark)
class partTimeStudent(student):
def __init__(self, name, dateOfBirth, examMark):
student.__init__(self, name, dateOfBirth, examMark)
self.__fullTimeStudent = False
class fullTimeStudent(student):
def __init__(self, name, dateOfBirth, examMark):
student.__init__(self, name, dateOfBirth, examMark)
self.__fullTimeStudent = True
Cambridge International AS & A Level Computer Science Answers
VB
'ACTIVITY 20D classes, objects and inheritance
Module Module1
Public Sub Main()
Dim myFullTimeStudent As New fullTimeStudent("Mary Wu", #10/12/2012#, 67)
myFullTimeStudent.displayExamMark()
Dim myPartTimeStudent As New fullTimeStudent("Janet Yo", #05/23/2012#, 95)
myPartTimeStudent.displayExamMark()
Console.ReadKey()
End Sub
Class student
Dim name As String
Dim dateOfBirth As Date
Dim examMark As Integer
Public Sub New(ByVal n As String, ByVal d As Date, ByVal e As Integer)
name = n
dateOfBirth = d
examMark = e
End Sub
End Class
End Class
End Module
Cambridge International AS & A Level Computer Science Answers
Java
//ACTIVITY 20D classes, objects and inheritance
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class student{
private String name;
private LocalDate dateOfBirth;
private int examMark;
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20E
Python
# ACTIVITY 20E polymorphism
class shape:
def __init__(self):
self.__areaValue = 0
self.__perimeterValue = 0
def area(self):
print("Area ", self.__areaValue)
class square(shape):
def __init__(self, side):
shape.__init__(self)
self.__side = side
class rectangle(shape):
def __init__(self, length, breadth):
shape.__init__(self)
self.__length = length
self.__breadth = breadth
class circle(shape):
def __init__(self, radius):
shape.__init__(self)
self.__radius = radius
mySquare = square(10)
mySquare.area()
myCircle = circle(20)
myCircle.area()
Cambridge International AS & A Level Computer Science Answers
VB
'VB ACTIVITY 20E polymorphism
Module Module1
Public Sub Main()
Dim myCircle As New circle(20)
myCircle.Area()
Dim myRectangle As New rectangle(10, 17)
myRectangle.Area()
Dim mySquare As New square(10)
mySquare.Area()
Console.ReadKey()
End Sub
Class shape
Protected areaValue As Decimal
Protected perimeterValue As Decimal
End Class
End Module
Cambridge International AS & A Level Computer Science Answers
Java
// ACTIVITY20E polymorphism
class shape {
protected double areaValue;
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20F
Python
#ACTIVITY 20F overloading
class greeting:
myGreeting = greeting()
myGreeting.hello()
myGreeting.hello("Christopher")
myGreeting.hello("Christopher", "Robin")
VB
'ACTIVITY 20F overloading
Module Module1
Public Sub Main()
Dim myGreeting As New greeting
myGreeting.hello()
myGreeting.hello("Christopher")
myGreeting.hello("Christopher", "Robin")
Console.ReadKey()
End Sub
Class greeting
End Module
Cambridge International AS & A Level Computer Science Answers
Java
//ACTIVITY 20F overloading
class greeting{
public void hello(){
System.out.println("Hello");
}
class ACTIVITY20F{
public static void main(String[] args){
greeting myGreeting = new greeting();
myGreeting.hello();
myGreeting.hello("Christopher");
myGreeting.hello("Christopher","Robin");
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20G
flight
courseID : STRING
numberOfLectures : INTEGER
courseLecture [1 : 50] OF lecture
numberOfExams : INTEGER
courseExam [1 : 3] OF exam
:
:
Constructor ()
addLecture ()
addExam ()
removeLecture ()
removeExam
:
:
lecture exam
Name : STRING Name : STRING
lecturerName : STRING marks : INTEGER
: :
: :
: :
showLectureDetails () showExamDetails ()
: :
: :
Containment diagram for a university course
Cambridge International AS & A Level Computer Science Answers
Activity 20H
Sample Answer in Python
#ACTIVITY20H
class Node:
self.leftPointer = None
self.rightPointer = None
self.item = item
# Preorder traversal
def PreorderTraversal(self, tree):
Cambridge International AS & A Level Computer Science Answers
result = []
if tree:
result.append(tree.item)
result = result +
self.PreorderTraversal(tree.leftPointer)
result = result +
self.PreorderTraversal(tree.rightPointer)
return result
#print(tree.search(16))
tree.PrintInOrder()
print(tree.PreorderTraversal(tree)
Activity 20I
language(england,Language).
language(Country,japanese).
Activity 20J
savingsRate(laila, X).
bankAccount(X,savings,Y).
bankAccount(robert,savings,300.00).
interest(sevenPercent,savings,2000.00).
Cambridge International AS & A Level Computer Science Answers
Activity 20K
1 Absolute/Immediate – uses the operand, e.g. LDM #20 stores the denary value 20 in the
accumulator.
Direct – uses the contents of the memory location specified by the operand,
e.g. LDD 20 stores the value stored in the location with address 20 in the accumulator.
Indirect - uses the contents of the contents of the memory location specified by the operand, e.g.
LDI 20 stores the value stored in the location with the address stored at location 20 in the
accumulator.
Indexed – uses the value found at the memory location specified by adding operand to the contents
of the index register, e.g. LDX 20 stores the value stored in the location with address 20 plus the
contents of the index register in the accumulator.
2 Use of procedures and functions for procedural programming. For example, each procedure or
function is developed separately.
def square(side):
return side * side
Use of polymorphism in object-oriented programming where classes can be derived from other
classes. For example, the use of the base class shape and the derived classed for specific shapes.
class shape:
def __init__(self):
self.__areaValue = 0
self.__perimeterValue = 0
def area(self):
print("Area ", self.__areaValue)
class square(shape):
def __init__(self, side):
shape.__init__(self)
self.__side = side
Cambridge International AS & A Level Computer Science Answers
3 a) language(java,highLevel).
language(java,oop).
b) i) fortran
cobol
visualBasic
visualBasic
python
python
ii) false
c) translator(assembler,X).
Python
#set up file with one record
class TStudentRecord:
def _init_(self):
self.name =""
self.address = ""
self.className =""
studentFile = open('student.TXT','w')
myStudent = TStudentRecord()
myStudent.name = "Ahmad Sayed"
myStudent.address = "My House"
myStudent.className ="5X"
studentFile = open('student.TXT','r')
print (studentFile.read()) #print all the records in a file
studentFile.close()
myStudent = TStudentRecord()
myStudent.name = "Frank Yang"
myStudent.address = "My bungalow"
myStudent.className ="5X"
Cambridge International AS & A Level Computer Science Answers
studentFile.close()
studentFile = open('student.TXT','r')
print (studentFile.read())
studentFile.close()
#delete record
studentFile = open('student.TXT','r')
newStudentFile = open('newStudent.TXT', 'w')
recordRead = studentFile.readline()
studentFile.close()
newStudentFile.close()
VB
'student record
Imports System.IO
Module Module1
Sub Main()
'set up file with one record
Dim recordWrite, recordRead As String
Dim studentFileWrite As StreamWriter
Dim studentFileRead As StreamReader
studentFileWrite = New StreamWriter("student.txt")
Dim myStudent As TStudentRecord
studentFileRead.Close()
Cambridge International AS & A Level Computer Science Answers
myStudent.className = "5X"
Console.WriteLine("Name " + myStudent.name)
Console.WriteLine("Address " + myStudent.address)
Console.WriteLine("Class " + myStudent.className)
studentFileWrite = New StreamWriter("student.txt", True)
recordWrite = myStudent.name + " " + myStudent.address + " " +
myStudent.className
studentFileWrite.WriteLine(recordWrite)
studentFileWrite.Close()
studentFileRead.Close()
'delete record
studentFileRead = New StreamReader("student.txt")
studentFileWrite = New StreamWriter("newStudent.txt")
Do
recordRead = studentFileRead.ReadLine
If recordRead <> "Frank Yang" + " " + "My bungalow" + " " + "5X"
Then
recordWrite = recordRead
studentFileWrite.WriteLine(recordWrite)
End If
Loop Until recordRead Is Nothing
studentFileRead.Close()
studentFileWrite.Close()
My.Computer.FileSystem.DeleteFile("student.txt")
My.Computer.FileSystem.RenameFile("newStudent.txt", "student.txt")
Console.ReadKey()
End Sub
Structure TStudentRecord
Dim name As String
Dim address As String
Dim className As String
End Structure
End Module
Cambridge International AS & A Level Computer Science Answers
Java
//student record
import java.util.*;
import java.io.*;
class ShouldKnow_20_2_Q1 {
static class TStudentRecord {
String name;
String address;
String className;
String gender;
String studentFileWrite;
studentFileWrite = myStudentRecord.name + " " + myStudentRecord.address + "
" + myStudentRecord.className;
try {
FileWriter studentFileWriter = new FileWriter("student.txt", false);
PrintWriter studentWriter = new PrintWriter(studentFileWriter);
studentWriter.printf(studentFileWrite + "\n");
studentWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
myStudentRecord.name = "Frank Yang
myStudentRecord.address = "My Bungalow";
myStudentRecord.className = "5X";
Cambridge International AS & A Level Computer Science Answers
try {
FileReader studentFileReader = new FileReader("student.txt");
BufferedReader studentReader = new
BufferedReader(studentFileReader);
FileWriter studentFileWriter = new FileWriter("NewStudent.txt",
false);
PrintWriter studentWriter = new PrintWriter(studentFileWriter);
String studentFileRead;
} catch (IOException e) {
e.printStackTrace();
}
}
}
2 Serial – records are stored in a file one after another in the order they were added to the file.
Sequential – records are stored in a file in a given order based on the key field
Random – records are stored in a file in any available position based a hashing algorithm used on
the key field.
3 Direct – a record is found using a hashing algorithm without searching any other records.
Sequential – a record is found by searching each record in turn starting at the beginning of the
file.
Cambridge International AS & A Level Computer Science Answers
Activity 20L
Python
#ACTIVITY 20L
import datetime
import pickle
class student:
def __init__(self):
self.name = ""
self.registerNumber = 0
self.dateOfBirth = datetime.datetime.now()
self.fullTime = True
studentRecord = student()
studentFile = open('students.DAT','wb')
studentFile.close()
studentFile = open('students.DAT','rb')
studentRecord = pickle.load(studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)
studentFile.close()
Cambridge International AS & A Level Computer Science Answers
VB
' ACTIVITY 20L
Option Explicit On
Imports System.IO
Module Module1
studentFileWriter.Write(studentRecord.name)
studentFileWriter.Write(studentRecord.registerNumber)
studentFileWriter.Write(studentRecord.dateOfBirth)
studentFileWriter.Write(studentRecord.fullTime)
studentFileWriter.Close()
studentFile.Close()
studentRecord.name = studentFileReader.ReadString()
studentRecord.registerNumber = studentFileReader.ReadInt32()
studentRecord.dateOfBirth = studentFileReader.ReadString()
studentRecord.fullTime = studentFileReader.ReadBoolean()
studentFileReader.Close()
studentFile.Close()
Cambridge International AS & A Level Computer Science Answers
End Sub
class student:
Public name As String
Public registerNumber As Integer
Public dateOfBirth As Date
Public fullTime As Boolean
End Class
End Module
Java
//ACTIVITY20L no data of birth
import java.io.*;
import java.util.*;
class student {
private String name;
private int registerNumber;
private boolean fullTime;
String nameIn;
int registerNumberIn;
boolean fullTimeIn;
Cambridge International AS & A Level Computer Science Answers
try {
FileWriter studentFile = new FileWriter("student.txt");
studentFile.write(nameIn + " " + registerNumberAsString +
" " + fullTimeAsString);
studentFile.close();
}
catch (IOException e) {
System.out.println("File write error");
e.printStackTrace();
}
try {
File myStudent = new File("student.txt");
Scanner myReader = new Scanner(myStudent);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("File read error");
e.printStackTrace();
}
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20M
Sample Python
#ACTIVITY 20L updated
import datetime
import pickle
class student:
def __init__(self):
self.name = ""
self.registerNumber = 0
self.dateOfBirth = datetime.datetime.now()
self.fullTime = True
studentRecord = student()
studentFile.close()
studentFile = open('students.DAT','rb')
studentRecord = pickle.load(studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)
studentFile.close()
Cambridge International AS & A Level Computer Science Answers
Activity 20N
Python
#ACTIVITY 20N
try:
value = int(input('Please enter an integer value '))
except:
print('Not an integer')
VB
'ACTIVITY 20N
Module Module1
End Module
Java
//ACTIVITY20N
import java.io.*;
import java.util.*;
try {
System.out.println("Please input an integer value ");
int value = myObj.nextInt();
}
catch (InputMismatchException e) {
System.out.println("Not an integer");
}
}
}
Cambridge International AS & A Level Computer Science Answers
Activity 20O
Python
#checking file exists before trying to read from it
try:
studentFile = open('students.DAT','rb')
except OSError:
print("Could not open students.DAT")
sys.exit()
Visual Basic
'checking file exists before trying to read from it
Try
studentFile = New FileStream("studentFile.DAT", FileMode.Open)
Catch e As System.IO.IOException
Console.WriteLine("File not found")
End Try
Cambridge International AS & A Level Computer Science Answers
DateOfBirth : DATETIME
ShowDateOfBirth()
FullTimeStuden PartTimeStudent
NumberOfCourses : INTEGER
TelephoneNumber : STRING
Fee : Currency
FeePaid : BOOLEAN
Constructor()
Constructor()
ShowNumberOf Courses()
ShowTelephoneNumber()
ShowFee()
ShowFeePaid()
Cambridge International AS & A Level Computer Science Answers
b) i)
Python
class Student : def __int__(self) :
self.__StudentName = ""
self.__DateOfBirth = "" # date(1,1,2015)
def ShowStudentName() :
pass
def ShowDateOfBirth() :
pass
VB
Class Student
Public Sub ShowStudentName()
End Sub
Public Sub ShowDateOfBirth()
End Sub
Private StudentName As String
Private DateOfBirth As Date
End Class
ii)
Python
class FullTimeStudent(Student) : def
__init__(self) :
self.Address = ""
self.__TelephoneNumber = ""
def ShowAddress() :
pass
def ShowTelephoneNumber() :
pass
VB.NET
Class FullTimeStudent : Inherits Student
Sub ShowAddress()
End Sub
Sub ShowTelephoneNumber()
End Sub
Private Address As String
Private TelephoneNumber As String
End Class
Cambridge International AS & A Level Computer Science Answers
iii)
Python
NewStudent = FullTimeStudent()
NewStudent.StudentName = "A.Nyone"
NewStudent.DateOfBirth = "12/11/1990"
NewStudent.TelephoneNumber = "099111"
VB
Dim NewStudent As FullTimeStudent = New FullTimeStudent()
NewStudent.StudentName = "A.Nyone"
NewStudent.DateOfBirth = #11/12/1990#
NewStudent.TelephoneNumber = "099111"
3 a) Exception – situation causing a crash/run-time error/fatal error.
Exception handling – code which is called when a runtime error occurs to avoid the program
terminating/crashing.
b) Opening a non-existent file.
Using a directory path that does not exist.
Attempting to read past the end of the file.
c) i) 09
ii) Line 11 catches exceptions (only) between lines 05 and 10 and stops the program from
crashing.
Line 12 outputs the exception message if required.