Skip to content · ⁨Lompat ke konten⁩

Further Programming · ⁨Pemrograman Lanjutan⁩

A-Level Computer Science · ⁨Ilmu Komputer A-Level⁩ · Topic 20 · ⁨Topik 20⁩

Video lesson for this topic · ⁨Pelajaran video untuk topik ini⁩ Open the video page · ⁨Buka halaman video⁩
13:52

Paradigma Pemrograman

Berikut adalah satu pekerjaan: daftarkan setiap siswa dengan nilai A. Satu programmer menulis sebuah perulangan — mulai dari rekaman pertama, periksa nilainya, tambahkan nama ke daftar, pindahkan…

English narration · English + 中文 subtitles burned in · ⁨Narasi bahasa Inggris · Subtitle bahasa Inggris + 中文 disematkan langsung⁩

20.1

Programming paradigms · ⁨Paradigma pemrograman⁩

Syllabus · ⁨Silabus⁩
English
Candidates should be able to: Notes and guidance
Understanding what is meant by a programming paradigm
Show understanding of the characteristics of a number of programming paradigms:
• Low-level Low-level Programming: • understanding of and ability to write 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
Bahasa Indonesia
Kandidat harus mampu: Catatan dan panduan
Memahami apa yang dimaksud dengan programming paradigm
Tunjukkan pemahaman tentang karakteristik beberapa programming paradigms:
• Low-level Low-level Programming: • pemahaman dan kemampuan untuk menulis kode low-level yang menggunakan berbagai addressing modes: immediate, direct, indirect, indexed dan relative
• Imperatif (Prosedural) Pemrograman Imperatif (Prosedural): • Pengetahuan dan pemahaman tentang Pemrograman Terstruktur (lihat detail di bagian konten AS 11.3) • pemahaman dan kemampuan menulis kode pemrograman imperatif (prosedural) yang menggunakan variabel, konstruk, prosedur, dan fungsi. Lihat detail di konten AS
• Berorientasi Objek Pemrograman Berorientasi Objek (OOP): • pemahaman terhadap terminologi yang terkait dengan OOP (termasuk objek, sifat/atribut, metode, kelas, pewarisan, polimorfisme, kontainment (agregasi), enkapsulasi, getter, setter, instansi) • pemahaman tentang cara memecahkan masalah dengan merancang kelas yang sesuai • pemahaman dan kemampuan menulis kode yang menunjukkan penggunaan OOP
• Deklaratif Pemrograman Deklaratif: • pemahaman dan kemampuan memecahkan masalah dengan menulis fakta dan aturan yang sesuai berdasarkan informasi yang diberikan • pemahaman dan kemampuan menulis kode yang dapat memenuhi tujuan menggunakan fakta dan aturan

Source: Cambridge International syllabus · ⁨Sumber: Silabus Cambridge International⁩

English

A programming paradigm 编程范式 is a style of programming — a way of structuring programs, with its own ideas and language features. Four programming paradigms are in this syllabus.

"Describe what is meant by an imperative (procedural) language" (two marks). A language in which the program is a sequence of instructions that are executed in order and that change the program's state; the programmer says how the task is done, using procedures, sequence, selection and iteration. "Describe what is meant by a declarative language": the program states facts and rules (what is known and what is wanted) and the language's inference engine works out how to find the answer; the programmer does not give the sequence of steps.

Identify the paradigm from a code sample (a regular Paper 3 question): LDD 200, ADD #5, STO 201 is low-level (mnemonics, registers, memory addresses); FOR Count ← 1 TO 10 … NEXT Count with procedures and assignments is imperative; CLASS Dog … PRIVATE Name : STRING … PUBLIC PROCEDURE NEW(…) is object-oriented; type(lion, wild). and dangerous(X) IF type(X, wild) is declarative (logic). In the matching question: low-level pairs with "mnemonics that correspond directly to machine instructions", imperative with "a sequence of statements that change the state", OOP with "objects that combine attributes and methods", declarative with "facts and rules, with no order of execution given".

Low-level programming

Programming close to the hardware in machine code 机器码 or assembly language 汇编语言, where each instruction maps to what the CPU runs. It gives direct access to registers 寄存器 and memory addresses 内存地址, using different addressing modes 寻址方式 (immediate, direct, indirect, indexed and relative). It is very fast and compact, but architecture-specific, tedious, and hard to maintain. This is low-level 低级 programming, used for device drivers, firmware and bootloaders.

