Further Programming
Object-oriented programming, files, and handling errors without crashing.
RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
//A class in Cambridge pseudocode
Attributes are PRIVATE, methods that the outside world uses are PUBLIC. That is encapsulation in one line of layout.
CLASS Student
PRIVATE Name : STRING
PRIVATE Mark : INTEGER
PUBLIC PROCEDURE NEW(GivenName : STRING)
Name ← GivenName
Mark ← 0
ENDPROCEDURE
PUBLIC PROCEDURE SetMark(m : INTEGER)
IF m >= 0 AND m <= 100 THEN // validation!
Mark ← m
ENDIF
ENDPROCEDURE
PUBLIC FUNCTION GetMark() RETURNS INTEGER
RETURN Mark
ENDFUNCTION
ENDCLASS
DECLARE S : Student
S ← NEW Student("Bat")
CALL S.SetMark(78)//Why attributes are private
If any code could set Mark directly, someone could store 500 or −20 and the object would be invalid. Forcing changes through SetMark means the class can validate first. That validation is the whole point — and it is the mark.
//Inheritance and polymorphism together
A subclass INHERITS everything from its superclass and may add to it or override it. Polymorphism means you can hold a collection of superclass references and call the same method on each, and each object runs its own version.
CLASS Shape
PUBLIC FUNCTION Area() RETURNS REAL
RETURN 0
ENDFUNCTION
ENDCLASS
CLASS Circle INHERITS Shape
PRIVATE R : REAL
PUBLIC FUNCTION Area() RETURNS REAL // overrides
RETURN 3.14159 * R * R
ENDFUNCTION
ENDCLASS//Exception handling
An exception is a runtime error such as dividing by zero, a missing file, or text where a number was expected. Handling it lets the program recover and tell the user, instead of crashing.
TRY
OPENFILE "data.txt" FOR READ
READFILE "data.txt", Line
EXCEPT
OUTPUT "The file could not be opened"
ENDTRY//Programming paradigms
Procedural: a sequence of instructions grouped into procedures. Object-oriented: data and the operations on it bundled into objects. Declarative: you state the facts and rules and the language works out how — as in SQL or Prolog. Low-level: instructions matching the processor directly.
KEY TERMS
CHECK YOURSELF
1.Why are class attributes usually private?
2.A subclass provides its own version of a method that its superclass already has. This is: