All Topics
344 flashcardsWhat is the function of the control unit (CU)?
Track your progress — Sign up free to save your progress and get smart review reminders based on spaced repetition.
All cards in this selection
What is the function of the control unit (CU)?
It controls and coordinates the CPU: it fetches and decodes instructions and sends control signals telling the other components what to do and when. It does no calculating itself.
What is the function of the arithmetic logic unit (ALU)?
It performs all arithmetic operations (add, subtract, multiply, divide) and logic operations (AND, OR, NOT, and comparisons) on data.
What does the program counter (PC) hold?
The address of the **next** instruction to be executed. It advances after each instruction is fetched.
What is the difference between the MAR and the MDR?
The MAR holds the **address** being accessed; the MDR holds the **value** travelling to or from memory. Address versus data.
What does the instruction register (IR) hold?
The instruction currently being executed, held there while the CU decodes and carries it out.
What does the accumulator (AC) hold?
The number the ALU is working on — both the value going in and the answer coming out. ADD 5 turns a 12 in the accumulator into 17, in the same register.
Name the three buses and what each carries.
**Address bus** — the memory address (one-way, CPU → memory). **Data bus** — the data or instruction itself (two-way). **Control bus** — the CU's commands and timing signals (two-way).
Why does a multi-core processor not speed up every program?
Only work that can be divided between cores benefits. If each step depends on the previous result, the work cannot be split and extra cores sit idle.
Why does a CPU use registers rather than working directly in RAM?
Registers sit inside the CPU and can be reached almost instantly, whereas RAM is much slower. Holding working values in registers stops the ALU waiting on memory.
What is the role of a GPU?
To perform many simple calculations at the same time. It has thousands of small cores, which suits work made of many identical independent sums — pixels, machine learning, simulations.
How does a GPU's architecture differ from a CPU's?
A CPU has a few powerful cores that handle complicated varied work in order. A GPU has thousands of simple cores that do the same calculation simultaneously.
Give two non-graphics uses of a GPU and say why they fit.
Machine learning (multiplying huge grids of numbers) and large simulations (updating millions of independent points). Both repeat one calculation across many values.
When is a GPU a poor choice?
When the work is a chain of steps that each need the previous answer. Nothing can run in parallel, and GPU cores are individually weaker than CPU cores.
How do the CPU and GPU divide a job between them?
The CPU runs the program, decides what needs doing, sends the repetitive part and its data to the GPU, and collects the result when it is finished. The GPU never chooses its own work.
List primary memory from fastest to slowest.
Registers, then cache (L1, L2, L3), then RAM. Each step holds more and takes longer to reach.
What is the purpose of cache?
To hold recently used data and instructions in a small, very fast store close to the CPU, so most requests avoid the slower trip to RAM.
What is a cache hit and a cache miss?
A hit means the value is already in cache, so no trip to RAM is needed. A miss means it is not, so it is fetched from RAM and copied into cache for next time.
What is the difference between RAM and ROM?
RAM is a large volatile working space holding programs in use; it empties when power is lost. ROM is small, non-volatile and read only, holding the start-up program.
Why is data copied into cache after a miss?
Because programs tend to reuse the same values shortly afterwards, so caching it turns the next request into a hit.
What are the three stages of the fetch-decode-execute cycle?
Fetch the next instruction from memory, decode it in the control unit, then execute it — usually a calculation in the ALU. The cycle then repeats.
Which registers are used during fetch?
The PC holds the address, which is copied to the MAR. Memory returns the instruction into the MDR, and it moves to the IR. The PC is then increased.
When is the program counter increased, and why then?
During fetch. A jump instruction works by writing a new address into the PC during execute — increasing it afterwards would overwrite the jump.
What happens during decode?
The control unit reads the instruction held in the IR, works out which operation is needed, and sends control signals to the parts that will carry it out.
Which buses does a fetch use?
All three: the address bus carries the address out, the control bus carries the read signal, and the data bus brings the instruction back.
What is secondary storage and why is it needed?
Non-volatile storage that keeps data when the power is off. RAM empties at power-off, so anything kept permanently — files, programs, the operating system — lives here.
Compare an SSD with an HDD.
An SSD uses flash memory with no moving parts: faster, quieter, more robust, but dearer per gigabyte. An HDD uses a spinning magnetic disk with a moving head: slower and more fragile, but much cheaper for the capacity.
Name three types of external secondary storage and a use for each.
Portable SSD/HDD for backups and large files; flash drives or memory cards for carrying small amounts; optical discs for distributing identical content cheaply. NAS puts drives on a network for shared access.
What is eMMC?
Flash storage soldered onto the board of phones, tablets and budget laptops. Compact and inexpensive, but slower than an SSD and not replaceable.
How do you decide which storage suits a scenario?
Weigh capacity, speed, portability, cost and how many people need access at once. The right answer follows from the situation, not from which is newest.
What is compression?
Storing the same data in fewer bits. It works because real files repeat themselves, and smaller files need less storage and travel faster over a network.
What is the difference between lossy and lossless compression?
Lossless can rebuild the original exactly — nothing is discarded, only written more briefly. Lossy permanently removes detail people are unlikely to notice, saving far more space but irreversibly.
Explain run-length encoding with an example.
Each run of identical values is replaced by a count and the value. A row of six white pixels is stored as '6 white' — two values instead of six. Expanding it restores every original pixel.
When does run-length encoding make a file bigger?
When neighbouring values rarely repeat, such as a detailed photograph. Most runs are length one, so storing a count beside every value adds data rather than saving it.
Which method suits text, and which suits photographs?
Text, code and spreadsheets need lossless — one altered character can change the meaning. Photographs, music and video use lossy, because small losses go unnoticed and the saving is much greater.
What is cloud computing?
Renting computing from a provider over the internet instead of buying and running the machines yourself. You pay for what you use and the provider keeps the hardware working.
What is the difference between IaaS, PaaS and SaaS?
How far up the stack the provider takes over. IaaS gives you a machine and you install the OS upwards. PaaS runs the OS and runtime, and you supply your program. SaaS is the finished program — you just sign in.
When should an organisation choose IaaS?
When it needs to choose the operating system or its version — for software with unusual requirements — and has technical staff able to configure and maintain the machines.
When should an organisation choose SaaS?
When it needs a finished tool and has no technical staff. The provider handles updates, patching and backups, and the service is usable immediately.
What is the trade-off between control and convenience in cloud services?
Every layer you hand to the provider saves you work and removes a choice. Towards IaaS: more control, more responsibility for patching and setup. Towards SaaS: ready in minutes, but you accept the provider's features and versions and moving away later is hard.
How do you convert a binary number to decimal?
Write the column values above it — 128 64 32 16 8 4 2 1 — and add the columns that have a 1 under them. 10110101 = 128 + 32 + 16 + 4 + 1 = 181.
How do you convert a decimal number to binary?
Take the biggest column value that fits, subtract it, and repeat with what is left. 181: 128 fits (53 left), 32 fits (21), 16 fits (5), 4 fits (1), 1 fits (0) — so 10110101. Add the columns back to check.
Why does one hex digit equal exactly four bits?
Four bits can hold the values 0 to 15, which is exactly the range of a single hex digit (0 to F). So any four bits swap cleanly for one character.
How do you convert binary to hexadecimal?
Group the bits in fours starting from the right, padding the leftmost group with zeros, then turn each group into its digit. 101101 is 0010 1101, which is 2D.
What are the hex digits above 9?
A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. To convert two hex digits to decimal, multiply the left by 16 and add the right: B5 = 11 × 16 + 5 = 181.
Why do the same bits mean different things in different files?
Because the meaning is an agreement held by the program reading them, not a property of the bits. 01000001 is 65 read by place value and A read through a character set.
How is text stored in binary?
Each character is given a number by an agreed character set — 65 for A in ASCII — and that number is stored in binary. A string is those numbers one after another, so CAT is 67, 65, 84.
What is the difference between ASCII and Unicode?
ASCII uses one byte per character and covers English. Unicode assigns numbers to every writing system, using more bytes per character where it needs them.
How is an image stored in binary?
The picture is divided into a grid of pixels, and each pixel's colour is stored as numbers — one byte for greyscale, or three bytes for red, green and blue. More pixels means proportionally more storage.
How are audio and video stored?
Audio: the height of the sound wave measured thousands of times a second, each measurement stored as a number. Video: a complete image 24 to 60 times a second, plus the audio — which is why video files are the largest.
What is a logic gate?
A component that takes one or two bits in and gives one bit out, always the same way for the same inputs. Gates wired together are what a CPU is physically built from.
When does each basic gate output 1?
AND: only when both inputs are 1. OR: when at least one input is 1. NOT: when the single input is 0. XOR: when the two inputs are different.
What does a circle on a gate's output mean?
Invert the output. AND with a circle is NAND, OR with a circle is NOR, XOR with a circle is XNOR — each is the original table with every output flipped.
What is the difference between OR and XOR?
When both inputs are 1, OR gives 1 but XOR gives 0. XOR means the inputs are different, so it rules out the both-on case. A rule saying 'one or the other but not both' is XOR.
Give a real use for AND and for OR.
AND: a microwave runs only if the door is closed and the timer is running — the rule says 'both'. OR: a car alarm sounds if any one of several doors opens — the rule says 'any'.
How many rows does a truth table need?
Two to the power of the number of inputs: 2 inputs give 4 rows, 3 give 8, 4 give 16. The rows are counted upwards in binary, so no combination is missed.
How do you build a truth table from a logic circuit?
Give every gate its own column and work left to right. Fill the input columns first, then each gate column using only its own inputs, then combine those for the final output.
How do you write a circuit as a Boolean expression?
Use · for AND, + for OR and NOT for inversion. A circuit where an AND of A and B feeds an OR alongside an inverted C is X = (A·B) + NOT C.
How does a Karnaugh map simplify an expression?
The outputs are arranged so neighbouring squares differ by one variable only. Circle the largest groups of adjacent 1s in sizes 1, 2, 4 or 8; for each circle keep the variables that stay constant and drop those that change.
Why simplify a Boolean expression?
A shorter expression is a circuit built from fewer gates — less hardware, less power consumption and fewer things to fail. For example A·B + A·(NOT B) simplifies to just A, needing no gates at all.
How do you construct a logic diagram from a worded rule?
Write the Boolean expression first, draw the inputs down the left, draw the gates inside the brackets first, then feed their outputs into the final gate and label the output line.
How are the standard gate symbols recognised?
A flat-backed D shape is AND; a curved back with a pointed front is OR; a triangle with a circle is NOT. A circle on any output inverts it; an extra curve at the back makes it exclusive.
Which gate in an expression gets drawn first?
Whichever is inside the brackets. Its output feeds the gate outside them. Drawing them the other way round reverses the logic and is the most common mistake.
Which two Boolean rules save the most gates?
A + A·B = A, which drops a whole term when A alone is already enough, and A·(B + C) = A·B + A·C, which lets you factor out what is common. A repeated letter is the clue to look for.
How do you check that a simplification is correct?
Build the truth table for the original expression and for the simplified one. Every row must match. This catches nearly every error, and a shorter expression is never proof on its own.
What is the role of an operating system?
It sits between programs and hardware doing two jobs: abstraction — giving programs one standard way to ask for anything — and resource management, deciding who gets the CPU, memory and devices, and when.
What does abstraction mean for an operating system?
Programs ask for what they need in one standard way whatever hardware is underneath. A program says 'save this file' without knowing which drive it is or how that drive works.
Why do programs not talk to hardware directly?
Because every program would then need to know every model of disk, printer and network card, and adding new hardware would mean rewriting all of them. With an OS, only a driver is added.
How does the OS stop two programs interfering with each other?
It gives each program its own region of memory, queues their requests for shared devices, and refuses direct access to hardware or to its own memory — programs have to ask.
What happens when a new model of printer is added?
A driver is added to the operating system, teaching it how to speak to that model. Every existing program keeps making the same standard request, so all of them work with it immediately.
Name the functions of an operating system.
Memory management, scheduling, file system, device management, security, accounting, graphical user interface, virtualization and networking — all running in the background at once.
What does memory management do?
Gives each program its own region of memory, tracks what is free, reclaims it when a program closes, and refuses any attempt to read or write memory belonging to another program.
What does device management do?
Talks to every device through its driver and queues requests, so two programs never try to use one device at the same moment and no program needs to know the device's model.
What is virtualization?
Making one physical machine appear to be several separate ones, each running its own operating system and unable to reach the others. It is how a single server hosts many customers.
How does an OS stop one crashing program taking down the machine?
Each program has its own memory region and access outside it is refused; no program can address hardware directly. When one fails the OS stops it and reclaims its memory, leaving everything else running.
What is scheduling?
The rule the operating system uses to decide which process gets the CPU next, and for how long. A core runs one process at a time, so switching fast enough makes them appear simultaneous.
Compare first come first served with round robin.
FCFS runs each process to completion in arrival order — simple, but one long job blocks everything behind it. Round robin gives each a fixed time slice then moves on, so everyone gets an early first turn, at the cost of time spent switching.
What is priority scheduling, and what is its risk?
The highest-priority waiting process runs next, so urgent work always goes first — essential for real-time systems. The risk is starvation: a low-priority process may never run if urgent work keeps arriving.
What is ageing?
Raising a process's priority the longer it has been waiting, so that even the lowest-priority work eventually reaches the front of the queue. It is the usual fix for starvation.
What is multilevel queue scheduling?
Processes are sorted into separate queues by what they are — interactive work in one, background batch work in another — and each queue gets its own scheduling rule and its own share of CPU time.
What is the difference between polling and interrupts?
With polling the CPU repeatedly asks the device whether it is ready. With interrupts the device signals the CPU when it is ready, so the CPU can work uninterrupted until then.
What happens when an interrupt occurs?
The CPU finishes its current instruction, saves where it was, runs a short routine that deals with the device, then restores the saved state and carries on. That saving and restoring is the overhead.
When is polling the better choice?
When the device is almost always ready, so nearly every check succeeds and you avoid saving state thousands of times a second; and when a guaranteed response time is needed, since the delay is bounded by the checking interval.
Why do battery-powered devices use interrupts?
Because the CPU can sleep between events, which uses very little power. Polling forces it awake to run checks that mostly find nothing, shortening battery life for no benefit.
What is the security concern with interrupt handling?
Interrupts are raised by devices, so a faulty or malicious device can raise them constantly and leave the CPU no time for other work. Polling cannot be flooded, because the CPU decides when to look.
What is a network, and what does it make possible?
Two or more devices connected so they can exchange data. That enables sharing hardware and files, communication between people, and reaching central services from anywhere.
What is the difference between a LAN and a WAN?
A LAN covers one site on cabling the organisation owns, making it fast and cheap. A WAN spans several distant sites over links it does not own — rented lines or the internet — so it is slower and costs more per unit of data.
What is a PAN?
A personal area network: a few metres around one person, joining a phone to its earbuds or a smartwatch. Usually Bluetooth, chosen for very short range and very low power.
What is a VPN and what does it do?
A virtual private network creates an encrypted tunnel across a public network, so a distant device behaves as though it were on the organisation's own LAN and can reach internal servers not exposed to the internet.
Give one benefit and one drawback of networking an organisation's computers.
Benefit: one central copy of data that everyone works from and that stays current, plus shared hardware. Drawback: a single failure or break-in can affect everyone connected rather than one machine.
What is the difference between the internet and the worldwide web?
The internet is the global network of networks — the connections themselves. The web is one service running on it, made of pages fetched with HTTP. Email, calls and games are other services on the same internet.
What is edge computing, and when is it the right choice?
Processing data where it is produced rather than sending it away. Right when an answer is needed in milliseconds, when raw data would flood the network, or when the device must keep working if its link fails — smart traffic lights, for example.
What is a distributed system?
Many machines cooperating on one job with no single machine in charge. There is no single point of failure and it scales by adding machines, but keeping every machine agreed on the same answer is genuinely hard. A cryptocurrency blockchain is one.
Give a benefit and a limitation of cloud computing.
Benefit: resources available on demand with no hardware to buy or maintain. Limitation: the service depends on both the provider's uptime and your own connection, and the costs recur indefinitely.
What limits a mobile network?
Bandwidth is shared with every device nearby, so a busy area slows down, and coverage has gaps where there is no signal from a mast.
What is the difference between a switch and a router?
A switch moves traffic within one network, delivering each frame to the device it is addressed to; it cannot read IP addresses. A router moves traffic between networks, reading the destination IP address to choose the next hop.
What does a gateway do?
Joins two networks that use different protocols, translating between them so traffic can cross. A plain router only forwards; a gateway also converts.
What do a modem, a NIC and a wireless access point each do?
A modem converts between the network's digital signal and what the physical line carries. A NIC connects one machine to the network. A wireless access point lets devices join the LAN over radio instead of cable.
Which TCP/IP layers do network devices work at?
Network access: switches, network interface cards, wireless access points and modems, handling frames and bits inside one network. Internet: routers and gateways, reading IP addresses to choose routes.
What does a hardware firewall do?
Sits where the network meets the outside world and inspects traffic against its rules, blocking anything forbidden — on outgoing traffic as well as incoming.
What is a network protocol?
An agreed set of rules for a conversation between machines: what gets said, in what order, and what a reply means. Machines from different makers can talk only because both follow the same rules.
What is the difference between TCP and UDP?
TCP numbers packets, checks they all arrived, asks again for missing ones and reorders them — so data arrives complete. UDP sends without checking and never resends, so it is faster but packets may be late, out of order or lost.
When should UDP be used instead of TCP?
When timeliness matters more than completeness — live video, voice calls, online games. A late packet is already useless, so waiting for a resend delays everything after it for no benefit.
What does HTTPS add to HTTP?
Two guarantees: encryption, so nobody between the two ends can read the conversation, and identity, because a digital certificate proves the server really is who it claims to be.
What is DHCP for?
Giving a device an IP address when it joins a network. The device asks, and a DHCP server assigns one from its pool for a limited time, instead of every device being configured by hand.
Which five factors decide a network topology?
Reliability, transmission speed, scalability, data collisions and cost. No shape wins on all five, so every recommendation is a trade between them.
Describe a star topology and its main weakness.
Every device connects to one central switch, which makes it cheap, easy to extend and nearly collision-free. Its weakness is that the switch is a single point of failure: if it fails, nothing reaches anything.
Why is a mesh topology reliable, and why is it rarely used at scale?
Every pair of devices has its own link, so there are many routes and no single link matters. But links grow roughly with the square of the devices — 5 need 10, 20 need 190 — so it is reserved for a few critical points.
What is a hybrid topology?
Stars joined together, usually by more resilient links between them. Cheap where the devices sit, reliable where the traffic concentrates — which is what almost every real office and campus network looks like.
Why are collisions rare on a star network?
Because the switch sends each frame only to the device it is addressed to, so devices are never competing for one shared line.
What is the difference between client-server and peer-to-peer?
In client-server one machine holds the data and answers requests from the rest. In peer-to-peer there is no machine in charge — every machine holds a share and serves the others directly.
Give a benefit and a drawback of client-server.
Benefit: one authoritative copy of the data, with security, access and backups controlled in a single place. Drawback: the server is a single point of failure and can bottleneck when many clients want it at once.
Give a benefit and a drawback of peer-to-peer.
Benefit: no single point of failure, and capacity grows as more peers join, with no expensive server. Drawback: no central control over who sees what, data may disagree between peers, and availability depends on peers being online.
Why is online banking client-server?
Because an account balance must have one correct value held and controlled by the bank. Copies spread across customers' machines could disagree and none would be authoritative.
Why is a blockchain peer-to-peer?
By design: every participant holds a copy of the ledger and they agree among themselves what it says, so no single organisation decides what is true.
What is network segmentation and why is it done?
Splitting one network into smaller separate ones. For performance, because less traffic competes on each segment, and for security, because a break-in or infection is contained where it started.
What is subnetting?
Dividing the IP address range into smaller ranges, each its own network. Traffic between subnets must pass through a router, which is where rules can be enforced.
What is a VLAN?
A logical grouping of devices configured on the switch, regardless of where each device is plugged in. Two machines in one room can be on different VLANs, and moving someone between groups is a setting rather than re-cabling.
How does segmentation reduce congestion?
Broadcast traffic reaches only its own segment rather than every device, so on a network split six ways each device sees roughly a sixth as much — the cabling carries useful work instead of noise.
What does segmentation cost an organisation?
It must be designed and maintained: wrong rules block legitimate work and forgotten rules leave gaps. Each crossing between segments also adds a routing step, and so a little delay.
What is the difference between IPv4 and IPv6?
IPv4 uses 32 bits, written as four numbers, giving about 4 billion addresses — which ran out. IPv6 uses 128 bits, written as groups of hex digits, so the supply is effectively unlimited.
What is the difference between a public and a private IP address?
A public address is unique across the whole internet and reachable from anywhere on it, which makes it scarce. A private address is used inside one network only and is not routable on the internet, so millions of networks can reuse the same one.
What does NAT do and why?
The router swaps each device's private address for the organisation's one public address on the way out, remembers which device asked, and swaps it back on the reply. It exists because public IPv4 addresses are scarce.
What is the difference between a static and a dynamic IP address?
A static address never changes, which anything that must always be findable needs — a web server, for instance. A dynamic address is assigned by DHCP when a device joins and may differ next time, which suits laptops and phones and reuses addresses efficiently.
How does NAT contribute to security?
Private addresses are not routable on the internet, so nothing outside can address an internal machine directly — it can only reply to a conversation that machine started. A firewall is still needed as well.
What are the three transmission media and what does each carry?
Twisted pair sends bits as electricity down copper, fibre optic sends them as light down glass, and wireless sends them as radio through the air.
What is the difference between attenuation and interference?
Attenuation is the signal getting weaker with distance — copper fades after about 100 m, fibre runs kilometres. Interference is something else corrupting the signal: electrical noise for copper, walls and other radios for wireless.
Why is fibre used between buildings but not to every desk?
Between buildings its very low attenuation and immunity to interference are worth paying for. To a desk the run is short and the bandwidth is never used, so copper's much lower cost wins across hundreds of sockets.
Why is wireless the least secure medium?
The signal leaves the building, so anyone nearby can receive it, whereas tapping copper or fibre requires physical access to the cable. That is why wireless must always be encrypted.
What limits wireless bandwidth in practice?
It is shared with every device nearby, and walls, appliances and other networks all cause interference, so the rate a device actually achieves varies with conditions rather than being fixed.
What is packet switching?
Data is cut into small packets, each sent independently across the network and joined back together at the destination. No line is reserved for a whole transfer, so many conversations share the network at once.
What does a packet header contain?
The destination address, so routers know where to send it; the source address, so a reply or a request to resend can be sent back; and a sequence number saying where this piece belongs in the message.
Why do packets arrive out of order?
Each packet is routed independently, and different routes take different times. This is expected behaviour, which is exactly why sequence numbers are in the header.
What do switches and routers each do in packet switching?
A switch delivers a frame to the one device it is addressed to within a single network. A router reads the destination IP address and chooses the next network to forward the packet to, one hop at a time.
Why is packet switching better than reserving a line?
A reserved line is wasted whenever nobody is talking, and a break in it ends the conversation. Packet switching fills the gaps with other traffic and routes around breaks, and a lost packet means resending one packet rather than everything.
What does a firewall do?
Sits where the network meets the outside world and inspects every packet crossing it, allowing or dropping each one by rule — on outgoing traffic as well as incoming.
What is the difference between a whitelist and a blacklist?
A whitelist allows only what is listed and blocks everything else: safe by default but restrictive. A blacklist blocks only what is listed: convenient, but anything not yet known about gets through, so it is always a step behind.
Why do outgoing firewall rules matter?
They stop an already-infected machine sending stolen data out or contacting whoever controls it. Most answers mention only incoming traffic, so this is a reliable extra mark.
Name three things a firewall cannot protect against.
Traffic that never crosses it, such as malware on a USB stick or one internal machine infecting another; the contents of encrypted connections, which it cannot read; and attacks delivered over ports the rules legitimately allow.
How does NAT contribute to security, and what are its limits?
Internal machines have private addresses that are not routable, so nothing outside can address them directly — only reply to conversations they start. But NAT does nothing about outgoing traffic, what an allowed connection carries, or anything inside the network.
What is the difference between symmetric and asymmetric cryptography?
Symmetric uses one key to both lock and unlock — fast, but the key must reach the other end safely. Asymmetric uses two matched keys: a public one anyone may have and a private one that never leaves, so nothing secret has to travel.
Which key encrypts and which decrypts in asymmetric cryptography?
For confidentiality, the recipient's public key encrypts and only their matching private key can decrypt. That is why the public key can be handed to anyone without weakening anything.
What is a digital certificate?
An organisation's public key together with its identity, signed by a certificate authority the browser already trusts. It proves the public key really belongs to who it claims, which a bare public key cannot.
Why does HTTPS use both symmetric and asymmetric encryption?
Asymmetric solves the problem of agreeing a key safely but is slow. So it is used once to agree a symmetric key, and all the actual traffic is then encrypted symmetrically because that is much faster for bulk data.
Why does key management matter as much as the encryption itself?
Keys must be generated properly, stored where nobody else can reach them, replaced periodically and revoked immediately if they leak. A private key that escapes makes every message ever sent with it readable, however strong the algorithm.
What is a relational database?
A database that stores data in tables and links those tables together with keys, so each fact is stored once in the table it belongs to and other tables point at it rather than copying it.
What is the difference between a primary key, a composite key and a foreign key?
A primary key uniquely identifies each row in its table. A composite key does that using two or more columns together, when no single column is unique. A foreign key holds a primary key value from another table, which is how the link is made.
Give three benefits of a relational database.
Reduced duplication, because each fact is stored once; data integrity, because the database enforces rules such as refusing an invalid foreign key; and consistency, because changing a fact in one place is seen by everyone.
Give three limitations of a relational database.
A rigid schema that must be decided up front and is disruptive to change; poor handling of unstructured data such as documents and images; and difficulty scaling very large volumes across many machines.
Why is storing everything in one large table a problem?
The same fact gets written out on every row that mentions it. Changing it means finding every copy, and missing one leaves the data contradicting itself.
What are the three database schema levels?
Conceptual — the entities and relationships the organisation cares about. Logical — those turned into tables, columns, keys and data types. Physical — how the chosen system actually stores it, including files and indexes.
What does a conceptual schema contain, and what does it leave out?
It contains the entities and the relationships between them, in language the organisation recognises. It deliberately omits keys, data types and any choice of database product.
What belongs to the physical schema?
How the chosen system stores the data: files on disk, indexes, partitions and storage settings. This is where performance decisions live, and it must be redone if you change database product.
What is data independence?
The schema levels are insulated from each other, so a change at one does not force a change at another. Adding an index at the physical level alters no query written against the logical schema.
Why describe one database three times?
So the meaning can be agreed with non-technical people before technical choices are made, so storage can change without breaking programs, and so the same logical design can be built on different database systems.
What does an ERD show?
The entities a database stores and the relationships between them. Each box is one kind of thing that will become a table; each line is a relationship, labelled with the verb joining them.
What is the difference between cardinality and modality?
Cardinality is how many — one or many, drawn as a bar or a crow's foot. Modality is whether the relationship is compulsory — mandatory drawn as a second bar, optional as a circle.
How do you work out a relationship's cardinality?
Say it as a sentence in both directions. 'A teacher teaches many classes' and 'a class is taught by one teacher' together give one-to-many, with the crow's foot on the Class end.
Why must a many-to-many relationship be resolved?
A column holds only one value, so neither table can hold several foreign keys. It is replaced by a linking entity with one row per pair, keyed on both foreign keys together.
Where does the foreign key go in a one-to-many relationship?
In the table on the many side. A Class holds TeacherID, because the alternative would need a Teacher row to hold an unknown number of class columns.
What does a column's data type do?
It says what kind of value may be stored, and the database refuses anything that does not fit. It also decides what can be done with the values — arithmetic on numbers, true ordering on dates.
How do you decide a column's data type?
Ask whether you will ever calculate with it, compare it, or sort it. If yes it needs a real type; if it is only ever displayed — a phone number or postcode — text is correct however numeric it looks.
Why store a phone number as text rather than a number?
A numeric type drops the leading zero, so 07700 becomes 7700, and no arithmetic is ever done on a phone number anyway.
What three things go wrong if a date is stored as text?
Sorting compares character by character so the order is wrong; date ranges and age calculations become impossible; and nothing rejects an impossible date such as 31/02/2026.
Why must a foreign key have the same data type as the primary key it references?
Otherwise the join either fails or silently returns nothing — values that look equal to a person are not equal to the database when their types differ.
How do you turn an ERD into tables?
Each entity becomes a table and each relationship becomes a foreign key. In a one-to-many the foreign key goes in the many table; a many-to-many needs a linking table holding both foreign keys.
Why does the foreign key go in the many table?
Because a column holds one value. A Class row holds one TeacherID easily, whereas a Teacher row would need an unknown number of columns to hold every class they take.
What is the difference between a composite key and a concatenated key?
A composite key uses two or more columns together as the primary key, keeping them separate and queryable. A concatenated key glues values into a single column, such as 2026-S1, which then has to be pulled apart to filter on either part.
What are entity, referential and domain integrity?
Entity integrity: a primary key is never empty or duplicated. Referential integrity: a foreign key must match an existing row. Domain integrity: a value must fit its column's data type.
Why enforce rules in the database rather than in the program?
Rules enforced by the database apply to every program that touches the data, including ones written years later. Rules enforced in a program apply only to that program.
What is a functional dependency?
One column's value determining another's. Knowing a StudentID tells you the student's name, so Name is functionally dependent on StudentID. Normal forms are rules about which dependencies are allowed where.
What do 1NF, 2NF and 3NF each require?
1NF: every cell holds one value and every row is uniquely identified. 2NF: no non-key column depends on only part of a composite key. 3NF: no non-key column determines another non-key column.
What is a partial-key dependency?
A non-key column depending on only part of a composite primary key. With a key of StudentID and Club, StudentName depends on StudentID alone. It can only arise when the key is composite.
What is a transitive dependency?
A non-key column determining another non-key column. Club determines Teacher and Teacher determines Room, so Room depends on Club only indirectly — which breaks 3NF.
Why normalise, beyond saving space?
To prevent update problems, where one copy of a repeated fact is changed and others are not; insert problems, where a new club with no members has nowhere to live; and delete problems, where removing the last member loses the club's details too.
What are the four steps to normalise a design to 3NF?
List every piece of data with sample rows; make cells atomic and choose the key; move out anything depending on part of a composite key; move out any non-key column determined by another non-key column.
Why write sample rows before normalising?
Because functional dependencies are far easier to see in actual data than in a list of column names — repeated values make the repeated facts visible.
How do you find a transitive dependency?
In each table ask whether any non-key column determines another non-key column. If so, both move to a new table, and the determining column stays behind as a foreign key.
How do you check a finished 3NF design?
Pick a fact the scenario needs and follow the keys to find it. If you cannot reach it, a link is missing; if you find it in two places, the design is not yet in 3NF.
How many tables should a typical scenario produce?
More than feels natural — a scenario with eight columns usually becomes about four tables. Finishing with one or two almost always means a transitive dependency was missed.
What is denormalisation?
Deliberately storing some data more than once so that reads need fewer joins and run faster. It is a considered engineering trade, not a mistake.
What does denormalising gain and what does it risk?
It gains faster reads and simpler queries. It risks the same fact being stored in two places and disagreeing, requires every update to find every copy, and brings back insert and delete problems.
When is denormalising justified?
When data is read far more often than it is written — reports, dashboards and data warehouses that are loaded in bulk and then only read. Never for frequently-written data such as bookings or stock levels.
How should the risk of denormalising be managed?
Keep the normalised tables as the authoritative source and rebuild the denormalised copy from them, so there is always one correct version to fall back on.
Why should you normalise before denormalising?
Because you should design in 3NF, run it, and find out where it is actually slow. Denormalising before a measured problem exists gives away correctness for a speed gain you cannot demonstrate.
What is the difference between DDL and DML?
DDL, data definition language, changes the structure of the database — tables, columns, keys. DML, data manipulation language, reads and changes the rows inside tables that already exist. The test is shape versus contents.
Name the main DDL statements and what each does.
CREATE makes a new table with its columns, types and keys; ALTER changes an existing structure, such as adding a column; DROP removes a table entirely, along with everything in it.
Name the main DML statements and what each does.
SELECT reads rows matching a condition; INSERT INTO adds a new row; UPDATE SET changes values in existing rows; DELETE removes rows from a table.
What is the difference between DELETE and DROP?
DELETE removes rows and the table stays, ready for more data — it is DML. DROP removes the table itself, with its structure and all its contents — it is DDL.
Who runs DDL and who runs DML?
DDL is run rarely, by a database administrator, when the design genuinely changes. DML is run constantly, by the application, every time somebody uses the system.
What does the ON condition in a JOIN do?
It names the two columns that must match — almost always a foreign key and the primary key it points at. Without it, every row of one table pairs with every row of the other.
In what order are SQL clauses applied?
FROM and JOIN decide which rows exist, WHERE filters them, GROUP BY collapses them, HAVING filters the groups, SELECT picks the columns, and ORDER BY sorts. SELECT is written first but applied near the end.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters groups after grouping, and is the only place a condition on a count or total can go, because that value does not exist until GROUP BY has run.
How does LIKE with the % wildcard work?
% stands for any run of characters. 'Sm%' matches anything starting Sm, '%son' anything ending son, and '%ann%' anything containing ann.
When is DISTINCT needed in a joined query?
When the join can legitimately produce the same row more than once — a student belonging to two clubs would otherwise appear twice in a list of names.
What do INSERT, UPDATE and DELETE each do?
INSERT INTO adds a new row; UPDATE SET changes values in rows that already exist; DELETE removes rows. All three are DML, so the table's structure is untouched.
What happens if an UPDATE or DELETE has no WHERE clause?
It applies to every row in the table, with no warning, no confirmation and no undo once committed. The safe habit is to write the WHERE clause first and test it with a SELECT.
Why does an index make reads fast and writes slow?
It is a separate sorted structure the database can go straight to, instead of reading every row. But every INSERT, UPDATE or DELETE on an indexed column must update that structure as well as the row.
What is index fragmentation, and how is it fixed?
After many changes an index's entries no longer sit in an efficient order, so it gradually stops helping. Reorganising tidies it in place; rebuilding constructs it from scratch. Both are usually scheduled for quiet hours.
Why might indexes be dropped before a bulk load and rebuilt afterwards?
With indexes present, every one of the millions of inserted rows updates every index individually. Building each index once at the end is a single sorted pass, which is far cheaper.
What decides which type of machine learning applies?
What the algorithm is given to learn from: labelled examples, unlabelled data, or an environment to act in. Answer that and you have named the type.
What is the difference between supervised and unsupervised learning?
Supervised learns from labelled examples to predict the label of something new. Unsupervised is given no labels and finds groups or structure the data already contains — but cannot say what those groups mean.
What is reinforcement learning?
An agent acts in an environment, receives a reward or penalty for what happens, and over thousands of attempts learns which actions earn the most reward. It needs no dataset, but must be allowed to fail repeatedly.
What makes deep learning different from other approaches?
It uses many layers, each building on what the last found — edges, then shapes, then whole objects — so it works out its own features. The cost is needing a great deal of data and being hard to explain.
What is transfer learning and when is it used?
Starting from a model already trained on a related task and retraining only its final layers on your own data. It is used when you have too few examples to train from scratch — hundreds rather than millions.
Why do training and using a model need different hardware?
Training repeats the same calculation over millions of examples for hours or days, needing massive parallel processing. Using the trained model is one small calculation per question, which a phone or camera can often do.
What are GPUs and TPUs used for in machine learning?
Both provide the massive parallel processing training needs. A GPU has thousands of general simple cores; a TPU is a chip designed specifically for machine-learning calculations.
What is the difference between an ASIC and an FPGA?
An ASIC is built for one task and can never do another — the fastest and most power-efficient option, but useless if the task changes. An FPGA can be reconfigured after manufacture, so it is slower but adaptable.
When is an edge device the right place to run a model?
When a trained model must answer immediately on the spot — in a camera or a vehicle. It gives millisecond responses, keeps data off the network, and works even when the connection drops.
Why does storage speed matter when training?
Training datasets run to terabytes and must be read fast enough to keep the processors busy. Slow storage leaves very expensive hardware sitting idle and waiting.
Where does bias in a machine-learning model come from?
From training data that reflects the world as it was. A model learns the patterns in past decisions, so historical unfairness is reproduced at scale — and wearing the appearance of objectivity, which makes it harder to challenge.
Why does removing a sensitive field not remove bias?
Because other fields stand in for it — a postcode can imply background, a school can imply income — and the model finds those substitutes on its own.
Why must fairness be measured per group rather than overall?
A model can be 95% accurate overall and far worse for a small group, because that group barely affects the average. The headline number hides exactly the problem you are looking for.
What is the accountability problem with machine learning?
When a model causes harm it is unclear who answers for it — the developer, the organisation using it, or the operator. 'The system decided' gives the affected person nobody to appeal to.
Name three ethical concerns about machine learning beyond bias.
Transparency, since a complex model cannot easily explain its decision; privacy and consent, because data given for one purpose is used to train models; and environmental impact, since training large models uses very large amounts of energy and water.
Why must ethical guidelines be continually reassessed?
Because they were written for the technology that existed at the time. Something genuinely new does not break the old rules — it sits outside them, doing something nobody thought to allow or forbid.
What four lenses can you apply to any new technology?
Individual rights: can a person refuse, and appeal? Privacy: what is collected, and did bystanders agree? Equity: who is left out or served worse? Society: what changes when everyone has it?
What is the ethical concern with quantum computing?
It would eventually break much of today's encryption. Because encrypted data can be stolen and stored now and decrypted later, the risk begins before the machines exist — so organisations need quantum-resistant encryption already.
Why is augmented reality a greater privacy concern than a fixed camera?
The glasses go everywhere the wearer goes, recording everyone they meet without any consent, and they can also alter what the wearer sees — which raises the question of who chooses that.
Why is pervasive AI a concern even when each individual system is defensible?
Because of the accumulation. When jobs, loans, healthcare and policing all involve models, large parts of a person's life are decided by systems they cannot see, question or appeal against.
What are the six parts of a problem specification?
Problem statement, objectives and goals, input specification, output specification, constraints and limitations, and evaluation criteria.
What makes an objective testable?
You can describe the test that would settle it in one sentence. 'Return results in under five seconds on 10,000 records' can be tried; 'be fast' is an opinion and never can be.
What goes in an input specification?
Each input item, its data type, its valid range, and where it comes from — for example 'Member ID: a whole number between 1 and 99999, entered by staff'. The validation rules come straight from this.
What is most often forgotten in an output specification?
What happens when there is nothing to show. Stating 'a message if there are no results' is a cheap and reliable mark.
Why write evaluation criteria before building?
So the target cannot be moved afterwards. Deciding what counts as success once you already know what you built is not judging the work at all.
What are the four concepts of computational thinking?
Decomposition — breaking a large problem into smaller separate ones. Pattern recognition — finding what repeats. Abstraction — deciding what to leave out. Algorithmic design — writing the steps precisely.
What does abstraction actually mean?
Deciding what to leave out, and why — not being vague. A route-planning app treats a road as a start point, an end point and a travel time, dropping surface, width and street name as irrelevant.
What is pattern recognition for?
Finding the parts of a problem that are the same, so one solution serves many cases. Every track event needs the same steps, so solving it once covers the 100 m, the 200 m and the relay.
What is algorithmic design?
Setting out the steps in order, precisely enough that someone else could follow them without asking a question. It does not require code — plain steps or a flowchart are enough.
Does computational thinking require programming?
No. The guide states it explicitly: it is a toolkit of problem-solving techniques. Planning a sports day, designing a database and diagnosing a fault all use the same four.
What four questions turn an unfamiliar problem into a solvable one?
What are the pieces (decomposition)? What repeats (pattern recognition)? What can I ignore (abstraction)? What are the steps (algorithmic design)? Then trace the steps on a small example by hand.
How is designing a database an example of computational thinking?
Decomposition splits one wide table into several; abstraction decides which attributes each entity actually needs; pattern recognition notices that every many-to-many relationship needs a linking table.
Where does abstraction matter most in machine learning?
In choosing which features to give the model and which to leave out. It is usually the single most important decision in a machine-learning project.
Why trace an algorithm by hand before writing code?
Because it turns a plausible-looking algorithm into one you know is right, and it finds the error before any code exists to debug. It is also very often exactly what the exam asks for.
Why does Paper 2 set a question with no code?
To test whether you can take a problem described in words and make it solvable without reaching for a programming language — which is what computational thinking means.
What are the standard flowchart symbols?
Rounded box for Start/End, slanted box for Input/Output, rectangle for Process, diamond for Decision with two labelled exits, arrow for Flowline, and a small circle for Connector.
How is a loop shown on a flowchart?
There is no loop symbol. A loop is a decision diamond with a flowline going back up to it — follow the arrows and the loop is obvious.
How do you trace a flowchart reliably?
Draw the table first with one column per variable plus output; write a new row for every change; write the comparison out in full at every diamond; and add to the output column only when an output box is reached.
What is the commonest tracing error?
The boundary case. When the test is 'count at most N', the loop still runs when the two values are equal — one more time than most people expect.
How many exits does a decision symbol have?
Exactly two, labelled Yes and No. A diamond drawn with one exit or with three is drawn incorrectly.
What is a variable, and what does its data type decide?
A named place in memory holding one value. Its data type says what kind of value it is, which decides both what can be stored there and what operations work on it.
Name the five data types and what each holds.
Integer: a whole number. Decimal: a number with a fractional part. Char: a single character. String: a sequence of characters. Boolean: exactly True or False.
Why does + behave differently on numbers and strings?
It adds numbers and joins strings, so 12 + 1 gives 13 but "12" + "1" gives "121". Mixing the two — "12" + 1 — fails, and is one of the commonest bugs.
What is the difference between a local and a global variable?
A local variable is created inside a function, cannot be seen from outside, and is destroyed when the function ends. A global variable is created outside any function and is visible throughout the program.
Why are local variables preferred?
If a local value is wrong, the cause is inside that function. If a global value is wrong, any part of the program could have changed it — so the bug could be anywhere.
Where do string positions start, and what does a slice include?
Positions start at 0, and a slice excludes its end position. So text[2:5] gives the characters at 2, 3 and 4 — three characters, which is simply 5 minus 2.
What do len, find and split each do?
len gives the number of characters. find gives the position where a piece of text starts, or -1 if it is absent. split breaks a string into a list at each occurrence of a separator.
Do string methods change the original string?
No. upper, lower and replace all return a new string and leave the original untouched. To keep the change you must assign it back: text = text.upper().
How do you split an email address at the @?
Find the position of the @, then take everything before it and everything from one position after it: at = email.find("@"); user = email[:at]; domain = email[at + 1:]. The +1 skips the @ itself.
When is split better than using fixed positions?
Whenever the parts can vary in length. code[0:2] works only while the prefix is exactly two characters, whereas splitting at the separator survives a longer or shorter one.
What is an exception?
A problem that appears while the program is running, rather than a mistake in the code's grammar. Without handling the program simply stops; with handling it can report the problem and carry on.
What do try, except and finally each do?
try holds only the lines that might fail. except (catch in Java) handles one specific kind of failure. finally runs whether or not anything failed, and is where files get closed.
What are the three sources of failure to look for?
Unexpected input, usually from people; unavailable resources such as a missing file or unresponsive network; and logic errors, where the code ran on values nobody planned for.
When should you validate rather than catch?
When the problem is predictable and inside your control — an empty list, a zero divisor. Catch the things outside it: files, networks and databases, which can fail between your check and your use.
Why must closing a file go in finally?
If a line inside try fails, control jumps straight to except and any later lines in try never run. finally runs either way, so the file is closed rather than left open holding a system resource.
What are the three kinds of error?
Syntax errors stop the program running at all. Run-time errors stop it partway with a message. Logic errors let it run perfectly and produce the wrong answer — and only the third needs debugging.
Name the four debugging techniques and what each is for.
Trace table: work through by hand, no tools needed — the exam method. Print statements: show a value at a chosen point. Breakpoints: pause and inspect every variable. Step-by-step execution: run one line at a time and watch values change.
What is the method for narrowing down a bug?
Write down what you expected for one specific input; find the first value that is wrong, halving the search each time; look only at the lines that set that value; then change one thing and test again.
Where do logic errors usually hide?
At the boundary: an empty list, a single item, the first and last positions, and values that are exactly equal. If a program is wrong, test the boundary before anything else.
Why change only one thing at a time?
If the change works, you know which change fixed it. If it does not, you have not added a new set of suspects to investigate.
What is the difference between a static and a dynamic data structure?
A static structure has its size fixed when it is created, in one contiguous block of memory. A dynamic structure grows and shrinks while the program runs, taking more memory only when it needs it.
Why is reading a position in a static array fast?
Everything sits in one block with items of equal size, so the address of item 20 is simply the start plus twenty item-widths. It is one calculation, with nothing searched for — O(1).
What does a dynamic structure cost when it grows?
When it outgrows its block it must claim a bigger one and copy everything across. That single operation is expensive, but it happens rarely, so the average cost of adding an item stays low.
When should you choose a static structure?
When the size is genuinely fixed — twelve months, seven days, sixty-four squares — or when a very large amount of data is scanned repeatedly and both speed and predictable memory matter.
Why is a fixed-size array wrong for an unknown number of items?
You must guess a maximum. Guess too small and it overflows or silently discards data; guess too large and most of the memory is never used — with still no guarantee the guess was enough.
How are items in a list addressed?
By position, starting at 0. A list of four items has positions 0, 1, 2 and 3, so asking for position 4 is an error — the commonest list bug there is.
How do you add to and remove from a dynamic list?
append adds at the end, insert(position, value) adds anywhere and shifts the rest along. remove(value) takes out the first match, and pop() removes the last item and gives it back.
Why must you not remove items while looping over a list?
Removing shifts everything after it down one place while the loop counter moves up, so items get skipped silently. Build a new list instead, or loop over a copy.
What is a 2D list and how is it addressed?
A list whose items are themselves lists — a grid. It is addressed [row][column], always in that order: grid[1][2] is row 1, column 2.
Why does visiting every cell of a grid need a nested loop?
The outer loop gives you each row, which is itself a list; the inner loop reaches the individual values inside it. That is also why scanning a grid is O(rows × columns).
What is a stack?
A structure that allows adding and removing at one end only, the top. The last item put in is the first taken out — last in, first out, or LIFO.
What are the four stack operations?
push adds an item on top; pop removes the top item and returns it; peek returns the top item without removing it; isEmpty says whether there is anything in the stack at all.
Why are all stack operations O(1)?
Every operation touches only the top. Nothing is shifted along and nothing is searched for, so the cost is the same whether the stack holds three items or three million.
Give three uses of a stack.
Undo, where the most recent action must be reversed first; the call stack, since function calls unwind in reverse order; and checking that brackets match, because the most recent opening bracket must close first.
What causes a stack overflow?
A stack that keeps growing with nothing being popped until it runs out of memory — usually a function that calls itself with no way to stop.
What is a queue?
A structure added to at one end and taken from at the other: items join at the back and leave from the front. The first item in is the first out — first in, first out, or FIFO.
What are the four queue operations?
enqueue adds an item at the back; dequeue removes the item at the front and returns it; front returns the next item out without removing it; isEmpty says whether anyone is waiting.
Why is a plain list a poor implementation of a queue?
Removing from the front of a list shifts every remaining item down one place, which is O(n) every time. A proper queue structure removes from the front in constant time.
What one question chooses between a stack and a queue?
Does the most recent item matter most, or the one that has waited longest? Most recent means a stack; longest waiting means a queue.
Give three uses of a queue.
Print jobs, so they print in the order sent; process scheduling, where round robin takes the front process and returns it to the back; and buffering data such as keystrokes or network packets, which must be handled in arrival order.
Why are sequence errors hard to spot?
Both lines are perfectly valid, so nothing is reported. The program runs to completion and simply produces the wrong answer.
What causes an infinite loop?
The thing the loop's test depends on never changes — most often because the counter is increased inside a branch that does not always run, so the test can never become false.
Where do setup, work and reporting belong relative to a loop?
Set up before the loop — totals at 0, counters at their start. Do the work for one item inside. Print or return the finished result after, since printing inside shows a running value rather than the final one.
What is deadlock and how is it prevented?
Two parts of a program each hold a resource the other is waiting for, so neither can move. It is prevented by having every part claim shared resources in the same fixed order.
What three questions check that a sequence is right?
Is every value set before it is used? Does the thing the loop tests always change? Is the result used after it is complete rather than during? Those three catch nearly every sequence error.
What is the difference between an else-if chain and separate ifs?
A chain runs exactly one branch and skips the rest once a match is found. Separate ifs test every condition, so several may run or none. Use a chain for mutually exclusive cases and separate ifs for independent ones.
Why must a range chain be ordered narrowest first?
The chain stops at the first true test. If mark >= 50 is tested before mark >= 70, every mark of 70 or more matches the first test, so the later branch is unreachable.
What do and, or and not do?
and requires both sides to be true; or requires at least one; not reverses the result. They are the same logic as the AND, OR and NOT gates, with the same truth tables.
What is wrong with 'if day == "Sat" or "Sun"'?
The second half is a bare piece of text rather than a comparison, and non-empty text counts as true — so the whole condition is always true. Each side of an or must be a full comparison.
What is the difference between == and =?
== compares two values and produces a Boolean; = assigns a value to a variable. Writing = where == belongs is a classic error.
How do you choose between a counted and a conditional loop?
Ask whether you know how many times it must repeat before it starts. Yes means a counted loop (for); no means a conditional one (while), which repeats as long as a condition holds.
How many times does a counted loop of 5 run, and what values does the counter take?
Five times, taking 0, 1, 2, 3 and 4. It starts at 0 and stops before 5 — the same rule as a string slice, and the same source of off-by-one errors.
Can a while loop run zero times?
Yes. The condition is tested before the first pass, so if it is already false the body never runs at all. That is correct behaviour and often exactly what is wanted.
Where should a counter or total be set up?
Before the loop. Setting it inside resets it on every pass, so the final answer would be just the last value rather than the accumulated one.
Why do nested loops produce O(n²) work?
The inner loop runs completely for every single pass of the outer loop, so the total work is rows times columns. That is where quadratic complexity comes from.
What is a function?
A named block of code that does one job, is given data through parameters, and hands back a result with return. Written once, it can be called anywhere and fixed in one place.
What is the difference between a parameter and an argument?
The parameter is the name in the function's definition — the placeholder. The argument is the actual value supplied when the function is called.
What are the benefits of modularisation?
Reusable: one definition serves every caller. Maintainable: a fix applies everywhere at once and faults trace to one function. Testable: each function can be tested on its own. And work can be split between people.
Why pass values in as parameters rather than using globals?
A function told what it needs works anywhere, can be tested on its own, and cannot be broken by something changing elsewhere in the program.
Why should a function return rather than print?
A returned value can be stored, compared or displayed by the caller, and the function can be tested. A function that only prints can do none of those.
What does Big O describe?
How an algorithm's work grows as the data grows — the shape of the growth, not the time in seconds, which depends on the machine it runs on.
How do you work out an algorithm's complexity?
Count the loops over the data. No loop is O(1), one loop is O(n), a loop inside a loop is O(n²), and halving what is left at each step is O(log n).
Why is 2n + 5 written as O(n)?
Big O describes the shape of the growth, and constants and lower-order terms do not change that shape. Doubling the data still doubles the work.
What is the difference between time and space complexity?
Time complexity is how the number of steps grows; space complexity is how the extra memory grows, not counting the input. Bubble sort is O(n²) time but O(1) space, because it sorts in place.
What does O(n²) mean in practice?
Twice the data means four times the work, and ten times the data means a hundred times. At 1,000 items that is a million steps; at 10,000 it is a hundred million.
How does linear search work, and what does it cost?
It checks each item in turn until it finds the target or runs out, returning the position or -1. Best case O(1) if the target is first, worst case O(n) if it is last or absent.
How does binary search work?
Look at the middle item. If it equals the target, stop. If it is too small the target is to the right, so move low to mid + 1; if too big, move high to mid - 1. Each step discards about half the remaining list.
Why must binary search have sorted data?
Discarding half depends on knowing which half the target would be in, which only holds if the list is in order. On unsorted data it does not run slowly — it returns the wrong answer.
How does binary search terminate?
When low passes high, meaning there is nothing left to search. It then returns -1 to indicate the target is absent.
How do the two searches grow with the data?
Doubling the list doubles linear search's worst case, but adds only one comparison to binary search's. Sixteen items need at most four binary comparisons; a million need about twenty.
How does bubble sort work?
It compares each neighbouring pair and swaps any that are out of order. Each pass sends the largest remaining value to the end, so the next pass can compare one fewer pair.
How does selection sort work?
For each position it looks through the whole remaining list, remembering where the smallest value is, then swaps it into place. At most one swap per position.
How do the two sorts compare on efficiency?
Both make O(n²) comparisons. Bubble sort makes up to O(n²) swaps; selection sort makes only O(n). Bubble sort has a best case of O(n) on sorted data thanks to its early exit, while selection sort has none.
What is the space complexity of bubble and selection sort?
Both are O(1). Each sorts in place, needing only a couple of extra variables however large the list becomes.
When is selection sort the better choice?
When writing data is far more expensive than reading it. The comparison counts are identical, so the algorithm doing O(n) swaps instead of O(n²) is clearly better.
What are the three file modes and what does each do?
r reads and fails if the file does not exist. w empties the file immediately and then writes, creating it if absent. a appends at the end, keeping what was already there.
What is the danger of opening a file in w mode?
It empties the file the moment it opens, before anything is written. Choosing w when you meant a destroys the previous contents, and no error is raised because it is a valid operation.
Why must a line read from a file be stripped and converted?
Every line carries the invisible newline that ended it, so comparisons fail until it is stripped. And everything read is text, so "72" must be converted with int() before any arithmetic.
Why must a file be closed?
Its contents may not be fully written to disk otherwise, and an open file holds a system resource, possibly locking it against other programs.
What does a with block do for file handling?
It closes the file automatically when the block ends, even if something fails inside it. It is the finally block of exception handling, built into the language.
What is object-oriented programming?
An approach that keeps a thing's data and the operations on it in one place. A book's title and its borrow() method live together, rather than the data in one structure and the code elsewhere.
What is the difference between a class and an object?
A class is the template, saying what every one of this kind will have and can do; it holds no values itself. An object is one actual thing made from that class, with its own values.
What is the difference between inheritance and polymorphism?
Inheritance is reusing what a more general class already has — Ebook takes Book's title and author. Polymorphism is the same method call answered appropriately by each kind. Inheritance often makes polymorphism possible, but they are different ideas.
Give two advantages and two disadvantages of OOP.
Advantages: it models real things with data and behaviour, and inheritance gives reuse with no copied code. Disadvantages: the class structure must be designed before coding, and it is more code than a small task needs.
When is OOP not worth using?
For a short script with no real entities to model — reading a file and printing a total gains nothing from classes while still paying the design and code overhead.
How do you find the classes and methods in a description?
Underline the nouns as candidates for classes and attributes, and the verbs as candidates for methods. It is crude but gets a first draft right surprisingly often.
What are the three parts of a UML class box?
The name at the top, the attributes in the middle with their types, and the methods at the bottom with their return types — always in that order.
What do -, + and underlining mean in UML?
A minus sign means private, reachable only inside the class. A plus sign means public. An underlined entry is static, belonging to the class itself rather than to each object.
Where should a method be placed?
In the class that holds the data it uses. borrow() belongs on Book because Book holds onLoan; putting it elsewhere would force that attribute to be made public, losing encapsulation.
When is inheritance the wrong choice?
When the relationship is really 'has a' rather than 'is a'. A Library has Books but is not a Book, so it should hold a collection rather than inherit.
What is the difference between a static and a non-static variable?
A non-static (instance) variable has one copy per object, holding what makes that object different. A static (class) variable has exactly one copy belonging to the class itself, shared by every object.
Why must a counter of objects created be static?
Because it is a fact about the class, not about any one object. As an instance variable, every object would hold its own count of 1 rather than a shared running total.
What is the difference between a static and an instance method?
An instance method uses the object's own data and cannot be called without an object. A static method belongs to the class, uses no object's data, and can be called as Book.count() with no object at all.
Why can a static method not use instance variables?
It can be called with no object in existence, so there is nothing for self to refer to — no way to know which object's data was meant.
What test decides between static and instance?
Would every object have the same value, always? Yes means static; no means it must be an instance variable. In doubt, choose instance — sharing one value is a decision, not a default.
What is the difference between defining a class and instantiating an object?
Defining writes the template once, saying what every one will have and can do. Instantiating creates an actual object from that template, with its own values, as often as needed.
What does a constructor do?
It runs automatically when an object is created and gives every attribute a value, so no object ever exists in an unfinished state. It can also refuse invalid values before the object exists.
What does self refer to?
The object the method was called on. self.title is this particular book's title, which is what lets one method definition serve every object of the class.
Why is not every attribute a constructor parameter?
Some have a single correct starting value. A new book is never on loan, so onLoan is set to False inside the constructor rather than asked for — which removes a chance to get it wrong.
What happens if a constructor misses an attribute?
The object exists with a missing value, and the failure appears much later, somewhere that has nothing to do with the cause — which makes it hard to trace.
What is encapsulation?
Keeping an object's data private and providing public methods as the only way to reach it, so every change goes through code that can check it first rather than any part of the program writing whatever it likes.
What is the difference between encapsulation and information hiding?
Encapsulation is the mechanism — private attributes, public methods. Information hiding is the principle behind it: the outside should know what a class does, not how, so the inside can be rewritten without breaking callers.
What are getters and setters?
A getter returns a private value; a setter changes one after checking it. Providing a getter but no setter makes a value readable from outside but not changeable.
Why is a setter with no checks not really encapsulation?
The data is then effectively public with extra typing. The value of encapsulation lies in the checking that happens on the way in, not in the wrapping itself.
How does a private attribute help when a value is wrong?
The fault must be inside that class, since nothing outside could have written it. With a public attribute, any line of the whole program could be responsible — the same argument as preferring local variables to global ones.
Track your progress with spaced repetition
Sign up free to get personalised review schedules and see exactly which cards you need to practice most.
Get Started Free