MATSEC AM Computing cheat sheet
MATSEC AM Computing · Keep the key ideas within reach.
Computer Systems and Architecture
Two's complement negation: invert all bits then add 1; an n-bit signed range is -2^(n-1) to 2^(n-1)-1, so 8-bit signed covers -128 to 127.
Boolean identities: De Morgan's laws give NOT(A AND B) = NOT A OR NOT B and NOT(A OR B) = NOT A AND NOT B; XOR outputs 1 only when inputs differ.
Half adder: Sum = A XOR B, Carry = A AND B; a full adder adds a third carry-in bit, so n full adders ripple-carry an n-bit addition.
Von Neumann cycle: fetch (PC to MAR, memory to MDR, MDR to CIR), decode, execute, then increment PC; the stored-program concept shares one memory for code and data.
Amdahl's law: speedup = 1 / ((1 - f) + f/s), where f is the fraction parallelised and s the improvement factor; the serial fraction caps the gain.
Memory hierarchy by cost and speed: registers, cache (L1/L2/L3), RAM, SSD/HDD, tape; locality of reference makes caching effective (temporal and spatial locality).
Cache mapping: direct mapping uses block mod number-of-lines, fully associative allows any line, set-associative maps to a set and searches ways within it.
Interrupt handling saves the program counter and register state, runs an interrupt service routine, then restores state; DMA lets devices transfer to memory without per-byte CPU involvement.
Pipeline speedup approaches the number of stages only when there are no hazards; data hazards need forwarding or stalls, control hazards need branch prediction or flushing.
Programming and Software Development
Pass by value copies the argument; pass by reference passes the address, so callee changes to the parameter are visible to the caller.
A stack frame holds parameters, local variables and the return address; recursion depth is limited by stack size, and every recursive case needs a base case to terminate.
Scope rules: a local variable shadows a global of the same name; static/class variables persist for the program lifetime, automatic locals die on block exit.
Big-O classes in ascending growth: O(1) < O(log n) < O(n) < O(n log n) < O(n^2) < O(2^n) < O(n!).
Loop invariant proof: show initialisation (true before the first iteration), maintenance (true after each iteration) and termination (gives the required postcondition).
Compilation stages: lexical analysis (tokens), syntax analysis (parse tree), semantic analysis (types), code generation and optimisation; interpretation executes without a separate code-generation step.
Test design: black-box uses equivalence partitioning and boundary values; white-box uses statement and branch coverage, where branch coverage implies statement coverage but not vice versa.
Object-oriented pillars: encapsulation hides state behind methods, inheritance reuses a superclass, polymorphism dispatches by runtime type, abstraction exposes only the essential interface.
Version control: a commit records a snapshot with a parent pointer; a branch is a movable pointer to a commit; a merge combines divergent histories and may raise conflicts.
Data, Databases and Algorithms
Relational keys: a candidate key is a minimal superkey; the primary key is the chosen candidate key and must be unique and not null; a foreign key references a primary key in another relation.
Normalisation: 1NF removes repeating groups, 2NF removes partial dependencies on part of a composite key, 3NF removes transitive dependencies on non-key attributes.
SQL clause evaluation order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY; WHERE filters rows before grouping, HAVING filters groups after aggregation.
Join semantics: INNER JOIN keeps matching rows only, LEFT JOIN keeps all left rows with nulls for non-matches, and a cross join yields the Cartesian product.
ACID: atomicity (all or nothing), consistency (constraints preserved), isolation (concurrent transactions do not interfere), durability (committed changes survive failure).
Binary search needs a sorted array and runs in O(log n); linear search is O(n); merge sort is O(n log n) in all cases but needs O(n) extra space.
Hash tables give average O(1) lookup but degrade to O(n) on heavy collisions; open addressing probes other slots, chaining stores colliding entries in a list.
Graph traversal: BFS uses a queue and finds shortest paths in unweighted graphs; DFS uses a stack or recursion and detects cycles; Dijkstra requires non-negative edge weights.
Sorting properties: quicksort averages O(n log n) but worst case O(n^2); insertion sort is O(n) on nearly sorted data; a stable sort preserves equal-key order.
Networks
TCP/IP layers: application, transport, internet, link; TCP is connection-oriented and reliable with sequencing and acknowledgements, UDP is connectionless with no delivery guarantee.
Three-way handshake: SYN, SYN-ACK, ACK; connection teardown uses FIN/ACK in each direction; sequence numbers detect loss and reordering.
IPv4 addresses are 32 bits, IPv6 are 128 bits; a /24 prefix leaves 8 host bits, so 2^8 - 2 = 254 usable hosts after removing network and broadcast addresses.
Private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16; NAT translates these to a public address at the router boundary.
DNS resolves names to addresses via recursive queries to a resolver and authoritative servers; records include A (IPv4), AAAA (IPv6), MX (mail) and CNAME (alias).
CSMA/CD detects collisions on shared Ethernet and backs off; switched Ethernet with full duplex removes collisions, and ARP maps IP addresses to MAC addresses on a LAN.
Routing: distance-vector protocols advertise whole routing tables to neighbours (RIP, hop count), link-state protocols flood topology and run Dijkstra (OSPF).
Ports identify services: HTTP 80, HTTPS 443, DNS 53, SMTP 25, SSH 22; a socket is the pair (IP address, port).
Bandwidth-delay product equals link capacity times round-trip time and bounds the data in flight for full throughput; latency, not bandwidth, dominates many interactive transfers.
Security and Social/Ethical Issues
CIA triad: confidentiality (encryption, access control), integrity (hashing, checksums, signatures), availability (redundancy, backups, DDoS defences).
Symmetric encryption (AES) uses one shared key and is fast; asymmetric encryption (RSA) uses a public/private pair and is slow, so it typically distributes a symmetric session key.
Hashing (SHA-256) is one-way and collision-resistant; salts defeat rainbow tables, and HMAC authenticates a message with a shared secret.
Digital signature: sign a hash with the sender's private key; the receiver verifies with the public key, giving authenticity, integrity and non-repudiation.
SQL injection is mitigated by parameterised queries or prepared statements, not by string escaping alone; XSS is mitigated by output encoding and input validation.
Malware classes: virus attaches to a host file, worm self-propagates over networks, trojan disguises as legitimate software, ransomware encrypts data for extortion.
Social engineering exploits people (phishing, pretexting); defence combines user training, multi-factor authentication and verification of unusual requests.
Data protection principles: lawfulness, purpose limitation, data minimisation, accuracy, storage limitation, integrity and confidentiality, accountability.
Ethical frameworks for computing: utilitarian (greatest overall benefit), deontological (duties and rights), and virtue ethics (character of the actor); professional codes stress public interest and competence.
Computer Systems and Architecture (extended)
Hexadecimal to binary: each hex digit maps to four bits, so 0x2F = 0010 1111 = 47 decimal.
Signed overflow in two's complement occurs when two operands of the same sign produce a result of the opposite sign.
Flip-flop versus latch: a latch is level-triggered, a flip-flop is edge-triggered and used in registers and counters.
Bus width determines addressable memory: n address lines address 2^n locations.
RISC versus CISC: RISC uses fixed-length instructions and many registers; CISC uses variable-length instructions and complex addressing.
Little-endian stores the least significant byte at the lowest address; big-endian stores the most significant byte first.
Clock speed, cycles per instruction and instruction count determine execution time: time = count x CPI / clock rate.
Virtual memory maps pages to frames via a page table; a TLB miss costs an extra memory access, and a page fault triggers disk I/O.
Programming and Software Development (extended)
Short-circuit evaluation: in A AND B, B is not evaluated if A is false; in A OR B, B is not evaluated if A is true.
Integer division truncates toward zero in many languages; the modulo result takes the sign of the dividend in C-family languages.
A pointer holds an address; dereferencing reads the value stored there, and a dangling pointer refers to freed memory.
Garbage collection reclaims unreachable heap objects automatically; reference counting frees an object when its count reaches zero but cannot reclaim cycles alone.
Exception handling separates error paths: try runs code, catch handles a matching exception, finally always executes for cleanup.
Functional constructs: map transforms each element, filter selects elements by predicate, reduce folds a list into a single value.
Agile versus waterfall: waterfall fixes requirements up front with sequential phases; agile iterates in short sprints with continuous feedback.
Coupling and cohesion: low coupling and high cohesion indicate good modular design, making modules easier to test and replace.
Data, Databases and Algorithms (extended)
Entity-relationship modelling: a one-to-many relationship becomes a foreign key on the many side; many-to-many requires a junction table.
A view is a stored query presenting a virtual table; an index speeds lookups on a column but adds cost to inserts and updates.
Transaction isolation levels trade consistency for concurrency; a dirty read sees uncommitted data, a phantom read sees new rows in a repeated query.
SQL aggregates: COUNT counts rows, SUM and AVG ignore nulls, and GROUP BY partitions rows before aggregation.
Stack versus queue: a stack is LIFO with push and pop; a queue is FIFO with enqueue and dequeue.
Linked list versus array: insertion at a known node is O(1) in a list but O(n) in an array due to shifting; arrays allow O(1) random access.
Tree terminology: a binary search tree keeps left keys smaller and right keys larger; in-order traversal yields sorted output; balanced trees keep height O(log n).
Algorithm design paradigms: greedy makes locally optimal choices, divide-and-conquer splits and combines, dynamic programming caches overlapping subproblems.
Data types in SQL: INTEGER for whole numbers, DECIMAL for exact money values, VARCHAR for variable text, DATE for calendar dates; FLOAT is unsuitable for currency.
Networks (extended)
OSI seven layers: physical, data link, network, transport, session, presentation, application; TCP/IP collapses the top three into application.
Subnetting: a /26 mask (255.255.255.192) splits a /24 into four subnets of 64 addresses each, giving 62 usable hosts per subnet.
TCP flow control uses a sliding receive window; congestion control uses slow start, congestion avoidance and multiplicative decrease on loss.
DHCP assigns addresses dynamically via DISCOVER, OFFER, REQUEST, ACK; a lease expires and must be renewed.
Switches forward frames by MAC address within a LAN; routers forward packets by IP address between networks; a gateway is the exit point of a subnet.
Wireless security: WEP is broken, WPA2 uses AES-CCMP, WPA3 adds simultaneous authentication of equals to resist offline dictionary attacks.
NAT and PAT: PAT maps many private hosts to one public IP using distinct source ports.
TLS handshake negotiates cipher suites, authenticates the server with a certificate and derives a shared session key for symmetric encryption.
Security and Social/Ethical Issues (extended)
Authentication factors: something you know (password), something you have (token), something you are (biometric); MFA combines different categories.
Access control models: DAC lets owners set permissions, MAC uses labels and clearances, RBAC grants rights by role.
Firewall types: packet-filtering inspects headers, stateful tracks connections, application-layer proxies inspect payloads.
A man-in-the-middle attack intercepts traffic; TLS with certificate validation and HSTS mitigates it on untrusted networks.
Password storage uses a slow salted hash (bcrypt, Argon2); storing plaintext or fast unsalted hashes is unsafe.
Denial of service floods a service with traffic; volumetric attacks saturate bandwidth, application-layer attacks exhaust server resources.
Intellectual property: copyright protects source code automatically, patents protect novel technical methods, and open-source licences set reuse conditions.
Digital divide and automation raise equity questions: access to connectivity and retraining for displaced workers are common ethical arguments.
Privacy by design: collect only necessary data, anonymise where possible, obtain informed consent, and allow data subjects access and erasure.
Computer Systems and Architecture (recap)
Logic gates: AND outputs 1 only if both inputs are 1; OR outputs 1 if either is 1; NOT inverts; NAND and NOR are universal gates.
Karnaugh maps simplify Boolean expressions by grouping adjacent 1s in powers of two, including wrap-around groups.
Memory units: 1 KiB = 1024 bytes, 1 MiB = 1024 KiB, 1 GiB = 1024 MiB; a byte is 8 bits.
Instruction cycle timing: fetch and execute phases alternate; a clock cycle is the smallest unit of processor timing.
RAID levels: RAID 0 stripes for speed without redundancy, RAID 1 mirrors, RAID 5 stripes with distributed parity tolerating one disk failure.
Secondary storage comparison: SSDs have no moving parts and low latency; HDDs offer cheaper capacity per byte.
Operating system roles: process scheduling, memory management, file systems and device drivers; a context switch saves and restores process state.
Fetch-decode-execute with pipelining overlaps stages; superscalar execution issues multiple instructions per cycle.
Programming and Software Development (recap)
Variable declaration versus assignment: declaration reserves a name and type, assignment stores a value into that storage.
Operator precedence: arithmetic before comparison, comparison before logical AND, logical AND before logical OR; parentheses override.
A while loop tests before each iteration and may run zero times; a do-while runs the body at least once.
Array indexing is zero-based in most languages; an out-of-bounds access is undefined behaviour in C and throws an exception in Java and Python.
Function signature: name, parameter types and return type; overloading allows the same name with different parameter lists.
Debugging strategies: breakpoints pause execution, step-over runs a call without entering it, step-into enters the callee.
UML class diagram: a class box lists attributes and methods; a filled diamond denotes composition, an open diamond aggregation, a hollow triangle inheritance.
Code quality: meaningful names, small functions, no duplicated logic, and comments explaining why rather than what.
Data, Databases and Algorithms (recap)
Primary key versus unique constraint: both enforce uniqueness, but a primary key also forbids nulls and is the main identifier.
DELETE removes rows and can be rolled back in a transaction; TRUNCATE empties a table quickly and usually cannot be rolled back.
SQL injection in queries is prevented by bound parameters, keeping data separate from SQL text.
Set operations: UNION removes duplicates, UNION ALL keeps them, INTERSECT returns common rows, EXCEPT returns rows in the first set only.
Complexity of common operations: array access O(1), linked-list search O(n), balanced-tree search O(log n), hash lookup O(1) average.
Recursion versus iteration: recursion uses the call stack and can overflow; iteration uses a loop variable and constant stack space.
Graph representation: an adjacency matrix uses O(V^2) space and O(1) edge lookup; an adjacency list uses O(V+E) space.
Binary tree height: a balanced tree of n nodes has height about log2(n); a degenerate tree has height n-1.
Sorting stability matters when sorting by multiple keys in sequence, such as surname then first name.
Networks (recap)
OSI encapsulation: each layer adds a header, so a message becomes segment, packet, frame and bits as it descends the stack.
IPv4 header fields include source and destination address, TTL and protocol; TTL decrements at each router and prevents infinite loops.
Classful versus CIDR: CIDR uses variable-length prefixes such as /27 to allocate address blocks efficiently.
TCP versus UDP use cases: TCP for file transfer and web pages, UDP for live streaming, DNS queries and online gaming.
A MAC address is 48 bits written as six hex pairs; the first three bytes identify the vendor.
DNS caching reduces lookup time; the TTL field controls how long a record may be cached.
Network topologies: star uses a central switch, mesh offers redundant paths, bus shares one backbone and suffers collisions.
Cloud service models: IaaS supplies virtual machines, PaaS supplies a runtime platform, SaaS supplies a finished application.
Security and Social/Ethical Issues (recap)
Threat versus vulnerability versus risk: a threat is a potential cause, a vulnerability is a weakness, and risk combines likelihood and impact.
Encryption at rest protects stored data; encryption in transit (TLS) protects data on the wire.
Phishing indicators: mismatched sender domain, urgency, unexpected attachments, and links whose visible text differs from the target URL.
Backup strategy 3-2-1: three copies, two different media, one stored off-site; test restores, not just backups.
Software licensing: proprietary licences restrict copying and modification, freeware is free of charge, open source grants access to source code.
Professional responsibility: report security flaws responsibly, avoid conflicts of interest, and respect user confidentiality.
Environmental impact: data centres consume energy for power and cooling; efficiency measures include virtualisation and renewable sourcing.
Legislation commonly examined: data protection law governs personal data processing, computer misuse law criminalises unauthorised access.
Computer Systems and Architecture (final)
Two's complement subtraction: A - B is computed as A + (NOT B) + 1 using the same adder hardware.
Parity versus checksum versus CRC: parity detects single-bit errors, checksums sum words, CRC uses polynomial division for stronger detection.
CPU components: ALU performs arithmetic and logic, control unit decodes and sequences, registers hold operands, cache reduces memory latency.
Addressing modes: immediate embeds the operand, direct names a memory address, indirect names a location holding the address, indexed adds an offset.
Machine cycle versus instruction cycle: the machine cycle covers fetch, indirect, execute and interrupt phases for one instruction.
Memory interleaving spreads consecutive addresses across banks so accesses proceed in parallel and effective bandwidth rises.
Embedded systems trade generality for constraints: fixed function, limited memory, real-time deadlines and low power.
Compiler versus interpreter versus assembler: a compiler translates a high-level language to machine code, an interpreter executes source directly, an assembler translates assembly to machine code.
Programming and Software Development (final)
Type systems: static typing checks types at compile time, dynamic typing at runtime; strong typing forbids implicit incompatible conversions.
Immutable values cannot change after creation, which simplifies reasoning and makes concurrent sharing safer.
A pure function returns the same output for the same input and has no side effects, so it is easy to test and cache.
Interface versus abstract class: an interface declares a contract without state, an abstract class may hold state and partial implementation.
Error versus exception: an error is a serious unrecoverable condition, an exception is a condition a program can catch and handle.
Design patterns: singleton ensures one instance, observer notifies dependents of changes, factory defers object creation to subclasses.
Refactoring changes internal structure without changing external behaviour; unit tests provide the safety net for it.
Documentation standards: docstrings describe parameters, return values and raised exceptions so tools can generate reference manuals.
Data, Databases and Algorithms (final)
Functional dependency X to Y means each X value determines exactly one Y value; a partial dependency uses only part of a composite key.
Referential integrity requires every foreign key value to match an existing primary key value or be null.
A candidate key with multiple attributes is composite; choosing one candidate as primary key leaves the others as alternate keys.
Aggregate versus window function: an aggregate collapses rows, a window function keeps row count and computes across a partition.
Stored procedure versus trigger: a procedure is called explicitly, a trigger fires automatically on insert, update or delete.
Heap versus sorted array versus hash: a heap gives O(1) minimum and O(log n) insert, a sorted array gives O(1) search but O(n) insert.
Dynamic programming requires optimal substructure and overlapping subproblems; memoisation stores results of recursive calls.
Algorithm correctness: a loop variant decreases toward a bound to prove termination, while the invariant proves the result.
Big-O versus Big-Theta: Big-O is an upper bound, Big-Omega a lower bound, Big-Theta a tight bound.
Networks (final)
Circuit versus packet switching: circuit reserves a path for the session, packet switching shares links and queues packets at routers.
Latency components: propagation delay depends on distance, transmission delay on packet size and link rate, queuing delay on congestion.
Error detection at the link layer uses CRC in the frame trailer; reliable delivery is handled by TCP at the transport layer.
HTTP is stateless, so cookies carry session state; HTTPS adds TLS between the client and server.
Email protocols: SMTP sends mail, IMAP and POP3 retrieve it; IMAP keeps messages on the server and synchronises folders.
VPN tunnelling encrypts traffic between client and gateway, giving confidentiality over public networks.
Quality of service prioritises latency-sensitive traffic such as voice over bulk downloads by classifying and scheduling packets.
IPv6 removes NAT dependence, supports stateless address autoconfiguration and uses a 128-bit address space.
Security and Social/Ethical Issues (final)
Symmetric key distribution problem: n users need n(n-1)/2 distinct pairwise keys, which asymmetric key exchange avoids.
Certificate authority signs a server certificate binding a public key to a domain; the client trusts the CA's root certificate.
Zero-day exploit targets an unknown vulnerability; patching reduces exposure but cannot pre-empt unknown flaws.
Defence in depth layers controls so a single failure does not compromise the system; least privilege limits each account's rights.
Audit logs record who did what and when, supporting accountability and forensic investigation.
Acceptable use policies define permitted system use; monitoring must be disclosed to respect employee privacy expectations.
Algorithmic bias arises when training data underrepresents groups; mitigation includes diverse data and fairness testing.
Whistleblowing is justified in professional codes when the public interest outweighs organisational confidentiality, after internal channels fail.
Computer Systems and Architecture (supplement)
Number base conversion: repeatedly divide by the target base and read remainders in reverse to convert decimal to another base.
Signed magnitude versus two's complement: signed magnitude has two zeros (+0 and -0), two's complement has a single zero and simpler arithmetic.
A multiplexer selects one of several inputs by select lines; a decoder activates one output line for each input combination.
Sequential versus combinational circuits: sequential circuits have memory (state) and a clock, combinational circuits depend only on current inputs.
RAM versus ROM: RAM is volatile and writable, ROM is non-volatile and typically read-only, holding firmware such as the boot loader.
Cache hit ratio equals hits divided by total accesses; effective access time = hit ratio x cache time + miss ratio x memory time.
Interrupt priority determines which pending interrupt the CPU services first; a higher-priority interrupt may preempt a lower one.
Floating-point representation stores sign, exponent and mantissa; it trades exactness for range, so 0.1 cannot be stored exactly in binary.
Programming and Software Development (supplement)
Variable lifetime versus scope: lifetime is how long storage exists, scope is where the name is visible; they are related but distinct.
Copy versus reference semantics: assigning an object reference copies the address, so both names point to the same object.
A null reference causes a runtime error when dereferenced; defensive checks or optional types reduce the risk.
String immutability means concatenation in a loop creates many objects; a builder or buffer avoids the repeated copying.
Recursion tree analysis: total work equals the sum over levels, which yields the recurrence solution such as O(n log n) for merge sort.
Testing pyramid: many unit tests, fewer integration tests, fewest end-to-end tests, because higher levels are slower and more brittle.
Continuous integration runs automated builds and tests on each commit, catching integration defects early.
Software estimation: function points and story points estimate effort from functionality rather than lines of code.
Data, Databases and Algorithms (supplement)
SQL join versus subquery: a join combines columns from tables, a subquery returns a value or set used in a condition.
NULL semantics: comparisons with NULL yield unknown, so use IS NULL or IS NOT NULL rather than equality.
A self-join joins a table to itself, useful for hierarchies such as employee to manager.
Index selectivity is high when a column has many distinct values; indexing low-selectivity columns rarely helps.
Denormalisation duplicates data to avoid joins and speed reads, at the cost of update anomalies.
Hash collision resolution by chaining keeps a list per bucket; load factor equals entries divided by buckets.
Breadth-first search finds the shortest path in an unweighted graph; Dijkstra generalises it to non-negative weighted edges using a priority queue.
Topological sort orders tasks with dependencies and is possible only on a directed acyclic graph.
Space complexity counts auxiliary memory beyond the input; in-place algorithms use O(1) extra space.
Networks (supplement)
A collision domain is a segment where frames can collide; a broadcast domain is the set of hosts reached by one broadcast, bounded by routers.
VLANs logically segment a switch, reducing broadcast domains without extra hardware.
Spanning Tree Protocol disables redundant switch links to prevent broadcast loops while keeping a backup path.
Static versus dynamic routing: static routes are configured manually and do not adapt; dynamic protocols react to topology changes.
A proxy server forwards client requests, offering caching and filtering; a reverse proxy fronts servers for load balancing and TLS termination.
Wireless channels overlap; non-overlapping 2.4 GHz channels are 1, 6 and 11 in common regulatory domains.
Packet capture tools read frames in promiscuous mode for diagnosis; this requires authorisation to respect privacy and law.
Bandwidth versus throughput: bandwidth is the link capacity, throughput is the actual achieved rate after overhead and loss.
Security and Social/Ethical Issues (supplement)
Symmetric block cipher modes: ECB encrypts identical blocks identically and leaks patterns; CBC chains blocks with an IV; GCM adds authentication.
Key length guidance: AES-128 and AES-256 are both considered secure; RSA keys of 2048 bits or more are standard today.
Hash versus encryption: a hash cannot be reversed, encryption can be decrypted with the key, so passwords are hashed, not encrypted.
Cross-site request forgery tricks a logged-in browser into sending a request; anti-CSRF tokens and SameSite cookies mitigate it.
Buffer overflow writes beyond allocated memory; bounds checking and safe libraries prevent it.
Social media ethics: informed consent for data use, transparency of algorithms, and protection of minors are recurring exam themes.
Digital signatures provide non-repudiation; symmetric MACs provide integrity and authenticity between parties sharing a key but not non-repudiation.
Incident response stages: preparation, identification, containment, eradication, recovery and lessons learned.
Computer Systems and Architecture (breadth)
Clock cycle time is the reciprocal of clock frequency; a 2 GHz clock has a 0.5 ns cycle.
A register is the fastest storage inside the CPU; the program counter holds the address of the next instruction.
The instruction register holds the instruction currently being decoded; the memory address register holds the address being accessed.
CISC instructions may take several cycles; RISC aims for one instruction per cycle with pipelining.
Memory-mapped I/O assigns device registers addresses in the same address space as memory, so ordinary load/store instructions access devices.
Polling versus interrupts: polling repeatedly checks a device and wastes CPU time; interrupts signal the CPU only when service is needed.
Solid-state storage wears out after limited write cycles; wear levelling spreads writes across blocks to extend life.
A bus carries address, data and control signals; wider data buses transfer more bits per cycle.
Programming and Software Development (breadth)
Iteration versus recursion trade-off: recursion is clearer for tree structures but costs stack frames; iteration is usually faster and uses constant space.
A sentinel value marks the end of data, such as a null terminator in C strings or a -1 returned by a search.
Input validation checks type, range and format before use; it prevents crashes and injection attacks.
Defensive programming assumes callers may pass invalid data and checks preconditions at function entry.
A stack trace lists the call chain at the point an exception was raised, which locates the fault.
Version control branching strategies: feature branches isolate work, and pull requests review changes before merging to main.
Pair programming and code review catch defects early; review is cheaper than fixing faults after release.
Technical debt is deferred design work that slows future change; it should be tracked and repaid deliberately.
Data, Databases and Algorithms (breadth)
A database schema defines tables, columns, types and constraints; the instance is the data currently stored.
The three-schema architecture separates external views, the conceptual schema and the physical schema.
A relation is a set of tuples, so duplicate rows are not allowed in the pure relational model; SQL tables are bags unless constrained.
SQL ORDER BY sorts ascending by default; DESC reverses it, and multiple keys sort lexicographically.
An aggregate query without GROUP BY returns one row summarising the whole table.
A foreign key with ON DELETE CASCADE removes dependent rows automatically; RESTRICT blocks the delete instead.
Quicksort partition places a pivot so smaller elements are left and larger right, then recurses on both sides.
A priority queue supports extract-min in O(log n) and is the core of Dijkstra and Huffman coding.
Amortised analysis averages cost over a sequence of operations, as with dynamic array resizing giving O(1) amortised append.
Networks (breadth)
The physical layer defines voltages, connectors and signalling; the data link layer frames bits and handles MAC addressing.
Ethernet frames carry source and destination MAC addresses and a type field indicating the encapsulated protocol.
IP is best-effort: it does not guarantee delivery, ordering or duplicate suppression, which TCP adds.
A default gateway is used when the destination is outside the local subnet, determined by comparing the prefix.
Ping uses ICMP echo request and reply to test reachability; traceroute varies TTL to reveal each hop.
Port forwarding on a router maps an external port to an internal host and port, exposing a service.
A demilitarised zone hosts public-facing servers between two firewalls, separating them from the internal network.
Content delivery networks cache content at edge locations, reducing latency and origin load.
Security and Social/Ethical Issues (breadth)
Confidentiality versus integrity: encryption hides content, hashing detects modification; both are often needed.
A salt is unique per password and stored with the hash; a pepper is a secret value kept outside the database.
Certificate pinning restricts which certificates a client accepts, reducing man-in-the-middle risk.
Security patching closes known vulnerabilities; unsupported software receives no fixes and becomes a liability.
Phishing versus pharming: phishing lures users with fake messages, pharming redirects users via DNS or hosts manipulation.
Data minimisation reduces breach impact because data not collected cannot be leaked.
Open data raises privacy questions when anonymised datasets can be re-identified by combining sources.
Professional codes require competence: do not accept work beyond your skills without supervision or training.
Computer Systems and Architecture (review)
A logic circuit's truth table lists every input combination and the corresponding output, with 2^n rows for n inputs.
Boolean absorption laws: A OR (A AND B) = A and A AND (A OR B) = A.
Two's complement range for n bits is asymmetric: one more negative value than positive because zero occupies a positive code.
A shift left by one multiplies an unsigned binary number by two; a logical shift right divides by two, discarding the remainder.
The fetch phase reads the instruction at the address in the program counter and increments the program counter.
DRAM needs periodic refresh because capacitors leak charge; SRAM holds state in flip-flops and needs no refresh.
A page table maps virtual page numbers to physical frame numbers; the page offset is unchanged by translation.
Multicore processors run threads in parallel but require synchronisation to avoid race conditions on shared data.
Programming and Software Development (review)
A parameter is the declared variable in a function; an argument is the value supplied at the call site.
Return values versus output parameters: a return value is the normal result, output parameters modify caller-supplied storage.
Short function design: one responsibility per function makes it easier to name, test and reuse.
A loop counter must be updated inside the loop body or the loop may never terminate.
String comparison uses equality of content, not of references, in languages where strings are objects.
Compilation errors prevent execution; runtime errors occur during execution; logic errors produce wrong results without any error message.
Version control commit messages should state why a change was made, since the diff already shows what changed.
A build script automates compiling, testing and packaging so results are reproducible across machines.
Data, Databases and Algorithms (review)
SQL SELECT DISTINCT removes duplicate result rows; without it duplicates are retained.
The WHERE clause cannot use aggregate functions; use HAVING for conditions on aggregated results.
A transaction groups statements so they commit together or roll back together; SAVEPOINT allows partial rollback.
Optimistic versus pessimistic concurrency: optimistic checks a version at commit, pessimistic locks rows in advance.
A composite index is usable when the query filters on a leftmost prefix of its columns.
A full table scan may be faster than an index lookup when a query returns a large fraction of rows.
A linked list supports O(1) insertion at a known node but O(n) search; an array supports O(1) access but O(n) insertion.
A hash function maps keys to bucket indices; a good hash distributes keys uniformly to limit collisions.
Memoisation trades space for time by caching results; it only helps when subproblems repeat.
Networks (review)
The transport layer provides end-to-end delivery between processes; the network layer provides host-to-host delivery between networks.
TCP segments carry sequence and acknowledgement numbers; a lost segment is retransmitted after a timeout or duplicate ACKs.
UDP has an 8-byte header with source port, destination port, length and checksum; it has no sequence numbers.
IPv4 fragmentation splits packets larger than the link MTU; path MTU discovery avoids it.
A subnet mask of 255.255.255.0 corresponds to prefix /24, leaving 8 host bits.
DNS record types: NS names authoritative servers, PTR maps an address to a name for reverse lookup.
Wireless access points bridge wireless clients to a wired LAN; a wireless controller coordinates many access points.
Network address translation hides internal addresses but complicates inbound connections, which need port forwarding.
Security and Social/Ethical Issues (review)
Authentication proves identity; authorisation decides what an authenticated identity may do.
Brute-force resistance comes from rate limiting, account lockout and strong password policies.
Encryption does not prevent deletion or tampering by an authorised insider; access control and auditing address that.
A digital certificate binds an identity to a public key and is valid only within its validity dates and for its named domain.
Security awareness training reduces phishing success more than technical filters alone, though both are used together.
Data breaches must often be disclosed to regulators and affected users within a set period under data protection law.
Accessibility is an ethical and often legal requirement: interfaces should support keyboard navigation, contrast and screen readers.
Sustainability in computing includes extending device lifetimes and responsible e-waste recycling.
Computer Systems and Architecture (consolidation)
A truth table with three inputs has eight rows; each row corresponds to one minterm in sum-of-products form.
A half adder cannot accept a carry-in; chaining full adders provides carry propagation across bit positions.
The status register holds flags such as zero, carry, negative and overflow produced by the ALU.
Immediate addressing embeds the operand in the instruction, so no extra memory access is needed to fetch it.
A cache miss on a modified line may require a write-back before the line is replaced.
A TLB caches recent page-table entries to avoid an extra memory access on every address translation.
DMA transfers raise an interrupt on completion rather than interrupting per byte, freeing the CPU.
Real-time systems must meet deadlines; a missed deadline is a failure even if the result is eventually correct.
Programming and Software Development (consolidation)
A variable's type determines its allowed operations and storage size; a cast converts between types and may lose information.
Integer overflow wraps or is undefined depending on the language; check bounds before arithmetic on untrusted input.
Recursive functions need a base case and progress toward it; otherwise the stack overflows.
A closure captures variables from its enclosing scope, so the captured value persists after the outer function returns.
Polymorphism allows a superclass reference to call subclass behaviour resolved at runtime by dynamic dispatch.
Encapsulation is implemented with private fields and public accessor methods that enforce invariants.
A test case specifies inputs, preconditions and expected output; an assertion checks the actual result against it.
Regression tests confirm that previously fixed defects stay fixed after later changes.
Data, Databases and Algorithms (consolidation)
SQL INSERT adds rows, UPDATE modifies existing rows, DELETE removes rows; UPDATE and DELETE should always carry a WHERE clause unless intended for all rows.
A primary key constraint creates an index automatically, which speeds lookups by that key.
A one-to-one relationship is implemented by a foreign key with a unique constraint, or by merging the tables.
Third normal form removes transitive dependencies, so every non-key attribute depends only on the key.
A Cartesian product results from a join without a matching condition and is usually a mistake.
Binary search requires random access and sorted order; on a linked list it is impractical because middle access is O(n).
Insertion sort is stable and in-place with O(n^2) worst case; it performs well on small or nearly sorted arrays.
A balanced binary search tree guarantees O(log n) search, insert and delete; an unbalanced one degrades to O(n).
Greedy algorithms are correct only when the problem has the greedy-choice property and optimal substructure.
Networks (consolidation)
The TCP/IP model's application layer combines OSI session, presentation and application functions.
A three-way handshake establishes initial sequence numbers in both directions before data flows.
TCP congestion window grows during slow start and is halved on detected loss in common implementations.
IPv4 private addresses are not routable on the public internet and require NAT to reach external hosts.
A host determines whether a destination is local by ANDing its address with the subnet mask and comparing prefixes.
DNS resolution order: local cache, then resolver cache, then recursive query to root, TLD and authoritative servers.
Switches learn MAC addresses from source addresses and flood frames with unknown destinations.
Encryption at the application layer (HTTPS) protects payloads end to end even across untrusted intermediate networks.
Security and Social/Ethical Issues (consolidation)
A vulnerability scan identifies known weaknesses; a penetration test attempts controlled exploitation with authorisation.
Least privilege limits damage from compromised accounts by granting only necessary permissions.
Multi-factor authentication resists password theft because a stolen password alone is insufficient.
Encryption key management covers generation, storage, rotation and revocation; losing the key loses the data.
A honeypot is a decoy system that attracts attackers and reveals their techniques.
Software supply chain risk includes compromised dependencies; pinning versions and verifying checksums reduce exposure.
Ethical use of AI includes disclosing automated decision-making and providing human review for consequential outcomes.
Intellectual property in software: copying code without a licence infringes copyright even if the code is modified.
Computer Systems and Architecture (assorted)
A demultiplexer routes one input to one of several outputs selected by control lines.
A ripple-carry adder's delay grows with bit width because each carry depends on the previous stage; carry-lookahead reduces that delay.
A clock signal synchronises sequential circuits; setup and hold times constrain when inputs may change relative to the clock edge.
Firmware such as the BIOS or UEFI initialises hardware and locates the boot loader.
Virtual memory allows programs larger than physical RAM by keeping inactive pages on disk.
Thrashing occurs when excessive paging leaves too little time for useful work; it is mitigated by reducing the multiprogramming level.
A GPU has many simple cores suited to data-parallel work, while a CPU has fewer complex cores for sequential control.
Von Neumann bottleneck: instruction and data share one memory bus, limiting throughput; caches and separate instruction/data caches mitigate it.
Programming and Software Development (assorted)
The DRY principle avoids duplicating knowledge; a single source of truth reduces inconsistent fixes.
KISS and YAGNI favour simple designs and deferring features not yet needed.
An API contract defines inputs, outputs and error behaviour, letting callers depend on it without knowing the implementation.
Semantic versioning uses major.minor.patch; a major increment signals incompatible changes.
A linter detects style and likely-error patterns without executing the program.
A debugger watch expression evaluates a variable as execution pauses at a breakpoint.
A race condition occurs when concurrent access order affects the result; locks or atomic operations prevent it.
Deadlock requires mutual exclusion, hold-and-wait, no preemption and circular wait; breaking any one condition prevents it.
Data, Databases and Algorithms (assorted)
A relational database enforces constraints: primary key, foreign key, unique, not null and check.
A view can restrict visible columns and rows, acting as a simple access-control mechanism.
A stored procedure reduces network round trips by running multiple statements on the server.
Backup types: a full backup copies everything, a differential copies changes since the last full, a log backup captures transaction logs for point-in-time recovery.
A B-tree index keeps data sorted, supporting range queries as well as equality lookups.
A hash index supports equality lookups only and cannot serve range queries efficiently.
Merge sort is stable and predictable at O(n log n) but needs O(n) auxiliary space; quicksort is in-place but has an O(n^2) worst case.
Dijkstra fails with negative edge weights; Bellman-Ford handles them and detects negative cycles.
A minimum spanning tree connects all vertices with minimum total edge weight; Kruskal sorts edges and uses union-find.
Networks (assorted)
The data link layer detects errors with CRC and may request retransmission in protocols such as Wi-Fi.
IPv4 TTL and IPv6 hop limit prevent packets circulating forever; each router decrements the value.
A broadcast address has all host bits set to 1; the network address has all host bits set to 0.
The loopback address 127.0.0.1 refers to the local host and never leaves the machine.
TCP window scaling allows large windows on high-latency links where the default window would cap throughput.
A load balancer distributes requests across servers using round-robin, least-connections or hashing strategies.
A firewall default-deny policy blocks all traffic except explicitly permitted flows.
Cloud elasticity scales resources automatically with demand, while reserved capacity trades flexibility for lower cost.
Security and Social/Ethical Issues (assorted)
Risk assessment multiplies likelihood by impact; controls reduce one or both factors.
A security policy defines acceptable use, password rules, incident reporting and data classification.
Physical security matters: locked server rooms, access logs and disposal of storage media prevent data theft.
Social engineering defences include verifying identity through a separate channel and limiting information published publicly.
Open-source software can be more auditable but shifts patching responsibility to the deployer.
Data anonymisation removes direct identifiers; pseudonymisation replaces them with codes but keeps re-identification possible with the key.
Automation ethics: decisions affecting people should remain explainable and contestable.
Professional misconduct can lead to licence revocation or legal liability, not only employment consequences.
Computer Systems and Architecture (closing)
A full adder's sum is A XOR B XOR carry-in, and its carry-out is majority(A, B, carry-in).
A D flip-flop stores one bit and updates on the clock edge; registers are arrays of flip-flops.
A counter is a sequential circuit that cycles through states, often built from flip-flops and combinational logic.
Memory address space size equals 2 raised to the number of address lines, multiplied by the word size in bytes.
A word is the natural unit of data the CPU processes at once; word size affects addressable range and arithmetic precision.
An instruction set defines opcodes, operand formats and addressing modes available to the programmer.
A system bus may be split into address, data and control buses with separate widths and timings.
Power consumption rises with clock frequency and voltage; dynamic voltage and frequency scaling reduces both when load is low.
Programming and Software Development (closing)
A data structure choice depends on the operations needed: frequent search favours hash tables, ordered traversal favours trees.
A stack supports undo operations and expression evaluation; a queue supports scheduling and breadth-first traversal.
A dictionary or map stores key-value pairs with average O(1) lookup by key.
A set stores unique elements and supports membership tests efficiently.
Exception safety: release acquired resources in a finally block or with a try-with-resources construct.
Input sanitisation and parameterised queries together prevent most injection attacks in application code.
Logging at appropriate levels (debug, info, warning, error) helps diagnose production faults without excessive noise.
Code coverage measures executed lines or branches; high coverage does not guarantee correct behaviour, only that code ran.
Data, Databases and Algorithms (closing)
SQL injection risk is highest where queries concatenate user input; prepared statements bind values separately from SQL text.
A database transaction should be as short as possible to reduce lock contention.
Deadlock in databases occurs when transactions wait on each other's locks; a timeout or wait-for graph detects it.
A clustered index determines physical row order; a non-clustered index stores pointers to rows.
Query execution plans show whether an index is used; a full scan on a large table signals a missing or unusable index.
A self-join can find pairs of rows satisfying a relationship, such as employees sharing a manager.
A recursive query or CTE traverses hierarchies such as organisational charts or category trees.
Algorithm analysis counts dominant operations rather than wall-clock time, because hardware varies.
A greedy algorithm may fail where dynamic programming succeeds, such as coin change with unusual denominations.
Networks (closing)
The maximum transmission unit limits frame payload size; larger packets are fragmented or rejected.
A VLAN tag adds 4 bytes to the Ethernet frame, identifying the VLAN to which the frame belongs.
Link aggregation combines multiple physical links into one logical link for bandwidth and redundancy.
A routing table maps destination prefixes to next hops and interfaces; the longest matching prefix wins.
BGP exchanges routes between autonomous systems on the internet; it is a path-vector protocol.
Network address translation can complicate protocols that embed IP addresses in payloads, requiring application-layer gateways.
A wireless network's SSID identifies it; hiding the SSID is not a security control because it is easily discovered.
Zero-trust networking authenticates and authorises every request regardless of network location.
Security and Social/Ethical Issues (closing)
Threat modelling identifies assets, adversaries and attack paths before code is written.
Secure coding practices include validating input, encoding output, avoiding hard-coded secrets and using vetted libraries.
A secret stored in source code is exposed to anyone with repository access; use a secret manager or environment configuration.
Dependency scanning flags libraries with known vulnerabilities; update or replace them promptly.
Incident disclosure should be timely and accurate; concealing a breach increases harm and often breaches legal duties.
Digital forensics preserves evidence with write blockers and documented chain of custody.
Ethical design considers vulnerable users, such as minors and people with disabilities, and avoids manipulative dark patterns.
Sustainability and social responsibility are increasingly part of professional computing ethics, alongside privacy and fairness.