The five addressing modes. The syllabus asks for low-level code that uses each addressing mode (the instruction set is in Topic 4). The operand of a load instruction can be read five ways, and the exam gives you the memory contents and asks what the accumulator holds:

  • immediate (LDM #105): the operand is the value; ACC becomes 105.
  • direct (LDD 105): the operand is the address of the value; ACC becomes the contents of 105, here 27.
  • indirect (LDI 105): the operand is the address of an address; ACC becomes the contents of 27, here 91. Used for pointers and for data whose position is decided at run time.
  • indexed (LDX 105): the address is the operand plus the index register IX; with IX = 2, ACC becomes the contents of 107. Used to step through an array by incrementing IX.
  • relative (JMR +65): the target is an offset from the address of the current instruction, which makes the code relocatable.

Worked example. Memory: 105 holds 27, 106 holds 64, 200 holds 0. Write code to add the contents of 105 and 106, store the result in 200 and output it. LDD 105 (ACC = 27), ADD 106 (ACC = 91), STO 200, OUT. To double the value in 105 instead: LDD 105, ADD 105, STO 105. State the register contents after each line when asked to trace.

Imperative (procedural) programming

In imperative programming 命令式编程 the programmer writes a sequence of commands that change the program's state — assignments, conditionals, loops, function calls. Variables 变量 hold state; statements change it; code is organised into procedures and functions (also called structured or structural programming). This is the style of Topics 9 and 11 (Python, C). Strong when the algorithm has clear sequential steps.

Object-oriented programming (OOP)

In object-oriented programming 面向对象编程 programs are built from objects 对象 — units combining data (attributes 属性) and operations (methods 方法). Objects are instances 实例 of classes 类. The four pillars:

  • encapsulation 封装 — an object's data is hidden behind its methods; outside code uses the public methods only, not the data directly. This protects the object and lets its internals change without breaking callers. For example, a BankAccount hides its balance; you change it only through deposit() and withdraw(), which can enforce a rule like "never go below zero".
  • inheritance 继承 — a subclass 子类 specialises a superclass 父类, inheriting its attributes and methods and adding or overriding 重写 them. Models "is-a" ("a Manager is an Employee").
  • polymorphism 多态 — different objects respond to the same method call differently; the caller need not know the exact type. Every Shape has Area(), and a Circle and a Rectangle each implement it their own way.
  • abstraction 抽象 — show a simple interface and hide the implementation.

Other terms:

  • a constructor 构造函数 is a special method run when an object is created, to set up its attributes.
  • getters and setters read and write an object's attributes (its properties) through methods.
  • aggregation 聚合 and containment 包含 build an object from other objects (a "has-a" relationship).

OOP is used for large systems, GUIs, simulations and games.

OOP as the examiner marks it

Definitions. Class: a template (blueprint) that defines the attributes and methods of the objects of that type. Object: an instance of a class, created from it, with its own values for the attributes ("an occurrence of an object" is the exam's phrase for an instance). Attribute (property): a data item belonging to a class. Method: a procedure or function belonging to a class that acts on its attributes. Encapsulation: combining the attributes and methods in one class and restricting external access to the data: the attributes are private and can only be read or changed through public methods. Inheritance: a subclass acquires the attributes and methods of its parent (super) class and can add its own or override them. Polymorphism: methods with the same name that behave differently in different classes; typically a subclass redefines a method of its parent, and the right version runs for each object. Containment: a class has an object of another class as an attribute (a car has an engine). "Identify the feature that restricts external access to the data" is encapsulation; "the term for an occurrence of an object" is instance.

"Outline the structure of a class" (three marks): attributes (properties) that hold the object's data, usually declared private; methods (procedures and functions) that act on those attributes, usually public; and a constructor, a method that runs when an object is created to initialise the attributes. "Give three benefits of OOP": code is reused through inheritance; data is protected by encapsulation, so it can only be changed by the class's own methods; a large program is split into classes that are written and tested independently, so it is easier to maintain and extend; classes model real-world entities, so the design is easier to understand; polymorphism lets the same call work for different objects.

The class in pseudocode, as Paper 3 sets it:

An object is created with MyCar ← NEW Car("AB12 CDE", 2020) and used with MyCar.AddMileage(150) and OUTPUT MyCar.GetMileage(). A subclass reuses the parent's constructor through SUPER:

The same class in Python, as Paper 4 expects it: attributes are made private with a double underscore, the constructor is __init__, and a subclass names its parent in brackets and calls super().__init__(…):

In Java the same ideas are private/public fields, a constructor with the class's name, extends and super(…); in VB.NET Private/Public, Sub New, Inherits and MyBase.New. A polymorphic method is written in the parent and overridden in the child with the same name; a call through a parent-type variable runs the child's version.

Data structures as objects. Paper 4 builds a stack, linked list or binary tree from a Node class whose attributes are the data and one or two references to other nodes; a Tree (or LinkedList) class holds the root (or start) and the methods.

A find method walks the same path and returns TRUE when Current.Data = Target, FALSE when it reaches NULL; an in-order output method is recursive: output the left subtree, the node, then the right subtree. For a linked list the node has one reference, Next, and the list class holds Start; for a stack built from a list, push and pop both work at Start.

Worked example. A game has characters. Each has a name, health (starting at 100) and a position given by X and Y. Write a class Character with a constructor and a method Move(DX, DY); then a subclass Wizard that adds Mana (starting at 50) and a method CastSpell() that takes 10 mana and returns TRUE if there was enough.

The marks are for private attributes, a constructor that sets every attribute, the inheritance line, the call to the parent's constructor, and a method that uses and changes the object's own data. When the question asks for a class diagram, draw a box in three parts (name; attributes with - for private; methods with + for public) and join a subclass to its parent with an arrow pointing at the parent.

Declarative programming

In declarative programming 声明式编程 you say what to compute, not how — the runtime works out the steps. Two kinds:

  • functional programming 函数式编程 — built from pure functions 纯函数 (no side effects 副作用; same input always gives the same output) composed together. Examples: Haskell, Lisp.
  • logic programming 逻辑编程 — state facts and rules; the engine answers a goal (query) by inference. Example: Prolog.

A familiar declarative example is SQL 结构化查询语言: SELECT * FROM Customer WHERE Country = 'UK' says what you want, not how to walk the records.

Facts, rules and goals are what the exam tests in the declarative paradigm. Given these facts 事实 (statements that are true) and a rule 规则 (a conclusion that holds when its conditions hold):

"Write the result of the goal type(X, wild)": X = leopard, X = lion. The engine matches the goal against each fact in turn; every match is a solution, and a capital letter is a variable that the match fills in. "Write a fact to show that a cheetah is wild": type(cheetah, wild). "Explain what line 07 does": it defines a rule with the conclusion dangerous(X), which is true for any X that is both wild and large, so dangerous(A) returns A = leopard, A = lion. "Write a rule: a feature F may be available for a body style B if F is a feature and B is a body style and F is not unavailable for B": may_be_available(F, B) IF feature(F) AND body_style(B) AND NOT unavailable(F, B). Copy the exact predicate names and argument order used in the question's facts; a new fact ends with a full stop, and a rule's conditions are joined with AND.

Comparing paradigms

Paradigm Strength Typical languages
Low-level maximum control, speed assembly
Imperative direct, intuitive C, Python
Object-oriented modular, models entities Java, C#, Python
Functional clear, no side effects Haskell, F#
Logic inference, rules Prolog
Database data queries SQL

Modern languages often mix paradigms — Python supports all of procedural, OOP and functional. The right one depends on the problem.

Bahasa Indonesia

Sebuah paradigma pemrograman adalah gaya pemrograman — cara menyusun program, beserta ide-ide dan fitur bahasa tersendiri. Empat paradigma pemrograman terdapat dalam silabus ini.

"Jelaskan apa yang dimaksud dengan bahasa imperatif (prosedural)" (dua poin). Bahasa di mana program merupakan urutan instruksi yang dieksekusi secara berurutan dan yang mengubah状态 program; programmer menyatakan bagaimana tugas dilakukan, menggunakan prosedur, urutan, seleksi, dan iterasi. "Jelaskan apa yang dimaksud dengan bahasa deklaratif": program menyatakan fakta dan aturan (apa yang diketahui dan apa yang diinginkan) dan mesin inferensi bahasa menentukan bagaimana menemukan jawabannya; programmer tidak memberikan urutan langkah-langkahnya.

Identifikasi paradigma dari contoh kode (soal Paper 3 reguler): LDD 200, ADD #5, STO 201 adalah level rendah (mnemonik, register, alamat memori); FOR Count ← 1 TO 10 … NEXT Count dengan prosedur dan penugasan adalah imperatif; CLASS Dog … PRIVATE Name : STRING … PUBLIC PROCEDURE NEW(…) adalah berorientasi objek; type(lion, wild). dan dangerous(X) IF type(X, wild) adalah deklaratif (logika). Dalam soal menjodohkan: level rendah berpasangan dengan "mnemonik yang sesuai langsung dengan instruksi mesin", imperatif dengan "urutan pernyataan yang mengubah state", OOP dengan "objek yang menggabungkan atribut dan metode", deklaratif dengan "fakta dan aturan, tanpa urutan eksekusi yang diberikan".

Empat paradigma: level rendah, imperatif, berorientasi objek, dan deklaratif
Empat paradigma: level rendah, imperatif, berorientasi objek, dan deklaratif

Pemrograman level rendah

Pemrograman mendekati perangkat keras dalam kode mesin atau bahasa assembly, di mana setiap instruksi memetakan apa yang dijalankan CPU. Memberikan akses langsung ke register dan alamat memori, menggunakan berbagai mode pengalamatan (segera, langsung, tidak langsung, terindeks, dan relatif). Ini sangat cepat dan ringkas, namun spesifik arsitektur, melelahkan, dan sulit dipelihara. Ini adalah pemrograman level rendah, digunakan untuk driver perangkat, firmware, dan bootloader.

Lima mode pengalamatan. Silabus meminta kode level rendah yang menggunakan setiap mode pengalamatan (himpunan instruksi ada di Topik 4). Operand dari instruksi load dapat dibaca dengan lima cara, dan ujian memberikan isi memori serta bertanya apa yang disimpan akumulator:

Tabel memori dengan alamat 105, 106, 107, 27, dan 145 beserta isinya, di samping lima baris yang menunjukkan apa yang diterima akumulator dari LDM #105, LDD 105, LDI 105, LDX 105 dengan IX = 2, dan lompatan relatif
Operand yang sama, 105, dibaca lima cara: sebagai nilai, sebagai alamat, sebagai alamat dari sebuah alamat, sebagai alamat ditambah register indeks, dan sebagai offset dari instruksi saat ini
  • segera (LDM #105): operand adalah nilainya; ACC menjadi 105.
  • langsung (LDD 105): operand adalah alamat dari nilai tersebut; ACC menjadi isi dari 105, yaitu 27.
  • tidak langsung (LDI 105): operand adalah alamat dari sebuah alamat; ACC menjadi isi dari 27, yaitu 91. Digunakan untuk pointer dan data yang posisinya ditentukan pada waktu eksekusi.
  • terindeks (LDX 105): alamat adalah operand ditambah register indeks IX; dengan IX = 2, ACC menjadi isi dari 107. Digunakan untuk menelusuri array dengan menambah IX.
  • relatif (JMR +65): targetnya adalah offset dari alamat instruksi saat ini, yang membuat kode dapat direlokasi.

Contoh dikerjakan. Memori: 105 menyimpan 27, 106 menyimpan 64, 200 menyimpan 0. Tulis kode untuk menjumlahkan isi 105 dan 106, simpan hasilnya di 200, dan tampilkan. LDD 105 (ACC = 27), ADD 106 (ACC = 91), STO 200, OUT. Untuk mengalikan dua kali nilai di 105 alih-alih: LDD 105, ADD 105, STO 105. Nyatakan isi register setelah setiap baris jika diminta melakukan pelacakan.

Pemrograman Imperatif (Prosedural)

Dalam pemrograman imperatif, programmer menulis urutan perintah yang mengubah state program — penugasan, kondisional, perulangan, panggilan fungsi. Variabel menyimpan state; pernyataan mengubahnya; kode diorganisir menjadi prosedur dan fungsi (juga disebut pemrograman terstruktur atau struktural). Ini adalah gaya pada Topik 9 dan 11 (Python, C). Kuat ketika algoritma memiliki langkah sekuensial yang jelas.

Pemrograman Berorientasi Objek (OOP)

Dalam pemrograman berorientasi objek, program dibangun dari objek — unit yang menggabungkan data (atribut) dan operasi (metode). Objek adalah instansi dari kelas. Empat pilar utama:

  • enkapsulasi — data objek disembunyikan di balik metodenya; kode luar hanya menggunakan metode publik, bukan datanya secara langsung. Ini melindungi objek dan memungkinkan perubahan internal tanpa merusak pemanggil. Misalnya, sebuah BankAccount menyembunyikan balance; Anda mengubahnya hanya melalui deposit() dan withdraw(), yang dapat menerapkan aturan seperti "tidak pernah turun di bawah nol".
  • pewarisan — subkelas menspesialisasikan superkelas, mewarisi atribut dan metodenya serta menambah atau menimpa mereka. Memodelkan "is-a" ("Seorang Manajer adalah Karyawan").
  • polimorfisme — objek berbeda merespons pemanggilan metode yang sama secara berbeda; Caller tidak perlu mengetahui tipe pastinya. Setiap Shape memiliki Area(), dan sebuah Circle serta sebuah Rectangle masing-masing mengimplementasikannya dengan caranya sendiri.
  • abstraksi — tunjukkan antarmuka sederhana dan sembunyikan implementasinya.

Istilah lain:

  • konstruktor adalah metode khusus yang dijalankan saat objek dibuat, untuk mengatur atributnya.
  • getter dan setter membaca dan menulis atribut objek (sifatnya) melalui metode.
  • aggregasi dan kontainmen membangun sebuah objek dari objek lain (relasi "memiliki-a").

OOP digunakan untuk sistem besar, GUI, simulasi, dan game.

Bentuk pemanggilan yang sama. Area() menjalankan kode berbeda untuk setiap objek: Circle menghitung pi r kuadrat, Rectangle menghitung lebar dikali tinggi
Polimorfisme: pemanggilan metode yang sama menjalankan kode masing-masing objek
Diagram kelas UML untuk Shape: kotak tiga bagian dengan nama kelas, atribut privat (Name, Area, Perimeter, ditandai dengan minus) dan metode publik (SetShape, calculateArea, calculatePerimeter, ditandai dengan plus)
Diagram kelas untuk Shape: atribut privat dan metode publik
Diagram pewarisan UML: superclass employee di bagian atas, dengan subclass partTime dan fullTime di bawahnya, masing-masing terhubung ke superclass melalui panah generalisasi segitiga kosong dan menambahkan atribut serta metodenya sendiri
Pewarisan: partTime dan fullTime adalah subclass dari employee
Objek BankAccount dengan saldo privat yang hanya dapat diakses melalui metode publik deposit() dan withdraw(); kode di luar tidak dapat menyentuh data secara langsung
Encapsulasi: data objek bersifat privat, hanya dapat diakses melalui metode publiknya

OOP menurut penilai ujian

Definisi. Kelas: sebuah templat (cetak biru) yang mendefinisikan atribut dan metode objek tipe tersebut. Objek: sebuah instansi dari sebuah kelas, dibuat darinya, dengan nilai-nilai sendiri untuk atributnya ("kejadian dari sebuah objek" adalah istilah ujian untuk instansi). Atribut (properti): item data yang milik sebuah kelas. Metode: prosedur atau fungsi yang milik sebuah kelas yang bertindak pada atributnya. Encapsulasi: menggabungkan atribut dan metode dalam satu kelas dan membatasi akses eksternal terhadap data: atributnya privat dan hanya dapat dibaca atau diubah melalui metode publik. Pewarisan: subclass memperoleh atribut dan metode dari induknya (super) kelas dan dapat menambahkannya sendiri atau menggantinya. Polimorfisme: metode dengan nama yang sama yang berperilaku berbeda di kelas yang berbeda; biasanya sebuah subclass mendefinisikan ulang metode induknya, dan versi yang tepat dijalankan untuk setiap objek. Kontainmen: sebuah kelas memiliki objek dari kelas lain sebagai atribut (mobil memiliki mesin). "Identifikasi fitur yang membatasi akses eksternal terhadap data" adalah encapsulasi; "istilah untuk kejadian dari sebuah objek" adalah instansi.

"Jelaskan struktur sebuah kelas (tiga nilai):**" atribut (properti) yang menyimpan data objek, biasanya dideklarasikan privat; metode (prosedur dan fungsi) yang bertindak pada atribut-atribut tersebut, biasanya publik; dan konstruktor, sebuah metode yang dijalankan ketika objek dibuat untuk menginisialisasi atribut-atributnya. "Berikan tiga manfaat OOP:" kode digunakan kembali melalui pewarisan; data dilindungi oleh encapsulasi, sehingga hanya dapat diubah oleh metode kelas itu sendiri; program besar dibagi menjadi kelas-kelas yang ditulis dan diuji secara independen, sehingga lebih mudah dipelihara dan dikembangkan; kelas memodelkan entitas dunia nyata, sehingga desainnya lebih mudah dipahami; polimorfisme memungkinkan pemanggilan yang sama berfungsi untuk objek yang berbeda.

Kelas dalam pseudocode, sebagaimana ditetapkan dalam Paper 3:

CLASS Car
    PRIVATE Registration : STRING
    PRIVATE Year : INTEGER
    PRIVATE Mileage : INTEGER
    PUBLIC PROCEDURE NEW(NewReg : STRING, NewYear : INTEGER)
        Registration ← NewReg
        Year ← NewYear
        Mileage ← 0
    ENDPROCEDURE
    PUBLIC FUNCTION GetMileage() RETURNS INTEGER
        RETURN Mileage
    ENDFUNCTION
    PUBLIC PROCEDURE AddMileage(Extra : INTEGER)
        Mileage ← Mileage + Extra
    ENDPROCEDURE
ENDCLASS

Sebuah objek dibuat dengan MyCar ← NEW Car("AB12 CDE", 2020) dan digunakan dengan MyCar.AddMileage(150) dan OUTPUT MyCar.GetMileage(). Sebuah subclass menggunakan ulang konstruktor induk melalui SUPER:

CLASS ElectricCar INHERITS Car
    PRIVATE BatteryCapacity : REAL
    PUBLIC PROCEDURE NEW(NewReg : STRING, NewYear : INTEGER, NewCapacity : REAL)
        SUPER.NEW(NewReg, NewYear)
        BatteryCapacity ← NewCapacity
    ENDPROCEDURE
ENDCLASS

Kelas yang sama dalam Python, sebagaimana diharapkan dalam Paper 4: atribut dibuat privat dengan double underscore, konstruktor adalah __init__, dan sebuah subclass menamai induknya dalam kurung dan memanggil super().__init__(…):

class Car:
    def __init__(self, reg, year):
        self.__registration = reg
        self.__year = year
        self.__mileage = 0
    def get_mileage(self):
        return self.__mileage
    def add_mileage(self, extra):
        self.__mileage = self.__mileage + extra

class ElectricCar(Car):
    def __init__(self, reg, year, capacity):
        super().__init__(reg, year)
        self.__capacity = capacity

cars = []
cars.append(Car("AB12 CDE", 2020))
cars.append(ElectricCar("EV21 XYZ", 2023, 75.0))
cars[1].add_mileage(150)
print(cars[1].get_mileage())

Dalam Java, ide yang sama adalah private/public field, konstruktor dengan nama kelas, extends dan super(…); dalam VB.NET Private/Public, Sub New, Inherits dan MyBase.New. Metode polimorfik ditulis di induk dan ditimpa di anak dengan nama yang sama; pemanggilan melalui variabel tipe induk menjalankan versi anak.

Struktur data sebagai objek. Paper 4 membangun tumpukan (stack), daftar terkait (linked list) atau pohon biner dari sebuah Node kelas yang atributnya adalah data dan satu atau dua referensi ke node lain; sebuah Tree (atau LinkedList) kelas menyimpan akar (atau awal) dan metododnya.

Pohon biner dari Node objects: Root object Tree menunjuk ke node 15,oman Left dan Right references menunjuk ke node 8 dan 19, dan seterusnya, dengan None untuk referensi kosong *Pohon biner yang dibangun dari objek: setiap Node menyimpan Data ditambah referens Left dan Right, dan Tree menyimpan Root; penyisipan berjalan turun sepanjang referens

CLASS Node
    PUBLIC Data : INTEGER
    PUBLIC Left : Node          // NULL when there is no child
    PUBLIC Right : Node
    PUBLIC PROCEDURE NEW(NewData : INTEGER)
        Data ← NewData
        Left ← NULL
        Right ← NULL
    ENDPROCEDURE
ENDCLASS

CLASS Tree
    PRIVATE Root : Node
    PUBLIC PROCEDURE Insert(NewData : INTEGER)
        DECLARE NewNode, Current : Node
        DECLARE Placed : BOOLEAN
        NewNode ← NEW Node(NewData)
        IF Root = NULL THEN
            Root ← NewNode
        ELSE
            Current ← Root
            Placed ← FALSE
            WHILE NOT Placed
                IF NewData < Current.Data THEN
                    IF Current.Left = NULL THEN
                        Current.Left ← NewNode
                        Placed ← TRUE
                    ELSE
                        Current ← Current.Left
                    ENDIF
                ELSE
                    IF Current.Right = NULL THEN
                        Current.Right ← NewNode
                        Placed ← TRUE
                    ELSE
                        Current ← Current.Right
                    ENDIF
                ENDIF
            ENDWHILE
        ENDIF
    ENDPROCEDURE
ENDCLASS

Sebuah metode find berjalan di jalur yang sama dan mengembalikan TRUE saat Current.Data = Target, FALSE saat mencapai NULL; sebuah metode output in-order bersifat rekursif: output subtrees kiri, node, lalu subtrees kanan. Untuk linked list node memiliki satu referensi, Next, dan kelas daftar menyimpan Start; untuk stack yang dibangun dari daftar, push dan pop keduanya bekerja di Start.

Contoh terpecahkan. Sebuah game memiliki karakter. Masing-masing memiliki nama, kesehatan (dimulai dari 100) dan posisi yang diberikan oleh X dan Y. Tulislah sebuah kelas Character dengan konstruktor dan metode Move(DX, DY); kemudian sebuah subclass Wizard yang menambahkan Mana (dimulai dari 50) dan metode CastSpell() yang mengambil 10 mana dan mengembalikan TRUE jika ada cukup.

CLASS Character
    PRIVATE Name : STRING
    PRIVATE Health : INTEGER
    PRIVATE X : INTEGER
    PRIVATE Y : INTEGER
    PUBLIC PROCEDURE NEW(NewName : STRING, StartX : INTEGER, StartY : INTEGER)
        Name ← NewName
        Health ← 100
        X ← StartX
        Y ← StartY
    ENDPROCEDURE
    PUBLIC PROCEDURE Move(DX : INTEGER, DY : INTEGER)
        X ← X + DX
        Y ← Y + DY
    ENDPROCEDURE
ENDCLASS

CLASS Wizard INHERITS Character
    PRIVATE Mana : INTEGER
    PUBLIC PROCEDURE NEW(NewName : STRING, StartX : INTEGER, StartY : INTEGER)
        SUPER.NEW(NewName, StartX, StartY)
        Mana ← 50
    ENDPROCEDURE
    PUBLIC FUNCTION CastSpell() RETURNS BOOLEAN
        IF Mana >= 10 THEN
            Mana ← Mana - 10
            RETURN TRUE
        ELSE
            RETURN FALSE
        ENDIF
    ENDFUNCTION
ENDCLASS

Nilai-nilai tersebut untuk atribut privat, konstruktor yang menetapkan setiap atribut, garis pewarisan, pemanggilan ke konstruktor induk, dan metode yang menggunakan dan mengubah data objeknya sendiri. Ketika pertanyaan meminta diagram kelas, gambarlah kotak dalam tiga bagian (nama; atribut dengan - untuk privat; metode dengan + untuk publik) dan hubungkan subclass ke induknya dengan panah yang menunjuk ke induk.

Pemrograman deklaratif

Dalam pemrograman deklaratif Anda menyatakan apa yang akan dihitung, bukan bagaimana — runtime menentukan langkah-langkahnya. Dua jenis:

  • pemrograman fungsional — dibangun dari fungsi murni (tanpa efek samping; input yang sama selalu menghasilkan output yang sama) yang disusun bersama. Contoh: Haskell, Lisp.
  • pemrograman logika — mendefinisikan fakta dan aturan; mesin menjawab sebuah tujuan (kueri) melalui inferensi. Contoh: Prolog.

Contoh deklaratif yang umum adalah SQL: SELECT * FROM Customer WHERE Country = 'UK' menyatakan apa yang Anda inginkan, bukan bagaimana menelusuri catatan.

Fakta, aturan, dan tujuan adalah hal yang diuji dalam ujian pada paradigma deklaratif. Diberikan fakta berikut (pernyataan yang benar) dan sebuah aturan (kesimpulan yang berlaku ketika kondisinya terpenuhi):

01 type(leopard, wild).
02 type(lion, wild).
03 type(tabby, domestic).
04 size(leopard, large).
05 size(lion, large).
06 size(tabby, small).
07 dangerous(X) IF type(X, wild) AND size(X, large).

"Tulis hasil dari tujuan type(X, wild):" X = leopard, X = lion. Mesin mencocokkan tujuan terhadap setiap fakta secara bergantian; setiap kecocokan adalah solusi, dan huruf kapital adalah variabel yang diisi oleh kecocokan tersebut. "*Tulis sebuah fakta untuk menunjukkan bahwa cheetah adalah liar":" type(cheetah, wild). "Jelaskan apa yang dilakukan baris 07:" ia mendefinisikan aturan dengan kesimpulan dangerous(X), yang benar untuk setiap X yang merupakan liar dan besar, sehingga dangerous(A) mengembalikan A = leopard, A = lion. "Tulis sebuah aturan: fitur F mungkin tersedia untuk gaya bodi B jika F adalah fitur dan B adalah gaya bodi dan F tidak tidak tersedia untuk B:" may_be_available(F, B) IF feature(F) AND body_style(B) AND NOT unavailable(F, B). Salin nama predikat dan urutan argumen yang persis digunakan dalam fakta pertanyaan; fakta baru diakhiri dengan titik, dan kondisi aturan digabungkan dengan AND.

Membandingkan paradigma

Paradigma Kekuatan Bahasa tipikal
Tingkat rendah kontrol maksimal, kecepatan assembly
Imperatif langsung, intuitif C, Python
Berorientasi objek modular, memodelkan entitas Java, C#, Python
Fungsional jelas, tanpa efek samping Haskell, F#
Logika inferensi, aturan Prolog
Basis data kueri data SQL

Bahasa modern sering mencampur paradigma — Python mendukung semua procedural, OOP, dan fungsional. Yang tepat tergantung pada masalahnya.

Explore · ⁨Jelajahi⁩

Programming concept lab · ⁨Makmal konsep pengaturcaraan⁩

Connect examples to the programming idea they show. · ⁨Sambungkan contoh kepada idea pengaturcaraan yang ditunjukkannya.⁩

Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
English Bahasa Indonesia
programming paradigm/ˈprəʊɡræmɪŋ ˈpærədaɪm/ paradigma pemrograman
facts/fækts/ fakta
rule/ruːl/ aturnya
low-level/ləʊ ˈlevl/ tingkat rendah
registers/ˈredʒɪstəz/ register
memory addresses/ˈmeməri əˈdresɪz/ alamat memori
objects/ˈɒbdʒekts/ benda
attributes/ˈætrɪbjuːts/ atribut-atribut
methods/ˈmeθədz/ metodenya
machine code/məˈʃiːn kəʊd/ kode mesin
assembly language/əˈsemblɪ ˈlæŋɡwɪdʒ/ bahasa assembly
addressing modes/əˈdresɪŋ məʊdz/ mode pengalamatan
array/əˈreɪ/ array
imperative programming/ɪmˈperətɪv ˈprəʊɡræmɪŋ/ pemrograman imperatif
Variables/ˈveərɪəblz/ Variabel
object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ pemrograman berorientasi objek
instances/ˈɪnstənsɪz/ instansi
classes/ˈklæsɪz/ kelas
encapsulation/ɪnˌkæpsjʊˈleɪʃn/ enkapsulasi
inheritance/ɪnˈherɪtəns/ warisan
subclass/ˈsʌbklæs/ subclass
superclass/ˈsuːpəklæs/ superclass
overriding/ˌəʊvəˈraɪdɪŋ/ pengalihan
polymorphism/ˈpɒlɪmɔːfɪzəm/ polimorfisme
abstraction/əbˈstrækʃn/ abstraksi
constructor/kənˈstrʌktə/ konstruktor
aggregation/ˌæɡrɪˈɡeɪʃn/ agregasi
containment/kənˈteɪnmənt/ keanggotaan
declarative programming/dɪˈklærətɪv ˈprəʊɡræmɪŋ/ pemrograman deklaratif
functional programming/ˈfʌŋkʃənl ˈprəʊɡræmɪŋ/ pemrograman fungsional
pure functions/pjʊə ˈfʌŋkʃnz/ fungsi murni
side effects/saɪd ɪˈfekts/ efek samping
logic programming/ˈlɒdʒɪk ˈprəʊɡræmɪŋ/ pemrograman logika
SQL/ˌes kjuː ˈel/ SQL
20.2

File processing · ⁨Pemrosesan file⁩

Syllabus · ⁨Silabus⁩
English
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 importance of exception handling Know when it is appropriate to use exception handling Write program code to use exception handling
Bahasa Indonesia
Kandidat harus mampu: Catatan dan panduan
Tulis kode untuk melakukan operasi pemrosesan file Buka (dalam mode baca, tulis, lampiran) dan tutup file Baca rekord dari file dan tulis rekord ke file Lakukan operasi pemrosesan file pada file serial, sekuensial, acak
Tunjukkan pemahaman tentang pengecualian dan pentingnya penanganan pengecualian Tahu kapan menggunakan penanganan pengecualian secara tepat Tulis kode program untuk menggunakan penanganan pengecualian

Source: Cambridge International syllabus · ⁨Sumber: Silabus Cambridge International⁩

English

This extends the file 文件 handling from Topic 10, processing serial, sequential and random (direct-access) files. Pseudocode operations: OPENFILE name FOR READ | WRITE | APPEND (READ opens an existing file, WRITE creates/overwrites, APPEND adds to the end); READFILE name, line; WRITEFILE name, value; CLOSEFILE name; and EOF(name) which is TRUE at the end.

Read a whole file:

Search a file (stop when found):

Updating a file in place

Most languages can't edit a text file in place. Instead: open the original for READ and a temporary file for WRITE; for each line, write the new version if it should change, else the original; close both; then replace the original with the temp file. The same pattern handles deleting lines (skip them) and inserting lines.

Records and random-access files

Opening modes. READ: the file must exist and reading starts at the beginning. WRITE: a new file is created, and an existing file of that name is overwritten. APPEND: writing adds to the end of an existing file. Every file that is opened is closed with CLOSEFILE, and EOF(name) is TRUE when the last item has been read.

Three file organisations. In a serial file the records are in the order they were added; in a sequential file they are in key order; both are read from the start. A random file 随机文件 (direct-access file) stores each record at an address calculated from its key by a hashing 哈希 function, so one record is found without reading the others. Records are declared as a user-defined type:

The random-file operations in pseudocode are OPENFILE "Acc.dat" FOR RANDOM, SEEK "Acc.dat", Address (move the file pointer to that record), GETRECORD "Acc.dat", Rec (read the record there) and PUTRECORD "Acc.dat", Rec (write the record there). Finding a customer by account number, as Paper 3 sets it:

To store a record, hash its key, SEEK to the address and PUTRECORD, stepping on past any slot already occupied. Marks go to the hash, the SEEK before the GET or PUT, the comparison with the target, the handling of a collision, and closing the file.

Worked example. ActiveFile.dat holds AccountRecord records. Write pseudocode that copies every record whose Active field is FALSE to the end of ArchiveFile.dat.

Text files in Python (Paper 4): file = open("HighScore.txt", "r"), then for line in file: with line.strip() and line.split(",") to separate the fields, int(…) to convert a score, and file.close(); to write, open(name, "w") (or "a" to append) and file.write(str(score) + "\n"). A high-score table is read into a list of records, the new score inserted at its place, and the whole list written back. The examiner marks the open with the correct mode, a loop that reads every line, the conversion of text to numbers, and the close.

Pitfalls

Forgetting to close a file (data may be lost); opening for WRITE when you meant APPEND (overwrites everything); reading past EOF; hard-coded paths — a path like /Users/Admin/data.txt breaks on another machine, so use a relative constant such as DataFile = "./data/scores.txt".

Bahasa Indonesia

Ini memperluas penanganan file dari Topik 10, memproses file serial, sekuen, dan acak (akses langsung). Operasi pseudocode: OPENFILE name FOR READ | WRITE | APPEND (READ membuka file yang ada, WRITE membuat/tertimpa, APPEND menambahkan di akhir); READFILE name, line; WRITEFILE name, value; CLOSEFILE name; dan EOF(name) yang bernilai TRUE di bagian akhir.

Baca seluruh file:

OPENFILE "names.txt" FOR READ
WHILE NOT EOF("names.txt") DO
    READFILE "names.txt", thisName
    OUTPUT thisName
ENDWHILE
CLOSEFILE "names.txt"

Cari file (berhenti saat ditemukan):

found ← FALSE
OPENFILE "people.txt" FOR READ
WHILE NOT EOF("people.txt") AND NOT found DO
    READFILE "people.txt", line
    IF line = target THEN
        found ← TRUE
    ENDIF
ENDWHILE
CLOSEFILE "people.txt"

Memperbarui file secara in-place

Sebagian besar bahasa tidak dapat mengedit file teks secara in-place. Sebaliknya: buka yang asli untuk READ dan file sementara untuk WRITE; untuk setiap baris, tulis versi baru jika harus berubah,否则 tulis yang asli; tutup keduanya; lalu ganti yang asli dengan file temp. Pola yang sama menangani penghapusan baris (lewatinya) dan penyisipan baris.

Memperbarui file secara in-place: baca file asli, tulis baris yang diubah ke file temp, lalu ganti yang asli dengan file temp
Memperbarui file secara in-place: baca yang asli, tulis perubahan ke file temp, lalu ganti yang asli

Record dan file akses acak

Mode pembukaan. READ: file harus ada dan pembacaan dimulai dari awal. WRITE: file baru dibuat, dan file yang sudah ada dengan nama itu ditimpa. APPEND: penulisan menambahkan ke akhir file yang sudah ada. Setiap file yang dibuka ditutup dengan CLOSEFILE, dan EOF(name) adalah TRUE ketika item terakhir telah dibaca.

Tiga organisasi file. Dalam file serial record berada dalam urutan penambahan; dalam file sekuen mereka berada dalam urutan kunci; keduanya dibaca dari awal. File acak (file akses langsung) menyimpan setiap record pada alamat yang dihitung dari kuncinya oleh fungsi hashing, sehingga satu record ditemukan tanpa membaca yang lain. Record dideklarasikan sebagai tipe yang didefinisikan pengguna:

TYPE AccountRecord
    DECLARE AccNo : INTEGER
    DECLARE Name : STRING
    DECLARE Balance : REAL
    DECLARE Active : BOOLEAN
ENDTYPE
Kunci 2317 di-hash dengan MOD 1000 ke alamat 317, kemudian SEEK dan GETRECORD pada file Acc.dat, ditampilkan sebagai baris slot record berukuran sama dengan slot 317 disorot
Menemukan satu record dalam file acak: kunci di-hash ke alamat, penunjuk file mencari langsung ke slot itu dan record dibaca; tidak ada record lain yang tersentuh

Operasi file acak dalam pseudocode adalah OPENFILE "Acc.dat" FOR RANDOM, SEEK "Acc.dat", Address (pindahkan penunjuk file ke record itu), GETRECORD "Acc.dat", Rec (baca record di sana) dan PUTRECORD "Acc.dat", Rec (tulis record di sana). Menemukan pelanggan berdasarkan nomor akun, seperti yang ditetapkan Paper 3:

DECLARE Rec : AccountRecord
DECLARE Target, Address : INTEGER
INPUT Target
Address ← Target MOD 1000              // the hashing function
OPENFILE "Acc.dat" FOR RANDOM
SEEK "Acc.dat", Address
GETRECORD "Acc.dat", Rec
WHILE Rec.AccNo <> Target AND Rec.AccNo <> 0    // 0 marks an empty slot
    Address ← Address + 1               // a collision: try the next slot
    SEEK "Acc.dat", Address
    GETRECORD "Acc.dat", Rec
ENDWHILE
IF Rec.AccNo = Target THEN
    OUTPUT Rec.Name, Rec.Balance
ELSE
    OUTPUT "No such account"
ENDIF
CLOSEFILE "Acc.dat"

Untuk menyimpan record, hash kuncinya, SEEK ke alamat dan PUTRECORD, melewati slot mana pun yang sudah ditempati. Nilai diberikan pada hashing, SEEK sebelum GET atau PUT, perbandingan dengan target, penanganan tabrakan, dan menutup file.

Contoh terpecahkan. ActiveFile.dat berisi AccountRecord record. Tulis pseudocode yang menyalin setiap record whose Active field is FALSE to the end of ArchiveFile.dat.

DECLARE Rec : AccountRecord
OPENFILE "ActiveFile.dat" FOR READ
OPENFILE "ArchiveFile.dat" FOR APPEND
WHILE NOT EOF("ActiveFile.dat")
    READFILE "ActiveFile.dat", Rec
    IF Rec.Active = FALSE THEN
        WRITEFILE "ArchiveFile.dat", Rec
    ENDIF
ENDWHILE
CLOSEFILE "ActiveFile.dat"
CLOSEFILE "ArchiveFile.dat"

File teks dalam Python (Kertas 4): file = open("HighScore.txt", "r"), lalu for line in file: dengan line.strip() dan line.split(",") untuk memisahkan field, int(…) untuk mengubah skor, dan file.close(); untuk menulis, open(name, "w") (atau "a" untuk melampirkan) dan file.write(str(score) + "\n"). Tabel skor tertinggi dibaca ke dalam daftar rekaman, skor baru disisipkan pada tempatnya, dan seluruh daftar ditulis kembali. Penguji memberikan nilai berdasarkan penggunaan mode yang benar saat membuka file, perulangan yang membaca setiap baris, konversi teks menjadi angka, dan penutupan file.

Jebakan

Lupa menutup file (data mungkin hilang); membuka untuk WRITE padahal bermaksud APPEND (menimpa segalanya); membaca melewati EOF; path yang dikodekan keras — path seperti /Users/Admin/data.txt rusak di mesin lain, jadi gunakan konstan relatif seperti DataFile = "./data/scores.txt".

Explore · ⁨Jelajahi⁩

File access route · ⁨Rute akses file⁩

Follow a file from storage to program and back safely. · ⁨Ikuti alur file dari penyimpanan ke program dan kembali dengan aman.⁩

Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
English Bahasa Indonesia
file/faɪl/ file
random file/ˈrændəm faɪl/ file acak
hashing/ˈhæʃɪŋ/ hashing
20.2

Exception handling · ⁨Penanganan pengecualian⁩

English

An exception 异常 is an error or unexpected condition during execution — divide by zero, file not found, network failure, an array 数组 index out of range. Exception handling 异常处理 lets a program detect it and respond gracefully instead of crashing.

It matters because real programs face errors that cannot be prevented up front (files moved, networks down, bad input); without it, every operation needs its own IF check; and it separates the normal flow from the error handling, so the main path reads cleanly. For example, a file may be deleted by another user between your program checking it exists and actually opening it — you cannot prevent that, only handle the failure when it happens.

"Describe, with an example, what is meant by an exception" (two marks). An unexpected event or error that occurs during the execution of a program (at run time) and interrupts its normal flow; for example dividing by zero, opening a file that does not exist, converting non-numeric input to an integer, an array index out of range, or running out of memory. "Identify two possible causes of exceptions" is answered from that list, plus "a device or network is not available" and "invalid data type entered".

"State the reasons for including exception handling" (three marks). To stop the program crashing (terminating unexpectedly); to output a meaningful message to the user rather than a system error; to allow the program to recover and continue, for example by asking for the input again, or to close files safely before it ends; and because some errors cannot be predicted when the program is written. "Describe how program termination due to an exception can be avoided": put the statements that might raise the exception inside a TRY block; write an EXCEPT (catch) block for that exception that handles it, for example by outputting a message, so that execution continues after the block instead of stopping. "Explain what is meant by exception handling": detecting an exception when it occurs and running code (the handler) that deals with it so that the program continues.

Pattern

The TRY block holds the code that might fail; the first matching EXCEPT block runs. Real languages also have a catch-all EXCEPT and a FINALLY block that runs whether or not an exception happened — useful for cleanup (closing files).

Raising an exception

A subroutine that detects an error can raise 抛出 an exception so the caller handles it:

Where to handle exceptions

Handle them close to the error if the response is simple (a message, a retry), or higher up the call stack 调用栈 if only the outer code knows what to do (a top-level GUI loop logs the error and shows a friendly dialog). Don't swallow exceptions silently — at least log them, or debugging becomes impossible.

Common exceptions: FileNotFound, IOError, DivisionByZero, IndexOutOfRange, InvalidArgument, NullReference, OutOfMemory. Wrapping each failing operation in a TRY with the right EXCEPT handlers gives a program that degrades gracefully instead of crashing.

Worked example (Paper 4). Write a function that reads whole numbers, one per line, from a file whose name is passed as a parameter and returns them in a list. It must not crash if the file does not exist or a line is not a whole number.

The try block holds the code that can fail (the open and the conversion); each except names one exception and does something useful; the function still returns a list, so the caller continues. In Java the same shape is try { … } catch (FileNotFoundException e) { … } catch (NumberFormatException e) { … }; in VB.NET Try … Catch ex As FileNotFoundException … End Try. Marks: the risky statements inside the try, the correct exception names, a message for each, and the program continuing afterwards; a catch-all except: gets the crash mark but not the "appropriate exception" mark.

Worked example. A text file of members needs one member's phone number changed. Why can the program not simply overwrite that line, and what is the pattern? A text file's lines are different lengths, and the file has no gaps to absorb a difference: a longer replacement would run into the next record, and a shorter one would leave part of the old line behind. So the pattern is to open the original for READ and a temporary file for WRITE, read every line in turn, writing the new version for the line that changes and the original line for all the others, close both, then replace the original with the temporary file. The same shape handles deleting (skip the line) and inserting (write the extra line). Note that every line gets written, not only the changed one - writing just the new record and losing the rest of the file is the classic slip.

Bahasa Indonesia

Sebuah pengecualian adalah kesalahan atau kondisi tak terduga selama eksekusi — pembagian dengan nol, file tidak ditemukan, kegagalan jaringan, indeks array di luar batas. Penanganan pengecualian memungkinkan program untuk mendeteksinya dan merespons dengan baik alih-alih mengalami crash.

Hal ini penting karena program nyata menghadapi kesalahan yang tidak dapat dicegah sejak awal (file dipindahkan, jaringan mati, input buruk); tanpa hal ini, setiap operasi memerlukan pemeriksaan IF sendiri; dan hal ini memisahkan alur normal dari penanganan error, sehingga jalur utama terbaca dengan jelas. Misalnya, sebuah file mungkin dihapus oleh pengguna lain antara saat program Anda memeriksa keberadaannya dan sebenarnya membukanya — Anda tidak dapat mencegah hal itu, hanya menangani kegagalan saat itu terjadi.

"Jelaskan, dengan contoh, apa yang dimaksud dengan pengecualian" (dua nilai). Kejadian atau kesalahan tak terduga yang terjadi selama eksekusi program (saat dijalankan) dan mengganggu alurnya yang normal; misalnya pembagian dengan nol, membuka file yang tidak ada, mengonversi input non-angka menjadi bilangan bulat, indeks array di luar batas, atau kehabisan memori. "Identifikasi dua kemungkinan penyebab pengecualian" dijawab dari daftar tersebut, ditambah "perangkat atau jaringan tidak tersedia" dan "tipe data yang dimasukkan tidak valid".

"Nyatakan alasan untuk menyertakan penanganan pengecualian" (tiga nilai). Untuk mencegah program crash (berhenti secara tak terduga); untuk menampilkan pesan bermakna kepada pengguna alih-alih pesan sistem; untuk memungkinkan program pemulihan dan melanjutkan, misalnya dengan meminta input lagi, atau menutup file dengan aman sebelum berakhir; dan karena beberapa kesalahan tidak dapat diprediksi saat program ditulis. "Jelaskan bagaimana penghentian program akibat pengecualian dapat dihindari": letakkan pernyataan yang mungkin memunculkan pengecualian di dalam blok TRY; tulis blok EXCEPT (catch) untuk pengecualian itu yang menanganinya, misalnya dengan menampilkan pesan, agar eksekusi berlanjut setelah blok alih-alih berhenti. "Jelaskan apa yang dimaksud dengan penanganan pengecualian": mendeteksi pengecualian saat terjadi dan menjalankan kode (the handler) yang menanganinya agar program tetap berjalan.

Pola

TRY
    OPENFILE "data.txt" FOR READ
    READFILE "data.txt", line
    OUTPUT line
    CLOSEFILE "data.txt"
EXCEPT FileNotFound
    OUTPUT "Sorry, the file does not exist."
EXCEPT ReadError
    OUTPUT "Sorry, error reading the file."
ENDTRY

Blok TRY berisi kode yang mungkin gagal; blok matching pertama dari EXCEPT akan berjalan. Bahasa asli juga memiliki catch-all EXCEPT dan blok FINALLY yang berjalan baik jika terjadi pengecualian maupun tidak — berguna untuk pembersihan (menutup file).

Aliran Pengecualian: jika blok TRY memunculkan pengecualian, kontrol melompat ke EXCEPT yang sesuai; tanpa pengecualian maka dilewati. Dalam kedua kasus, blok FINALLY berjalan, lalu program berlanjut
Aliran Pengecualian: pengecualian melompat ke EXCEPT yang sesuai; FINALLY selalu berjalan sebelum program berlanjut

Memunculkan pengecualian

Subrutin yang mendeteksi kesalahan dapat memunculkan pengecualian agar pemanggil menanganinya:

PROCEDURE Divide(a : INTEGER, b : INTEGER) RETURNS INTEGER
    IF b = 0 THEN
        RAISE DivideByZero
    ENDIF
    RETURN a DIV b
ENDPROCEDURE

Di mana menangani pengecualian

Tanganlah mereka dekat dengan kesalahannya jika responsnya sederhana (pesan, coba ulang), atau lebih tinggi di call stack jika hanya kode luar yang tahu apa yang harus dilakukan (loop GUI tingkat atas mencatat error dan menampilkan dialog ramah). Jangan serap pengecualian diam-diam — setidaknya catatlah, atau debugging menjadi mustahil.

Pengecualian umum: FileNotFound, IOError, DivisionByZero, IndexOutOfRange, InvalidArgument, NullReference, OutOfMemory. Membungkus setiap operasi yang gagal dalam sebuah TRY dengan handler EXCEPT yang tepat memberikan program yang melambat dengan baik alih-alih crash.

Contoh dikerjakan (Kertas 4). Tulis fungsi yang membaca bilangan bulat, satu per baris, dari file yang namanya diteruskan sebagai parameter dan mengembalikannya dalam sebuah list. Fungsi ini tidak boleh crash jika file tidak ada atau baris bukan bilangan bulat.

def read_scores(filename):
    scores = []
    try:
        file = open(filename, "r")
        for line in file:
            scores.append(int(line))
        file.close()
    except FileNotFoundError:
        print("The file", filename, "does not exist")
    except ValueError:
        print("A line in the file was not a whole number")
    return scores

Blok try berisi kode yang bisa gagal (open dan konversi); setiap except menamai satu pengecualian dan melakukan sesuatu yang berguna; fungsi tetap mengembalikan list, sehingga pemanggil terus berlanjut. Di Java bentuk yang sama adalah try { … } catch (FileNotFoundException e) { … } catch (NumberFormatException e) { … }; di VB.NET Try … Catch ex As FileNotFoundException … End Try. Nilai: pernyataan berisiko di dalam try, nama pengecualian yang benar, pesan untuk setiap, dan program berlanjut afterwards; catch-all except: mendapat nilai crash tapi bukan nilai "pengecualian yang sesuai".

Contoh dikerjakan. File teks anggota memerlukan nomor telepon satu anggotanya diubah. Mengapa program tidak bisa sekadar menimpa baris itu, dan apa polanya? Baris file teks memiliki panjang berbeda, dan file tidak memiliki celah untuk menyerap perbedaan: penggantian yang lebih panjang akan menabrak rekaman berikutnya, dan yang lebih pendek akan meninggalkan sebagian baris lama. Jadi polanya adalah membuka yang asli untuk READ dan file sementara untuk WRITE, baca setiap baris secara bergantian, tulis versi baru untuk baris yang berubah dan baris asli untuk semua yang lain, tutup keduanya, lalu ganti yang asli dengan file sementara. Bentuk yang sama menangani penghapusan (lewatkan baris) dan penyisipan (tulis baris ekstra). Perhatikan bahwa setiap baris ditulis, bukan hanya yang berubah - menulis hanya rekaman baru dan kehilangan sisa file adalah kesalahan klasik.

Explore · ⁨Jelajahi⁩

How exception handling flows · ⁨Bagaimana alur penanganan pengecualian bekerja⁩

Step through what happens when code fails. The exception jumps out of the normal flow to a handler, FINALLY cleans up either way, and the program carries on instead of crashing. · ⁨Ikuti apa yang terjadi ketika kode gagal. Pengecualian melompat keluar dari alur normal menuju handler, FINALLY membersihkan baik-baik, dan program berlanjut alih-alih crash.⁩

Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
English Bahasa Indonesia
exception/ekˈsepʃn/ pengecualian
exception handling/ekˈsepʃn ˈhændlɪŋ/ penanganan pengecualian
raise/reɪz/ meningkatkan
call stack/kɔːl stæk/ call stack
20.2

Definitions the examiner accepts · ⁨Definisi yang diterima oleh penguji⁩

English

A definition question is marked against fixed wording. Learn these exactly, and give one answer only.

Term Definition
programming paradigm a style or way of programming, with its own way of structuring a program
imperative language the program is a sequence of statements that change the program's state; the programmer says how the task is done
declarative language the program states facts and rules and the inference engine works out how to find the answer
class a template defining the attributes and methods of the objects of that type
object (instance) an occurrence of a class, with its own values for the attributes
attribute a data item that belongs to a class
method a procedure or function that belongs to a class and acts on its attributes
encapsulation keeping the attributes and methods together in a class and restricting external access to the data, so that it is changed only through public methods
inheritance a subclass acquires the attributes and methods of its parent class and can add or override them
polymorphism methods with the same name that behave differently for different classes
constructor a method that runs when an object is created and initialises its attributes
containment a class has an object of another class as one of its attributes
fact a statement in a declarative program that is true
rule a conclusion that holds when its conditions are true
serial, sequential, random file records in the order added; records in key order; each record at an address calculated from its key
exception an unexpected error or event during execution that interrupts the normal flow
exception handling detecting an exception when it occurs and running code that deals with it so that the program continues
Bahasa Indonesia

Soal definisi dinilai berdasarkan frasa tetap. Hafalkan ini persis, dan berikan hanya satu jawaban.

Istilah Definisi
paradigma pemrograman gaya atau cara pemrograman, dengan cara sendiri dalam menyusun program
bahasa imperatif program adalah urutan pernyataan yang mengubah status program; programmer mengatakan bagaimana tugas dilakukan
bahasa deklaratif program menyatakan fakta dan aturan dan mesin inferensi bekerja mencari jawaban
kelas template yang mendefinisikan atribut dan metode dari objek tipe tersebut
objek (instansi) kejadian dari sebuah kelas, dengan nilainya sendiri untuk atribut
atribut item data yang milik kelas
method prosedur atau fungsi yang milik kelas dan bertindak pada atributnya
enkapsulasi menjaga atribut dan metode tetap bersama dalam sebuah kelas serta membatasi akses eksternal terhadap data, sehingga data hanya dapat diubah melalui metode publik
pewarisan subclass memperoleh atribut dan metode dari kelas induknya dan dapat menambah atau menimpa mereka
polimorfisme metode dengan nama yang sama namun berperilaku berbeda untuk kelas yang berbeda
konstruktor sebuah metode yang dijalankan ketika objek dibuat dan menginisialisasi atributnya
keterkandungan sebuah kelas memiliki objek dari kelas lain sebagai salah satu atributnya
fakta pernyataan dalam program deklaratif yang bernilai benar
aturan kesimpulan yang berlaku ketika kondisinya benar
file serial, sekuensial, acak rekord dalam urutan penambahan; rekord berdasarkan urutan kunci; setiap rekord pada alamat yang dihitung dari kuncinya
pengecualian kesalahan atau peristiwa tidak terduga selama eksekusi yang mengganggu alur normal
penanganan pengecualian mendeteksi pengecualian saat terjadi dan menjalankan kode yang menanganinya agar program terus berjalan
20.2

Exam tips · ⁨Tips ujian⁩

English
  • Paradigms: know the one-line description of each and be ready to name the paradigm from a code sample; low-level questions want the five addressing modes and what the accumulator receives.
  • OOP definitions come up every session: class, object, attribute, method, encapsulation, inheritance, polymorphism, constructor. Write a class in pseudocode with PRIVATE attributes, a PUBLIC NEW and getters; a subclass with INHERITS and SUPER.NEW.
  • Declarative: a goal with a variable returns every matching fact; a rule is a conclusion IF conditions joined with AND; copy the question's predicate names exactly.
  • Files: the three modes and what each does to an existing file; READFILE in a WHILE NOT EOF loop; random files use a hash, SEEK, GETRECORD and PUTRECORD, with a step-on for collisions.
  • Exceptions: definition with an example, three reasons for handling them, and TRY with a named EXCEPT that lets the program continue.

Common mistakes

  • Describing a declarative program as "a sequence of steps that gives the answer"; it states what is true and what is wanted, not how.
  • Confusing an object with a class, or an instance with an attribute; the question "an occurrence of an object" wants instance.
  • Declaring the attributes PUBLIC, or reaching them from outside the class instead of through a getter, which loses the encapsulation marks.
  • A subclass constructor that sets the parent's attributes directly instead of calling SUPER.NEW.
  • Explaining polymorphism as "many objects"; it is the same method name behaving differently for different classes.
  • Opening a file FOR WRITE to add a record, which destroys the existing contents; use APPEND.
  • Reading a random file from the start; SEEK to the hashed address first.
  • Putting the exception handler around code that cannot fail, or catching everything with no message, or describing exception handling as "checking the input with IF".
Bahasa Indonesia
  • Paradigma: pahami deskripsi satu baris untuk masing-masing dan siap menyebutkan paradigma dari contoh kode; pertanyaan tingkat rendah meminta lima mode pengalamatan dan apa yang diterima akumulator.
  • Definisi OOP muncul di setiap sesi: kelas, objek, atribut, metode, enkapsulasi, pewarisan, polimorfisme, konstruktor. Tulislah sebuah kelas dalam pseudocode dengan atribut PRIVAT, NEW PUBLIK, dan getter; sebuah subclass dengan INHERITS dan SUPER.NEW.
  • Deklaratif: tujuan dengan variabel akan mengembalikan semua fakta yang cocok; sebuah aturan adalah kesimpulan JIKA kondisi digabungkan dengan DAN; salin nama predikat pertanyaan secara tepat.
  • File: tiga mode dan apa yang dilakukan masing-masing terhadap file yang sudah ada; READFILE dalam loop WHILE NOT EOF; file acak menggunakan hash, SEEK, GETRECORD dan PUTRECORD, dengan langkah tumpang tindih untuk tabrakan.
  • Pengecualian: definisi dengan contoh, tiga alasan untuk menanganinya, dan TRY dengan EXCEPT bernama yang memungkinkan program terus berjalan.

Kesalahan umum

  • Mendeskripsikan program deklaratif sebagai "urutan langkah yang memberikan jawaban"; ia menyatakan apa yang benar dan apa yang diinginkan, bukan bagaimana.
  • Membingungkan objek dengan kelas, atau instance dengan atribut; pertanyaan "sebuah kemunculan dari objek" menginginkan instance.
  • Mengumumkan atribut sebagai PUBLIK, atau mengaksesnya dari luar kelas alih-alih melalui getter, yang kehilangan poin enkapsulasi.
  • Konstruktor subclass yang menetapkan atribut induk secara langsung alih-alih memanggil SUPER.NEW.
  • Menjelaskan polimorfisme sebagai "banyak objek"; itu adalah nama metode yang sama yang berperilaku berbeda untuk kelas yang berbeda.
  • Membuka file FOR WRITE untuk menambahkan rekord, yang menghancurkan isi yang sudah ada; gunakan APPEND.
  • Membaca file acak dari awal; SEEK ke alamat terhash terlebih dahulu.
  • Menempatkan handler pengecualian di sekitar kode yang tidak bisa gagal, atau menangkap semuanya tanpa pesan, atau mendeskripsikan penanganan pengecualian sebagai "memeriksa input dengan IF".

Interactive lessons on this topic · ⁨Pelajaran interaktif untuk topik ini⁩

Work through it step by step, with instant-check exercises. · ⁨Kerjakan langkah demi langkah, dengan latihan pengecekan instan.⁩

Past Papers · ⁨Soal-Soil Masa Lalu⁩

More topics in A-Level Computer Science · ⁨Ilmu Komputer A-Level⁩ · ⁨Topik lain dalam A-Level Computer Science · ⁨Ilmu Komputer A-Level⁩⁩

Log in or create account · ⁨Masuk atau buat akun⁩

IGCSE, A-Level & AP