2026 paper questions
Set B
- ASimplicity
- BTesting
- CRapid Development
- DScalabilityAnswer
Scalability means designing the MVP so its architecture and technology choices support future enhancements and growth. Simplicity keeps it lean, testing validates assumptions and rapid development builds it quickly.
- AEncapsulation
- BInheritanceAnswer
- CAbstraction
- DPolymorphism
Inheritance creates a derived (child) class from an existing parent class; the child reuses the parent's attributes and methods, so code is not repeated.
- AAccessibility
- BSimplicityAnswer
- CFeedback
- DLearnability
Simplicity means the design is as straightforward as possible, removing unnecessary complexity and focusing on core functions, like Google's homepage.
- AUsers
- BEnvironment
- CInterface
- DTasksAnswer
Tasks are the specific activities users perform with the system, such as searching, adding to cart and paying on a shopping site.
- ALinked List
- BQueue
- CStackAnswer
- DArray
A stack adds (push) and removes (pop) elements only at its top, so the last element added is the first removed. A queue is FIFO.
- ALeafAnswer
- BRoot
- CParent
- DSubtree
A leaf node has no child. The root is the node with no parent; a parent has at least one child; a subtree is a part of a tree, not a node.
- ANull Hypothesis ()Answer
- BCause-and-effect Hypothesis
- CAlternative Hypothesis ()
- DResearch Hypothesis
The null hypothesis () states that there is no effect or relationship between the variables and that any observed difference is due to random chance. The alternative hypothesis () claims an effect exists.
- ASelf-Learning
- BReinforcement Learning
- CUnsupervised Learning
- DSupervised LearningAnswer
In supervised learning the model is trained on labelled data, where the correct output is given for each input. Unsupervised learning uses unlabelled data, and reinforcement learning uses rewards and penalties.
- AProcessing unit
- BInput layer
- COutput layerAnswer
- DHidden layer
The output layer is the final layer that produces the output. The input layer only receives raw data, and hidden layers process it in between. \"Processing unit\" is not a layer.
- ATraffic flow statistics
- BEmployee ID numberAnswer
- CWeather forecast data
- DCompany revenue reports
PII identifies a particular person: names, ID numbers, addresses, birth dates, contact numbers. An employee ID number points to one person. The other options are general data about traffic, weather or a company.
- ASecurity Question
- BPassword
- CBiometricAnswer
- DOTP Code
'Something you are' is a physical or behavioral trait of the person, such as a fingerprint or face, which is biometric verification. A password and a security question are something you know; an OTP code comes from something you have (the phone).
- AGoogle Docs
- BExcelAnswer
- CPrezi
- DMicrosoft Teams
Excel (with Google Sheets and Tableau) is a data visualisation tool used to create graphs, charts and tables that illustrate trends in research data. Google Docs is for text, Prezi for presentations and Teams for collaboration.
- AIntroduction
- BReflection
- CFindingsAnswer
- DProcess
The Findings section communicates results clearly and concisely with well-designed graphs, charts, infographics or videos. The introduction states the question and objectives.
One mark for each aspect with its meaning:
- Effectiveness: the degree to which users can successfully complete their tasks using the device or system. Example: a user completes an online form without help.
- Efficiency: the speed and minimal effort with which tasks can be done. Example: sending money in a few taps.
- Satisfaction: the user's sense of comfort and positive experience while using the system. Example: users enjoy a clean app and return to it.
One mark for each advantage:
- Handles complex and unstructured data: it can work with images, audio, text and large datasets that are too complex for fixed rules.
- Learns patterns automatically: it learns from data without explicit programming of every rule and does not need expert knowledge or human intervention for each decision.
- Improves with more data: it adapts to new data and becomes more accurate over time (continuous learning); for example a spam filter learns new spam words as users mark emails.
| Stack | Queue |
|---|---|
| Follows LIFO: the last element added is removed first. | Follows FIFO: the first element added is removed first. |
| Insertion and deletion at one end, the top. | Insertion at the rear, deletion at the front. |
| Operations: push, pop, top. | Operations: enqueue, dequeue, front. |
| Used in undo, back button, recursion, DFS. | Used in scheduling, buffering, print queue, BFS. |
Real-life example of a stack: a pile of plates in a cafeteria; the plate put on last is taken first. Real-life example of a queue: students standing in line at a canteen or bank counter; the person who came first is served first.
Importance (2 marks)
Security protocols are sets of rules and procedures that protect data and communication from unauthorized access, tampering and interception. They are important because:
- they keep data confidential by encryption and maintain its integrity (data is not changed);
- they authenticate users and devices and control access, so only authorized people use the data;
- they secure transmission over the internet, protect against malware and support backup and recovery, which reduces risk and builds trust in online banking, shopping and learning.
Example (1 mark)
HTTPS (HTTP with SSL/TLS) encrypts a student's password and card details between the browser and a university fee-payment website, so a hacker on the network cannot read them.
Linked list: a linear data structure in which elements, called nodes, are connected by pointers. Each node stores the data and the reference (memory address) of the next node; the last node points to NULL. The first node is reached through head.
Advantages
- Dynamic size: it can grow or shrink during execution; no size is declared at the start, so memory is not wasted.
- Easy insertion and deletion at any position: only pointers are changed; no shifting of elements as in an array.
- It can store different types of data, and a doubly linked list can be traversed in both directions.
Efficiency in cybersecurity means protecting systems without significantly hindering user productivity. It is important because:
- Security that slows users down gets bypassed: if a measure is too slow or complicated, users find shortcuts (such as writing passwords on paper), which weakens security.
- It protects productivity and saves time: auto-save and backup systems (for example Google Docs saving to Drive in real time) mean work is not lost in a crash or cyberattack and tasks need not be redone.
- It makes strong security easy: password managers such as LastPass or Bitwarden store and autofill strong, unique passwords, so logging in is both quicker and more secure.
A p-value measures how likely the observed results are due to chance, assuming the null hypothesis is true.
- Evidence: a low p-value (such as 0.02) is strong evidence against ; a high p-value (such as 0.5) is weak evidence and the result may be random.
- Decision: it is compared with the significance level . If p-value , is rejected and the result is statistically significant; otherwise we fail to reject .
- Example: plants given a new fertilizer grew taller. A p-value of 0.02 shows the extra growth is very unlikely to be chance, so the fertilizer probably works.
Learnability is how easily new users can accomplish basic tasks the first time they use a system, without extensive guidance or prior experience.
Why it is important: many systems (banking apps, government websites, ticket machines) are used by a broad audience with different levels of technical skill. If a system is hard to learn, new users make errors, need training, feel frustrated and may abandon it. A learnable system makes users confident from the first interaction, reduces training and support costs, and increases adoption of the product.
Example: a mobile banking app lets a new user quickly learn to check the balance, transfer funds and view transaction history. Onboarding tutorials and interactive guides further improve learnability.
Spyware (1.5 marks) is harmful software that secretly installs on a device and collects information about the user without their knowledge: it can record keystrokes, take screenshots and watch online activity, then send the data to a remote attacker.
Phishing (1.5 marks) is a trick (social engineering attack) in which fake emails, websites or messages pretend to come from a reliable source and deceive the user into giving away passwords or credit card numbers personally.
| Spyware | Phishing |
|---|---|
| A type of malicious software (malware) | A deception technique, not necessarily software |
| Works silently without the user's action | Needs the user to click and type the information |
| Stops with anti-malware tools | Stopped mainly by awareness and email filters |
| Example: a keylogger hidden in a free game | Example: fake bank SMS with a login link |
Symmetric cryptography (1.5 marks) uses one shared secret key for both encryption and decryption. It is fast and efficient, so it suits large volumes of data, but the key must be shared securely because anyone who has it can read the data. Example: AES.
Asymmetric cryptography (1.5 marks), or public-key cryptography, uses a pair of keys: a public key to encrypt and a private key to decrypt. No secret key has to be shared, and it provides digital signatures, but it is slower. Example: RSA.
| Symmetric | Asymmetric |
|---|---|
| One key | Two keys (public and private) |
| Same key encrypts and decrypts | Public key encrypts, private key decrypts |
| Fast; good for bulk data | Slower; good for key exchange and signatures |
| Key distribution is a problem | Easy key distribution |
Data normalization (1 mark)
Data normalization is a database design technique that divides data into smaller, related tables linked by keys, so that redundancy (duplicate data) is reduced and inconsistencies during insertion, update and deletion are avoided.
Two forms (1 + 1 marks)
- First normal form (1NF): every cell holds a single (atomic) value; repeating groups and multi-valued cells are removed.
- Second normal form (2NF): the table is in 1NF and every non-key attribute depends on the whole primary key (no partial dependency).
- (Also: Third normal form (3NF): the table is in 2NF and no non-key attribute depends on another non-key attribute, that is, no transitive dependency.)
Time complexity measures how the execution time of an algorithm grows with the size of its input . It is found by counting the basic steps (comparisons, assignments) and is written in Big O notation. Example: linear search is , binary search is .
Space complexity measures how much memory an algorithm uses with respect to the input size: extra variables, arrays and the recursion stack. Example: linear search needs only a few variables, ; recursive binary search uses stack space.
So time complexity judges a solution by speed, and space complexity by memory; a good solution keeps both low, and sometimes one is traded for the other (merge sort is faster than bubble sort but uses extra memory).
Two-factor authentication (2FA) requires users to prove their identity with two different forms of identification, usually a password (something you know) and a one-time code sent to their phone (something you have).
Security (1.5): even if an attacker steals or guesses the password, for example through phishing or a data leak, they cannot log in without the second factor on the user's phone. This adds an extra layer of protection against unauthorised access.
Privacy (1.5): because only the genuine user can open the account, personal emails, messages, photos and financial details stay private. The user is also alerted by an unexpected code when someone tries to use their password. Example: when logging into email, a user enters the password and then a code received by SMS.
Two-factor authentication (2FA) requires two separate forms of identification from different categories: something you know (password, PIN), something you have (phone OTP, token, smart card) or something you are (fingerprint, face).
Security (1.5 marks)
A password alone can be guessed, phished or leaked in a data breach. With 2FA, if one factor is compromised the attacker still needs the second factor, for example the OTP on the user's own phone, so account takeover and fraud are blocked.
Privacy (1.5 marks)
Because only the real owner can log in, personal e-mails, photos, messages and bank details in the account stay private. Many services also alert the user when a login attempt fails the second step, so the user can change the password quickly.
A test-train split divides the dataset into two parts: training data, the main (larger) portion used to teach the model, and test data, the smaller portion kept aside and not shown during training, used to evaluate the model on unseen data.
A common ratio is 70:30 (or 80:20). For example, from 100,000 labelled images of cats, dogs and horses, 70,000 are used for training and 30,000 for testing. The ratio must be chosen wisely: with too little training data the model underfits, and (as the book states) with too much training data it overfits. The split gives an honest measure of real-world accuracy.
When accessibility is ignored, the system is not designed for users with visual, hearing, motor or cognitive impairments. The problems are:
- Exclusion of users: a large part of potential users cannot use the system at all. For example, blind users cannot understand images without alt text, and deaf users miss information in videos without captions or in apps that use only sound alerts.
- Poor user experience and more errors: small text and low-contrast colours make reading hard; mouse-only controls stop users with motor impairments.
- Loss for the organisation: fewer customers, damaged reputation and possible legal action for not meeting accessibility standards.
A queue is a FIFO (First-In, First-Out) data structure with two ends, front and rear.
- Enqueue
- Adds a new element at the end (rear, back or tail) of the queue. Before adding, the queue is checked with IsFull.
- Dequeue
- Removes the existing element from the start (front or head) of the queue, that is, the element that has waited longest. Before removing, IsEmpty is checked.
- Front
- Returns the element at the front of the queue without removing it, so we can see which item will be served next.
Example: queue [3, 4, 5]; enqueue(6) gives [3, 4, 5, 6]; dequeue() removes 3; front() now returns 4.
Advantage: array elements are stored in contiguous memory locations and identified by indexes, so any element can be reached directly (random access) in time. Arrays also need no extra memory (metadata or pointers) to store the elements, so they are efficient.
Types of arrays
- One-dimensional (1-D) array: elements of the same type stored in a single row; one index reaches an element, for example marks = [2, 4, 8, 12], marks[2] is 8.
- Two-dimensional (2-D) array: also called a matrix; elements stored in rows and columns; two indexes (row, column) reach an element, for example M[1][2].
Opening a file (1.5 marks)
A file is opened with the built-in function, which takes the file name (with path if needed) and the mode ("r" read, "w" write, "a" append, "rb"/"wb" binary). It returns a file object (file handler) used for all later operations: .
Closing a file (1.5 marks)
The file is closed with , which saves all data to the disk and frees the memory used by the file. Alternatively the statement opens the file and closes it automatically when the block ends, even if an error occurs.
f = open("marks.txt", "w") # open: returns a file object
f.write("Ali 85\n")
f.close() # close: saves data, frees memory
with open("marks.txt", "r") as f: # opened here ...
print(f.read(), end="")
# ... and closed automatically hereAli 85Identity theft (2 marks)
Identity theft happens when someone uses your personal details, such as your name, CNIC number, bank account or credit card information, without permission to commit fraud. Thieves get these details through phishing, data breaches, lost or stolen items and online scams.
Why it is harmful (1 mark)
The thief can withdraw money, shop, take loans or open accounts and SIMs in the victim's name. This causes financial loss, harms the victim's reputation and credit record, and can take a long time and legal effort to correct.
A/B testing (split testing) compares two versions of a website, A and B, by showing each version randomly to different users and measuring which performs better.
How it improves usability: it measures real users' behaviour, such as task completion, clicks, time taken, errors and sales, instead of relying on guesses. The version that users find easier and more effective is kept, and the process can be repeated for buttons, menus and page layouts, so the site improves step by step based on evidence.
Example: an online retailer shows two homepage layouts to random halves of its visitors; by comparing sales and engagement it keeps the layout that is more effective.
Caesar cipher (2 marks)
The Caesar cipher is a simple and very old substitution cipher. Each letter of the plaintext is shifted by a fixed number of positions (the key) in the alphabet, wrapping round after Z. To decrypt, the letters are shifted back by the same number.
Example (1 mark)
With key : A becomes D, B becomes E, so HELLO is encrypted as KHOOR. It is easy to break because there are only 25 possible shifts.
Feature engineering is selecting and transforming the most relevant data features to improve a model's performance. It is important because:
- Improves accuracy: relevant features (size, colour, ear and eye shape of animals) make the pattern easy to learn, so predictions are more correct; a sitting horse is not confused with a big standing dog.
- Removes noise and reduces overfitting: dropping irrelevant features stops the model learning useless details.
- Makes training faster and data usable: fewer, cleaner features need less computation, and transforming data (normalising values, encoding categories as numbers) puts it into a form the algorithm can use.
Use of digital tools (2 marks)
Digital tools present the same research in forms that suit different audiences. Visuals (charts in Excel or Tableau, infographics in Canva or Piktochart) simplify large data; videos explain processes with narration and animation; interactive elements (dashboards, clickable Prezi presentations, hyperlinks) let users explore the data themselves. Collaboration tools such as Google Drive let the audience comment and share. This makes complex topics clear to experts and non-experts alike.
Example (1 mark)
A study on energy use in office buildings can be shown as an interactive Power BI dashboard where each user selects a city to see its energy consumption, together with a short infographic for the general public.
Robotics is the branch of computer science and engineering that designs, builds and operates robots. Deep learning is heavily used to build robots that perform specific tasks with little or no human intervention.
- Sensing: a robot has sensors, cameras and microphones. Deep neural networks with many hidden layers process these images and sounds to recognize objects, people, speech and obstacles.
- Learning: the network is trained on huge data sets (by feedforward and backpropagation) so the robot learns tasks such as picking, sorting or moving, and improves as more data is given.
- Acting: the computer that controls the robot uses the network's output to decide and act, for example in manufacturing, moving goods in warehouses, packaging medicine, performing operations, handling hazardous material or working in extreme temperature.
Concept of Blockchain (2 marks)
Blockchain is a distributed ledger (database) of records or transactions shared among many network users. The ledger keeps growing as new records, called blocks, are added. Blocks are chained together using cryptography: each block stores the hash of the previous block, so changing one block breaks the chain. Once data is recorded it cannot be changed (immutability). This increases security against fraud, increases transparency and reduces vulnerability to cyber attacks.
One application (1 mark)
Voting: each vote is recorded on the transparent, immutable ledger, so rigging and manipulation are prevented and voters trust that their vote is counted and the result is accurate. (Other acceptable applications: banking, healthcare records, verification of degrees.)
They are measures of central tendency, which describe the typical value of a dataset. Example data: 2, 3, 3, 5, 7.
- Mean: the average value: the sum of all values divided by their number, .
- Median: the middle value when the data is arranged in order. Here the 3rd of 5 values is 3. (For an even number of values, take the average of the two middle values.)
- Mode: the most frequent value in the data. Here 3 occurs twice, so the mode is 3.
Air pollution from industries, vehicles and homes causes heart disease, lung cancer and eye irritation in Pakistan's cities. IoT helps control it for three reasons:
- Real-time monitoring: IoT sensors across the city measure pollutants such as and plus temperature and humidity, and send the data wirelessly to the cloud.
- Forecasting and trends: the cloud processes the data with machine learning to calculate the Air Quality Index, show trends and forecast pollution.
- Quick, intelligent response: when pollution exceeds a limit, alerts reach authorities and citizens, so polluting sources can be controlled and people protected in time.
Method: User-Centred Design (UCD). UCD is a design philosophy that places the end users at the core of the design process. It is iterative: user feedback is continuously gathered and integrated throughout the development cycle (understand users, design, build a prototype, test with users, and repeat). This makes the final product match users' needs, preferences and limitations, giving a more effective and satisfying experience.
Example: while developing educational software for schools, developers involve teachers and students from the beginning. Early testing shows that students prefer interactive quizzes over static reading material, so the design is changed, improving engagement and learning.
1. Interface issues (2.5 marks)
Poorly designed interfaces are among the most common HCI problems. The interface is the main way users interact with a system, so untidy layouts and unclear navigation paths make important features hard to find. This leads to confusion, inefficiency and more errors, and users may abandon the system.
Example: an e-commerce website has a crowded navigation menu with too many options. A user looking for electronics must search through a long list of unrelated categories and becomes frustrated. Solution: simplify the interface and group options into clear categories.
2. Performance issues (2.5 marks)
Slow or unresponsive systems severely reduce usability. Users expect quick responses, and delays cause frustration and lower productivity. Causes include poor system optimisation, excessive resource use and network latency. When content loads slowly, users abandon tasks or switch to alternatives.
Example: an online banking app takes too long to load account information or to process a transaction and shows "Payment failed, retry payment". Users become impatient, worry about the safety of their money and stop using the app. Solution: optimise images and code and compress files to reduce load time.
Primary purpose of an MVP (2 marks)
A Minimum Viable Product (MVP) is the simplest version of a product that includes only the essential features needed to solve the core problem of the target audience. In the Lean Start-Up approach its primary purpose is to test the business idea and its key assumptions with real users quickly and at low cost, collect feedback and data, and learn what to build next before investing in a full product. Example: Dropbox's demo video attracted thousands of sign-ups and proved demand.
Rapid development (1.5 marks)
The MVP is built quickly with agile methods in short sprints (often with low-code tools). This brings the product to users early, so feedback arrives sooner and less money is spent before the idea is validated. Agile work is flexible, so the team can respond to changing requirements and feedback, and a competitor has less time to enter the market first.
Testing (1.5 marks)
The MVP is continuously tested with real users (beta tests, user testing sessions, in-app surveys). Testing validates or rejects assumptions, uncovers bugs and usability problems, and shows which features users value. The team iterates on these insights, so each version fits user needs better, which increases retention and the chance of success.
Together, rapid development and testing form the Build-Measure-Learn loop: build fast, measure with users, learn and improve.
Process of hypothesis formulation (2 marks)
Hypothesis formulation is making an educated guess or assumption about a relationship between variables, based on existing data or prior knowledge. It is the starting point for investigating how certain factors might influence an outcome.
- Identify the research problem or question from observation or previous studies (literature review).
- Identify the independent variable (possible cause) and the dependent variable (effect).
- State the expected relationship as a clear, testable statement, for example "Increased study hours lead to better exam scores." This proposes a cause-and-effect relationship.
- Write it as a pair: null hypothesis and alternative hypothesis , ready for hypothesis testing with data.
Role of null and alternative hypotheses (3 marks)
- **Null hypothesis ():** states there is no effect or relationship; any difference is due to random chance. It is the default assumption that is tested and challenged.
- **Alternative hypothesis ():** states there is a significant effect or relationship. It is what the researcher wants to show.
- Role: they make the question testable and define what counts as evidence. Data is collected and a p-value is found. If p-value (0.05), is rejected and is supported; otherwise we fail to reject .
Example
- Question: Does drinking coffee improve cognitive function in students?
- : drinking coffee has no effect on cognitive function. : drinking coffee improves cognitive function.
- Researchers compare students' cognitive function with and without coffee.
- If the data shows a significant improvement, is rejected and supported: coffee has a positive effect on cognitive function.
Tree traversal means visiting every node of a tree exactly once in a systematic order. For a binary tree the methods differ in when the root is visited.
Pre-order traversal (2.5 marks)
- 1. Visit the root node.
- 2. Traverse the left subtree in pre-order.
- 3. Traverse the right subtree in pre-order.
Example: for the tree shown, visit root 1, then the left subtree (2, then its children 4 and 5), then the right subtree (3, then 6). Order: 1, 2, 4, 5, 3, 6. Use: processing a node before its children, such as copying a tree or printing a folder before its contents.
Post-order traversal (2.5 marks)
- 1. Traverse the left subtree in post-order.
- 2. Traverse the right subtree in post-order.
- 3. Visit the root node.
Example: for the same tree, finish the left subtree (4, 5, then 2), then the right subtree (6, then 3), and visit the root 1 last. Order: 4, 5, 2, 6, 3, 1. Use: deleting nodes or freeing memory, because children are processed before their parent.
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
def preorder(n): return [n.key] + preorder(n.left) + preorder(n.right) if n else []
def postorder(n): return postorder(n.left) + postorder(n.right) + [n.key] if n else []
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print("Pre-order: ", preorder(root))
print("Post-order:", postorder(root))Pre-order: [1, 2, 4, 5, 3, 6]
Post-order: [4, 5, 2, 6, 3, 1]IoT in the healthcare sector (2.5 marks)
IoT combined with AI has created the Internet of Medical Things (IoMT). It improves doctors' productivity and hospital workflow.
- Patients' data is saved in the cloud, where machine learning finds patterns to diagnose disease and recommend medicines or tests.
- IoT devices track blood pressure, heart rate and oxygen level in real time.
- Smart wearables allow remote patient monitoring at home, saving hospital visits, time and money.
- Smart beds observe vital signs and alert nurses when urgent care is needed.
- Smart ambulances send the patient's critical data to the hospital during transport so treatment starts on the way.
IoT in traffic management systems (2.5 marks)
Traffic congestion in big cities wastes fuel and time, so a smart traffic management system is needed.
- Sensors at traffic lights, roads and highways collect real-time traffic data and send it wirelessly to traffic control rooms.
- Traffic flow is optimized, reducing congestion, improving road safety and lowering accident risk.
- Drivers get real-time information about road conditions, congested areas and hazards.
- RFID tags on cars open gated entrances automatically, saving time.
- Surveillance cameras capture images of traffic rule violators for action by authorities.
DDoS attack (2.5 marks)
In a Distributed Denial of Service (DDoS) attack, the attacker takes control of many infected computers (a botnet) and makes them all send a flood of traffic or requests to one website or system at the same time. The target's bandwidth and processing power are used up, so it becomes very slow or completely unavailable to regular users.
- Threat to organizations: online banking, shopping or government portals go offline; the organization loses money, customers and reputation.
- Threat to individuals: users cannot reach services they need; the infected home computers used in the botnet are themselves compromised.
- Protection: firewalls and traffic filtering, extra server capacity and DDoS protection services.
Ransomware (2.5 marks)
Ransomware is malicious software that locks or encrypts the victim's files so they cannot be opened, and then the attackers demand money (a ransom), often in cryptocurrency, to unlock or decrypt them. It usually enters through phishing e-mail attachments, infected downloads or unpatched software.
- Threat to security: important files and whole systems become unusable; hospitals, businesses and schools stop working.
- Threat to privacy: many attackers also steal the data and threaten to publish it.
- Paying the ransom does not guarantee the files will be returned.
- Protection: regular offline backups, updates and patches, anti-malware tools, and not opening unknown attachments.
Functional programming (1 mark)
Functional programming is a programming paradigm in which the program is divided into functions according to their functionality. The solution is broken into segments and each segment is handled by a function. The programmer focuses on what is to be computed rather than how, and functions return results without changing data outside themselves (no change of state, no side effects). Python supports this style with functions, , and lambda.
def square(n):
return n * n
print(list(map(square, [1, 2, 3, 4])))[1, 4, 9, 16]Two pros (2 marks)
- Simpler, concise code that is easy to debug: each function does one job, so its logic is easy to follow and an error is traced to one function; a change affects only that function.
- Easy to test and suited to parallel work: a function's result depends only on its inputs, so it is tested on its own; because state is not shared and changed, functions can run in parallel (concurrently).
Two cons (2 marks)
- Not easy for beginners: thinking in functions without changing variables needs practice, and complex algorithms may need higher-order functions that are hard to express.
- Overhead and lower performance: creating new data instead of changing existing data costs extra memory and time, especially with large data structures, so it may be less efficient in performance-critical programs.
How a neural network is trained (1 mark)
A neural network is not given rules. It learns from a set of input data with known correct outputs by repeating two processes, feedforward propagation and backpropagation, until the difference between predicted and actual output (the loss) is minimum. After training it can predict outputs for new data it has never seen.
Feedforward propagation (2 marks)
Information moves in the forward direction: from the input layer, through the hidden layers, to the output layer. Each neuron computes the weighted sum of its inputs plus bias and applies the activation function. Only neurons whose output is above a threshold pass their value to the next layer. The output layer finally produces the predicted result.
Backpropagation (2 marks)
The predicted output is compared with the actual output using the loss function, which tells how well the network is performing. To minimize the loss, the weights (and biases) are modified working backward from the output layer, through the hidden layers, to the input layer. This reduces the difference between actual and predicted output, so the network performs better after each cycle.
Set D
- AConfidentiality
- BEffectivenessAnswer
- CEncryption
- DAvailability
The key aspects of usability are effectiveness, efficiency and satisfaction. Confidentiality and availability belong to the CIA triad of security, and encryption is a security method.
- ASegmentation of code into functions
- BEncapsulation, Abstraction, InheritanceAnswer
- CEmphasis on program flow only
- DWriting code without using objects
Encapsulation, abstraction and inheritance (with polymorphism) are the pillars of OOP. Dividing code into functions is the functional/procedural idea, and OOP is built on objects.
- AEthics
- BCost
- CEfficiency
- DPrivacyAnswer
The book defines privacy as ensuring that users' personal data is handled responsibly and securely. Ethics is about respecting user rights through transparent and fair practices.
- AThe first nodeAnswer
- BNULL
- CThe previous node
- DThe middle node
In a circular linked list the last node's next pointer goes back to the first node, forming a loop; only non-circular lists end with NULL.
- ALevel-order
- BPost-order
- CIn-orderAnswer
- DPre-order
Left, Root, Right is in-order traversal. Pre-order is Root, Left, Right and post-order is Left, Right, Root; level-order visits level by level.
- AStrong evidence against Answer
- BWeak evidence against
- CResults due to chance
- DNull hypothesis is always accepted
A low p-value means the result is unlikely to be due to chance, which is strong evidence against the null hypothesis . A high p-value gives weak evidence.
- AFixed instructions only
- BManual data organizing
- CLearn from data to decideAnswer
- DStore data in databases
Machine learning is a method in which computers learn from existing data to make new decisions. Fixed instructions only (A) describes a rule-based algorithm.
- AInput layerAnswer
- BHidden layer
- CNetwork layer
- DOutput layer
Each neuron of the input layer receives raw data from the outside world and passes it to the hidden layer. \"Network layer\" is not a layer of a neural network.
- ABoth require full transparency
- BBoth demand maximum collection
- CNeither affects stakeholders
- DSharing needs openness, privacy needs limitsAnswer
Data sharing needs data to be open and available to many users, while privacy needs limits on who can access personal data and for what purpose. So they have conflicting requirements. The other options are false: neither requires full transparency or maximum collection, and both affect stakeholders.
- ATo store large data
- BTo compress files
- CTo secure communicationAnswer
- DTo build websites
Security protocols are rules and procedures that protect data and communication on networks from unauthorized access, tampering and interception, so their purpose is to secure communication.
- ATableau
- BMicrosoft WordAnswer
- CPrezi
- DPowerPoint
Text-based tools such as Microsoft Word or Google Docs are used for writing detailed research reports with explanations, references and citations. Tableau is for data visualisation; Prezi and PowerPoint are for presentations.
- ALearnability
- BEfficiency
- CMemorability
- DConfidentialityAnswer
The components of usability in HCI are learnability, efficiency, memorability, error handling and satisfaction. Confidentiality is a security principle.
- ATesting
- BScalability
- CUser Onboarding
- DSimplicityAnswer
Under Simplicity the book says: keep the MVP as simple and lean as possible, avoid feature creep and deliver a streamlined user experience.
Usability is how easily, efficiently and satisfactorily users can interact with a device or system to achieve their goals. In HCI it is the extent to which a system can be used by specific users to achieve specified goals effectively. A system with high usability is easy to learn, simple to use and matches users' expectations.
It has three key aspects: effectiveness (users can complete their tasks), efficiency (tasks are done quickly with minimal effort) and satisfaction (users feel comfortable and positive).
Example: Google's homepage shows only a search box, so anyone can search immediately without confusion.
A queue is a FIFO (First-In, First-Out) data structure: elements join at the rear and leave from the front. Three of its operations are:
- Enqueue
- Adds a new element at the end (rear) of the queue, for example enqueue(9) on [3, 4, 5] gives [3, 4, 5, 9].
- Dequeue
- Removes the element at the start (front) of the queue; on [3, 4, 5, 9] it removes 3.
- Front
- Returns the front element without removing it.
Other operations are IsEmpty (checks whether the queue has no elements) and IsFull (checks whether a fixed-size queue is full).
An array is the simplest data structure: a collection of elements of the same type stored in contiguous memory locations. Each element is identified by an index (starting from 0), so any element can be accessed directly. Its size is fixed when it is declared.
Example: marks = [2, 4, 8, 12, 16, 18] is a 1-D array of 6 integers. marks[0] is 2 and marks[3] is 12. If the array starts at address 100 and each element takes 1 unit, marks[3] is at address 100 + 3 = 103. A 2-D array (matrix) such as M[4][5] needs two indexes, row and column.
Symmetric cryptography (1.5 marks) uses one shared secret key for both encryption and decryption. It is fast and efficient, so it suits large volumes of data, but the key must be shared securely because anyone who has it can read the data. Example: AES.
Asymmetric cryptography (1.5 marks), or public-key cryptography, uses a pair of keys: a public key to encrypt and a private key to decrypt. No secret key has to be shared, and it provides digital signatures, but it is slower. Example: RSA.
| Symmetric | Asymmetric |
|---|---|
| One key | Two keys (public and private) |
| Same key encrypts and decrypts | Public key encrypts, private key decrypts |
| Fast; good for bulk data | Slower; good for key exchange and signatures |
| Key distribution is a problem | Easy key distribution |
| Supervised learning | Unsupervised learning |
|---|---|
| Model is trained on labelled data: the correct output is given for each input. | Data is unlabelled: no correct outputs are given. |
| Learns to predict the label or value for new inputs. | Finds hidden patterns or groups on its own. |
| Used for classification and regression. | Used for clustering. |
| Example: Linear Regression to predict prices or temperatures; classifying emails as spam. | Example: K-Means Clustering for customer segmentation. |
Enhances security: encryption converts data into a format that can be read only with a decryption key. Even if the data is stolen or intercepted during transmission, the attacker cannot read or misuse it, so confidentiality is protected.
Reduces usability: encrypting and decrypting takes processing time, so data access and processing can become slower. Managing encryption keys is complex and time-consuming, and a lost key can make data unreadable.
Example: a hospital encrypts patient records. The records are secure, but access may be slow, which can be a problem during an emergency when doctors need information immediately.
| Null hypothesis | Alternative hypothesis |
|---|---|
| States there is no effect or relationship between the variables. | States there is a significant effect or relationship. |
| Assumes observed differences are due to random chance. | Assumes differences are due to a real factor. |
| Default assumption that is tested; it is rejected or not rejected. | What the researcher wants to prove; supported when is rejected. |
| Example: drinking coffee has no effect on cognitive function. | Example: drinking coffee improves cognitive function. |
Sharing private information online makes identity theft (misuse of personal details for fraud) more likely. Three primary risks (1 mark each):
- Phishing: scammers send fraudulent emails, texts or messages that look as if they come from trusted organizations and ask for passwords or financial details, which are then misused.
- Data breaches: when an organization or website we shared data with is attacked, our personal data is leaked with its customer records and can be used by identity thieves.
- Online scams: fake websites or advertisements fool people into giving personal information or paying money to the wrong places.
(Lost or stolen devices and documents containing personal information are a further risk.)
Error handling is the system's ability to prevent errors, guide users in correcting them and help them recover from mistakes. It improves trust and satisfaction because:
- Prevention: real-time validation, autofill and confirmations ("Save changes before closing?") stop mistakes and data loss, so users feel safe using the system.
- Clear guidance: instead of letting users continue with faulty data, the system highlights the wrong field in red and explains what to fix, for example "Please enter a valid email address". Users are not left confused.
- Easy recovery: undo options and saved progress let users recover quickly and confidently. When things go wrong and the system still helps, users trust it and are satisfied.
Example: an airline booking site flags an invalid date or blank required field before payment.
Definition (2 marks)
Security protocols are sets of rules and procedures used to protect data and communication on networks. They keep sensitive information, such as passwords, private and safe from unauthorized access, verify user identities (authentication) and make sure data remains unchanged during transmission (integrity), mainly by using encryption.
Example (1 mark)
HTTPS (Hypertext Transfer Protocol Secure) encrypts data between a web browser and a website using SSL/TLS, for example when logging in to online banking. (Other examples: SSL/TLS, SSH, IPsec, SFTP.)
Concept (2 marks)
A primary key is a field, or a minimal set of fields, whose value uniquely identifies each record in a table. Its value can never be repeated and can never be empty (NULL), and each table has only one primary key. It is chosen from the candidate keys, and other tables link to the record through it as a foreign key. It prevents duplicate records and makes searching fast.
Example (1 mark)
In the Customer table, is the primary key: C1, C2 and C3 each identify exactly one customer, although two customers may have the same name.
| C_ID (primary key) | C_Name | C_Phone |
|---|---|---|
| C1 | Qamar | 123-4567 |
| C2 | Mahtab | 987-6543 |
| C3 | Chaand | 543-2109 |
CREATE TABLE Customer (C_ID TEXT PRIMARY KEY, C_Name TEXT, C_Phone TEXT);Overfitting (1.5): the model learns the training data too well, including its noise and irrelevant details. It performs very well on training data but poorly on new, unseen data, because it has become too specific to the training set. Example: a student who memorises past papers word for word fails when questions change.
Underfitting (1.5): the model is too simple and fails to capture the underlying pattern in the data. It performs poorly on both training data and new data, because it has not learned enough. Example: fitting a flat line to data that clearly rises.
The goal is to implement effective security within budget; cost decides the scope and scale of the measures. Three points:
- Budgets are limited, especially for home users and small businesses. Freemium security software, such as Avast's free antivirus, gives essential protection without high costs.
- Cloud-based security reduces upfront costs. A small business can use a cloud firewall such as Cloudflare instead of buying and maintaining its own expensive hardware.
- Open source solutions are cost-effective. Tools such as those from OWASP give robust security features without large financial investment, reducing the need for expensive commercial software.
Role (1.5): the p-value measures how likely the results are due to chance if is true. A low p-value is strong evidence against ; a high p-value is weak evidence. It is compared with the significance level : if p-value , reject (significant result); otherwise fail to reject it.
Examples (1.5): (1) Exercise for six weeks reduced blood pressure by 8 mmHg with p-value 0.005, below 0.05, so is rejected: exercise likely lowers blood pressure. (2) Fertilized plants grew taller; a p-value of 0.5 would mean the difference could easily be random, so the fertilizer may have had no real effect.
- Screen readers: tools such as JAWS, NVDA or VoiceOver read text and describe images (through alt text) aloud or in braille, so blind users can navigate websites, read messages and use apps independently.
- High contrast modes: themes in Windows, macOS and websites such as BBC make text stand out against the background, so low-vision and colour-blind users can read easily.
- Zoom and text enlargement: built-in zoom in Chrome and Firefox magnifies text and images, and large-button designs (such as TV remotes for the elderly) are easier to see and press.
These features make the system perceivable, so visually impaired users complete tasks effectively and with less effort.
An algorithm is correct if it produces the expected output for all valid inputs. Correctness is checked by running the algorithm on many test cases covering different situations, including edge cases such as an empty list, a single element, repeated values or negative numbers. If it always gives the expected result, it is considered correct.
Example: bubble sort on the unsorted array [5, 2, 9, 1, 5, 6] must give [1, 2, 5, 5, 6, 9], and it must also work for [] and [7]. Similarly, binary search on the sorted array [1, 2, 3, 4, 5] with key 3 must return index 2, and for a missing key such as 6.
| Singly linked list | Doubly linked list |
|---|---|
| Each node has 2 parts: data and next. | Each node has 3 parts: prev, data and next. |
| Traversal in one direction only (forward). | Traversal in both directions (forward and backward). |
| Less memory per node (one pointer). | More memory per node (two pointers). |
| Last node's next is NULL. | First node's prev and last node's next are NULL. |
Example: singly: head → [A|next] → [B|next] → [C|NULL]. Doubly: NULL ← [prev|1|next] ⇄ [prev|2|next] ⇄ [prev|3|next] → NULL. A browser's back and forward buttons suit a doubly linked list, since we move both ways.
- Not easy for beginners: it needs practice to solve problems only with functions and without changing variables.
- Overhead with large data: because data is not changed in place, new copies are created, which uses extra memory and time when handling large data structures; it may be less efficient in performance-critical tasks.
- Complex algorithms are harder to express: they often need higher-order functions (functions that take or return functions), and sharing data between functions needs careful handling and synchronisation.
Ransomware (1.5 marks) is malicious software that locks or encrypts the victim's files so they cannot be accessed, and then demands money (a ransom) to unlock them. It announces itself with a ransom message.
Spyware (1.5 marks) is harmful software that secretly collects information about the user without their knowledge, such as keystrokes, screenshots and browsing activity, and sends it to a remote attacker. It tries to stay hidden.
| Ransomware | Spyware |
|---|---|
| Aim: extort money | Aim: steal information |
| Visible: shows a ransom demand | Hidden: user is unaware |
| Mainly harms availability of data | Mainly harms privacy |
| Defence: offline backups, updates | Defence: anti-malware scans, trusted apps only |
A stack is a LIFO (Last-In, First-Out) structure in which all operations take place at the top.
- Push
- Adds a new element at the top of the stack (after checking IsFull to avoid overflow).
- Pop
- Removes the existing element from the top of the stack and returns it (after checking IsEmpty to avoid underflow).
- Top
- Returns the top element without removing it, so we can see the most recently added item.
Example: push(A), push(B), push(C) gives [A, B, C]; top() returns C; pop() removes C, leaving [A, B].
To find the sum of the numbers (digits) in a list of elements, we set total = 0 and add each element once in a loop.
digits = [4, 0, 9, 6]
total = 0
for d in digits: # the loop runs n times
total += d
print("Sum =", total)Sum = 19- **Time complexity: .** Each of the elements is visited and added once, so the number of steps grows linearly with the length of the list.
- **Space complexity: .** Only one extra variable (total) and a loop variable are used, whatever the size of the list.
(For the book's version, the sum of the digits of one integer with digits, time is , that is for the number , and space is again .)
| Text file | Binary file |
|---|---|
| Stores data as readable characters (ASCII/Unicode). | Stores data as raw bytes (0s and 1s), the same form as in memory. |
| Each line ends with an end-of-line marker (); characters may be translated when read or written. | No end-of-line marker and no translation; bytes are stored exactly. |
| Can be read and edited by a person in any text editor. | Cannot be read by a person; needs the program that created it. |
| Usually larger for numbers (12345 needs 5 characters). | Usually smaller and faster to read and write (an int takes 4 bytes). |
| Examples: .txt, .csv, .py | Examples: .jpg, .png, .mp3, .mp4, .exe |
Any three rows earn the three marks. In Python a text file is opened with "r"/"w" and a binary file with "rb"/"wb".
IoT combined with AI has produced the Internet of Medical Things (IoMT), which improves doctors' productivity and hospital workflow:
- Real-time tracking: IoT devices measure blood pressure, heart rate and oxygen level continuously; data saved in the cloud is analysed by machine learning to diagnose disease and suggest treatment.
- Remote patient monitoring: smart wearables let doctors monitor patients at home, saving visits, time and money.
- Smart beds and smart ambulances: smart beds alert nurses when a patient needs urgent attention; smart ambulances send the patient's critical data to the hospital so treatment starts during transport.
Neural networks learn from input data through feedforward propagation (followed by backpropagation). In feedforward propagation:
- Training data enters the input layer; each input neuron represents one feature.
- Information moves only in the forward direction through the hidden layers. Each neuron computes the weighted sum of its inputs plus its bias and applies the activation function; only neurons whose value exceeds a threshold pass their output to the next layer.
- The output layer produces the prediction. This prediction is compared with the actual output by the loss function, and backpropagation then adjusts the weights. Repeating the cycle trains the network.
Microsoft Word and Google Docs are text-based tools used to write and format detailed research reports and papers. They are important because:
- Detailed explanation: they allow long, organised text with headings for introduction, methodology, findings and conclusion.
- Referencing and citations: footnotes, reference lists and citation tools (with Zotero or EasyBib) credit sources in APA or MLA style, making the report credible.
- Tables, charts and formatting: findings can be shown with tables, inserted charts and consistent formatting.
- Sharing and collaboration: Google Docs lets several researchers edit and comment at the same time, and both can export to PDF for sharing.
Data storytelling (2): the use of visuals (charts, graphs) combined with a narrative to communicate insights from data. It makes data relatable, engaging and memorable, simplifies complex data, highlights key points and bridges the gap between data and decision-making.
Example (1): a school's average attendance is 85%, with 9th grade at 90% and 12th grade at 78%. The story of Jameel, a 12th-grader who misses 5 days, shown with a bar chart of the grades, persuades the school to apply the 9th grade's successful practices to the 12th grade.
Cloud computing (1 mark)
Cloud computing is the use of hosted services such as servers, data storage, databases, networking and software over the Internet. These services are maintained by a cloud service provider and are available on demand, so users can store data and software on the cloud and access them from anywhere with an Internet-connected device.
One application (2 marks)
Healthcare: hospitals keep patients' medical records on the cloud, so doctors can view, share and update them in real time and give better treatment based on the complete history. Telemedicine platforms on the cloud allow video consultation with patients who cannot travel, and patients can see their lab reports online. (Other acceptable applications: education through LMS, banking, business, transport e-ticketing, Netflix and YouTube, software development.)
Problem: accessibility challenges (2 marks). Many systems are not designed with accessibility in mind, because designers do not fully consider the needs of all users. As a result, people with visual, hearing, motor or cognitive impairments face barriers: they cannot perceive content, operate controls or understand instructions, so their experience is incomplete or impossible, and they are excluded.
Example (1 mark): a website without alternative text for images is inaccessible to blind users who rely on screen readers; they miss the information shown in the images. Similarly, an app that gives notifications only by sound is unusable for people with hearing impairments.
Efficiency (2.5 marks)
Efficiency is how quickly and effectively users can perform tasks once they have learnt to use the system. An efficient system lets users reach their goals with minimal time and effort.
Contribution: efficient systems increase productivity, reduce effort and frustration, and let expert users work at speed. Features such as shortcut keys, customisable toolbars, fewer steps per task and fast response times make the system effective for daily and professional use.
Example: a graphic designer using Adobe Photoshop edits images, creates layouts and applies filters quickly through shortcut keys, customisable toolbars and responsive tools.
Memorability (2.5 marks)
Memorability is how easily users can remember how to use a system after a period of not using it. A memorable system lets returning users perform key tasks without relearning the interface.
Contribution: high memorability saves time for occasional users, reduces errors and support requests, and makes users confident to return. It is achieved through consistent design patterns, clear labels and a logical flow of steps.
Example: a user who files taxes on a tax website once a year can easily recall how to navigate, fill out the forms and submit them months later, because the design is consistent and clearly labelled.
Tree traversal is the systematic visiting of every node of a tree exactly once. In a binary tree each node has a left and a right subtree, and the traversal methods differ in when the root is visited.
In-order traversal (2.5 marks)
- 1. Traverse the left subtree in in-order.
- 2. Visit the root node.
- 3. Traverse the right subtree in in-order.
Example: in the tree shown, first go to the leftmost node 4, then its parent 2, then 5; the left subtree is done, so visit root 1; then the right subtree gives 6, 3, 7. Order: 4, 2, 5, 1, 6, 3, 7. Use: in a binary search tree, in-order visits the keys in ascending (sorted) order.
Pre-order traversal (2.5 marks)
- 1. Visit the root node.
- 2. Traverse the left subtree in pre-order.
- 3. Traverse the right subtree in pre-order.
Example: visit root 1, then the left subtree (2, 4, 5), then the right subtree (3, 6, 7). Order: 1, 2, 4, 5, 3, 6, 7. Use: when a node must be processed before its children, for example copying a tree or listing a folder before the files inside it.
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
def inorder(n): return inorder(n.left) + [n.key] + inorder(n.right) if n else []
def preorder(n): return [n.key] + preorder(n.left) + preorder(n.right) if n else []
root = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6), Node(7)))
print("In-order: ", inorder(root))
print("Pre-order:", preorder(root))In-order: [4, 2, 5, 1, 6, 3, 7]
Pre-order: [1, 2, 4, 5, 3, 6, 7]A machine learning model learns from data to make decisions and improves as it gets more data. A rule-based algorithm follows fixed instructions written by people and changes only when the rules are updated.
Advantages of machine learning over rule-based algorithms (2.5)
- Handles complex and unstructured data such as images, audio and text, which cannot be described by simple rules.
- Learns patterns automatically without explicit programming of every rule and without expert intervention for each case.
- Adapts and improves as more data arrives (continuous learning), whereas rule-based systems need new rules for every new situation.
- Example: a spam filter learns new spam words; a fixed rule "subject contains lottery" misses new spam.
Limitations of machine learning compared with rule-based algorithms (2.5)
- Needs large datasets: it performs poorly when data is too little, while rule-based algorithms work with limited data.
- Hard to interpret: its decision-making is complex, while rules are easy to follow and explain.
- Needs significant computing resources, while rule-based systems are cheap and easy to implement.
- Risk of overfitting and bias: a too-complex model overfits, and biased training data gives wrong results; rule-based output is consistent for the same rules.
Deep learning (1 mark)
Deep learning (DL) is an AI technology, a specialized form of machine learning, that uses deep neural networks (neural networks with multiple hidden layers) to enable computers to autonomously extract hidden patterns and features from huge data sets for making decisions. It needs vast data, long training time and GPU-based computers, and its decisions improve as more data is given.
Application 1: Natural Language Processing (2 marks)
NLP allows machines to understand human language in the form of text and speech. DL-based NLP teaches computers and robots to give suitable responses to linguistic inputs. Widely used examples are language translators (such as Google Translate), sentiment analysis of reviews and customer-service chatbots.
Application 2: Self-driving car (2 marks)
A self-driving car is an autonomous vehicle based on DL that senses its environment and operates without a human driver. It uses data from cameras, sensors and geo-mapping to calculate distances to nearby objects, detect traffic lights, recognize road signs and avoid pedestrians. Tesla is an example. Such cars can help elderly and physically disabled people to travel.
Blockchain (1 mark)
Blockchain is a distributed ledger (database) of records or transactions shared among many network users. It grows as new records (blocks) are added, and the blocks are chained together using cryptography, which increases security against fraud and increases transparency. Once recorded, data cannot be changed.
Blockchain in the banking industry (2 marks)
Online banking has made transfers easy but exposed banks to data breaches and cyber threats, in Pakistan as elsewhere. Blockchain integrated with cyber security solves these problems:
- Every transaction is recorded permanently on a shared ledger that cannot be secretly altered, so financial fraud is eliminated.
- Operations become more secure and transparent.
- Transactions are processed efficiently and at lower cost, without many middle steps.
Blockchain in the education sector (2 marks)
Degrees, diplomas and certificates are kept manually, so verification is slow and fake credentials are used.
- Records on a distributed ledger make record-keeping efficient, secure and transparent and eliminate fake degrees.
- Verification by employers and universities becomes simple and quick.
- Students' academic records and administrative processes become more secure, and students get complete control of their certificates because they are saved on the Blockchain, not only on institutions' servers.
Two-factor authentication (2.5 marks)
2FA requires two separate forms of identification, from two different categories, before access to a system, account or app is given:
- something you know (password or PIN);
- something you have (smartphone OTP, token or smart card);
- something you are (fingerprint or face).
How it improves cybersecurity: passwords can be guessed, phished or leaked. With 2FA, if one factor is compromised the attacker still needs the second factor, so stolen passwords alone are useless. This blocks account takeover, identity theft and fraud, and alerts the user to login attempts. Example: bank login with password plus SMS code.
Biometric verification (2.5 marks)
Biometric verification confirms identity using unique physical or behavioral traits such as fingerprints, facial features, iris patterns, voice, or typing and walking patterns. The user gives a sample (fingerprint or face scan), and the system compares it with stored data; access is given only if they match.
- Hard to fake or share: traits are unique, so they cannot easily be guessed or stolen by phishing.
- Convenient: no password to remember, so users do not write passwords down or reuse weak ones.
- Strong second factor: combined with a password, it gives very strong 2FA.
- Limitation: it raises privacy concerns, because biometric data is sensitive and must be stored securely.
Using both methods together provides strong protection for accessing systems and data.
Object-oriented programming (1 mark)
OOP is a programming paradigm based on objects. A class is a template that defines attributes (data) and methods (functions); an object is an instance of a class that models a real-world thing such as a car or a bank account. The emphasis in problem solving is on objects rather than logic, and OOP uses encapsulation, abstraction, inheritance and polymorphism.
class Car:
def __init__(self, color):
self.color = color
def start(self):
return self.color + " car started"
c = Car("Red")
print(c.start())Red car startedTwo pros (2 marks)
- Reusability and simpler complex systems: a big system is broken into smaller reusable classes, and inheritance lets new classes reuse existing code.
- Security and maintainability: encapsulation hides implementation details and protects data from direct access, so code is safer and easier to maintain; objects also represent real-world things naturally.
Two cons (2 marks)
- Complex design: if not planned carefully, class hierarchies become complex, and inheritance can make the design rigid and less flexible.
- Harder to understand and not always efficient: encapsulation and polymorphism can make code harder to follow and debug, and OOP may not suit computationally intensive tasks.
Primary purpose of an MVP (2 marks)
A Minimum Viable Product (MVP) is the most basic version of a product with only the essential features that address the core problem or need of the target audience. Its primary purpose is to validate the business idea with real users at the lowest cost and time: early users try it, the team collects feedback and data, and then improves the product step by step. This keeps development customer-focused and reduces the risk of building something nobody wants.
Feature prioritization (1.5 marks)
Feature prioritization means identifying the core features absolutely necessary to solve the primary problem and give value to early users, and leaving others for later. It contributes to success because the MVP is launched faster and cheaper, users see the main value clearly, feature creep is avoided, and feedback focuses on what matters. Example: a tuition app launches with only tutor search and booking, leaving chat for later.
Scalability (1.5 marks)
Scalability means designing the MVP's architecture and technology so it can handle increased demand and future enhancements. It contributes to success because when the MVP gains traction the product can grow (more users, new features, new markets) without crashing or needing a complete rebuild. For example, using cloud servers and a scalable database lets the app serve thousands of users after a successful launch.
Old syllabus (Curriculum 2009)
int a = 5, b = 10, c;
c = a++ * --b;
cout << c;- A45Answer
- B50
- C54
- D60
is post-increment: the old value 5 is used, then a becomes 6. is pre-decrement: b becomes 9 before it is used. So .
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10, c;
c = a++ * --b;
cout << c << endl;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}45
a = 6, b = 9- A13
- B0
- C12Answer
- D11
Post-increment assigns the old value first (b = 12) and then increases a to 13.
#include <iostream>
using namespace std;
int main() {
int a = 12, b;
b = a++;
cout << "b = " << b << ", a = " << a << endl;
cout << "sizeof(float) = " << sizeof(float) << endl;
return 0;
}b = 12, a = 13
sizeof(float) = 4- A2
- B4Answer
- C6
- D8
A float is a single-precision real number stored in 4 bytes (32 bits); a double takes 8 bytes. The program in the previous question prints sizeof(float) = 4.
- AA[x++]
- BA[x]
- CA[7]
- DA[++x]Answer
Array indexes start at 0, so the seventh element is A[6]. increases x to 6 before it is used, giving A[6]. and use A[5] (sixth element) and A[7] is the eighth element.
#include <iostream>
using namespace std;
int main() {
int A[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int x = 5;
cout << A[++x] << endl; // x becomes 6 first: A[6] is the 7th element
return 0;
}70- AOne parameter
- BTwo parameters
- CThree parameters
- DAny number of parametersAnswer
A function may be defined with no parameters or with as many parameters as it needs; there is no fixed limit of one, two or three.
- A*Answer
- B&
- C**
- D&&
gives the value stored at the address held in pointer p. is the address-of (reference) operator and is logical AND.
- A&&
- B<=
- C%Answer
- D++
% (modulus) gives the remainder of a division and is one of the arithmetic operators + - * / %. && is logical, <= is relational and ++ is the increment (unary) operator.
- AProtected
- BPublic
- CPrivateAnswer
- DDefault
Members of a C++ class are private unless a specifier is written, which supports encapsulation. (In a struct the default is public.)
- ACommand
- BClassAnswer
- CObject
- DMethod
ofstream is a class of the fstream library for writing to files; we create an object of it, for example .
- Aget()
- Bfputs()
- Cfgets()
- Dput()Answer
writes a single character to an output stream (file). get() reads one character; fputs() and fgets() handle whole strings in C.
- (alert): produces a beep (bell) sound from the computer.
- (backspace): moves the cursor one position back, so the next character overwrites the previous one.
- (new line): moves the cursor to the beginning of the next line.
#include <iostream>
using namespace std;
int main() {
cout << "Line 1\nLine 2" << endl; // \n: new line
cout << "ABC\bD" << endl; // \b: backspace, D overwrites C on screen
cout << "\a" << "Beep!" << endl; // \a: alert (bell sound)
return 0;
}Line 1
Line 2
ABC<BS>D
Beep!- 2a: a variable name cannot start with a digit; it must start with a letter or an underscore.
- S$: special characters such as $ are not allowed; only letters, digits and the underscore may be used.
- Int: it looks like the reserved keyword int (data type), and keywords cannot be used as variable names.
Purpose (1 mark)
The break statement immediately ends the loop (for, while, do-while) or switch statement in which it appears; control passes to the first statement after that loop or switch. It is used to leave a loop early when a condition is met, such as when a searched item is found.
Syntax and example (2 marks)
break;#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5)
break; // leave the loop when i is 5
cout << i << " ";
}
cout << endl << "Loop ended";
return 0;
}1 2 3 4
Loop ended| Text file | Binary file |
|---|---|
| Stores data as readable characters (ASCII/Unicode). | Stores data as raw bytes (0s and 1s), the same form as in memory. |
| Each line ends with an end-of-line marker (); characters may be translated when read or written. | No end-of-line marker and no translation; bytes are stored exactly. |
| Can be read and edited by a person in any text editor. | Cannot be read by a person; needs the program that created it. |
| Usually larger for numbers (12345 needs 5 characters). | Usually smaller and faster to read and write (an int takes 4 bytes). |
| Examples: .txt, .csv, .py | Examples: .jpg, .png, .mp3, .mp4, .exe |
Any three rows give the three marks.
| Constructor | Destructor |
|---|---|
| Called automatically when an object is created. | Called automatically when an object is destroyed (goes out of scope). |
| Same name as the class: . | Same name with a tilde: . |
| Initialises data members; can take parameters and can be overloaded. | Releases resources; takes no parameters and cannot be overloaded (one per class). |
#include <iostream>
using namespace std;
class Demo {
public:
Demo() { cout << "Constructor called" << endl; }
~Demo() { cout << "Destructor called" << endl; }
};
int main() {
{
Demo d; // object created: constructor runs
cout << "Inside block" << endl;
} // object goes out of scope: destructor runs
cout << "After block" << endl;
return 0;
}Constructor called
Inside block
Destructor called
After blockIn Python the constructor is and the destructor is .
cout<<p;
cout<<*p;- prints the value of the pointer itself, which is a memory address (for example 0x7ffd5c2a), the address of the variable it points to.
- uses the dereference operator * and prints the value stored at that address, that is, the value of the variable p points to.
#include <iostream>
using namespace std;
int main() {
int n = 25;
int *p = &n; // p stores the address of n
cout << (p == &n) << endl; // cout << p would print this address, e.g. 0x7ffd...
cout << *p << endl; // value stored at that address
return 0;
}1
25Here the first line confirms that p holds the address of n (1 means true; printing p itself shows a different address on every run), and gives 25, the value of n.
A two-dimensional array stores values in rows and columns and is initialised with nested braces, one inner pair per row. Below, an int array holds marks of 2 students in 3 subjects and a float array holds temperatures.
#include <iostream>
using namespace std;
int main() {
int marks[2][3] = {{85, 90, 78}, {70, 88, 92}}; // integer 2D array
float temp[2][2] = {{30.5, 31.2}, {28.4, 29.9}}; // float 2D array
cout << "Marks:" << endl;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++)
cout << marks[r][c] << " ";
cout << endl;
}
cout << "Temperatures:" << endl;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 2; c++)
cout << temp[r][c] << " ";
cout << endl;
}
return 0;
}Marks:
85 90 78
70 88 92
Temperatures:
30.5 31.2
28.4 29.9 The nested for loops visit each row (outer loop) and each column (inner loop), just like a nested list in Python.
- I. is true (1) but is false (0); true && false is false, so A = 0.
- II. % has higher precedence than +, so and S = 13 + 1 = 14.
- III. means , so n = 20.
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 15, n = 10;
int A = (x > 0) && (y < 10);
int S = 13 + 21 % 4;
n *= 2;
cout << "A = " << A << endl << "S = " << S << endl << "n = " << n << endl;
return 0;
}A = 0
S = 14
n = 20Purpose (1 mark)
The if-else statement selects one of two blocks of code. If the condition is true, the if block runs; otherwise the else block runs. It is used for two-way decisions such as pass/fail or even/odd.
Syntax with example (2 marks)
if (condition)
{
// statements when condition is true
}
else
{
// statements when condition is false
}#include <iostream>
using namespace std;
int main() {
int marks = 72;
if (marks >= 40)
cout << "Pass";
else
cout << "Fail";
return 0;
}PassA class is a template or blueprint that defines the attributes (data members) and methods (member functions) of a type of thing. An object is an instance of a class: a real entity created from that template, with its own values of the attributes. The class is only a design and uses no memory for data; memory is allocated when objects are created. One class can create many objects, all with the same structure and functions but different data, just as many houses can be built from one map.
#include <iostream>
using namespace std;
class Box { // class: the design
public:
int length;
};
int main() {
Box b1, b2; // objects: real boxes made from the design
b1.length = 10;
b2.length = 25;
cout << b1.length << " " << b2.length << endl;
return 0;
}10 25Importance
Comments are notes in the source code that the compiler ignores. They explain what the code does and why, so the program is easier to read, understand, debug and modify later, by the same programmer or by others. They can also switch off a line temporarily during debugging.
Two types
| Single-line comment | Multi-line comment |
|---|---|
| Starts with // and ends at the end of that line. | Starts with /* and ends with */; may cover several lines. |
| Used for short notes beside a statement. | Used for longer descriptions, such as the purpose of a program or function. |
| \texttt{x = x + 1; // increase x} | \texttt{/* This program finds the average of marks */} |
In Python a single-line comment starts with #.
Concept (2 marks)
Inheritance is an OOP feature in which a new class (derived or child class) is created from an existing class (base or parent class). The derived class automatically gets the data members and functions of the base class and can add its own. It gives code reusability, reduces repetition and builds a hierarchy of classes (an "is-a" relationship).
Daily life example (1 mark)
A car is a vehicle. The Vehicle class has wheels and start(); the Car class inherits them and adds its own member, seats. Similarly, a child inherits features from its parents.
#include <iostream>
using namespace std;
class Vehicle { // base class
public:
int wheels;
void start() { cout << "Vehicle started" << endl; }
};
class Car : public Vehicle { // derived class
public:
int seats;
};
int main() {
Car c;
c.wheels = 4; // inherited member
c.seats = 5;
c.start(); // inherited function
cout << c.wheels << " wheels, " << c.seats << " seats" << endl;
return 0;
}Vehicle started
4 wheels, 5 seatschar c = 'A';
do
{
cout << c << "\t";
c = c + 2;
}
while (c <= 'K');c starts at 'A'. Each pass prints c followed by a tab and adds 2 to its ASCII code, so the letters are A, C, E, G, I, K. After K, c becomes 'M', which is greater than 'K', so the loop stops.
#include <iostream>
using namespace std;
int main() {
char c = 'A';
do
{
cout << c << "\t";
c = c + 2;
} while (c <= 'K');
return 0;
}A C E G I K | Pass | c printed | c after c + 2 | c <= 'K'? |
|---|---|---|---|
| 1 | A (65) | C (67) | yes |
| 2 | C | E | yes |
| 3 | E | G | yes |
| 4 | G | I | yes |
| 5 | I | K (75) | yes |
| 6 | K | M (77) | no: stop |
int x = 5;
do {
cout << x << " ";
x++;
} while (x < 8);The do-while loop runs its body first and tests the condition afterwards. x = 5 is printed and becomes 6; 6 < 8, so 6 is printed and x becomes 7; 7 < 8, so 7 is printed and x becomes 8; now 8 < 8 is false and the loop stops. Output: 5 6 7
#include <iostream>
using namespace std;
int main() {
int x = 5;
do {
cout << x << " ";
x++;
} while (x < 8);
return 0;
}5 6 7 cout<<(((num%2)==0)?"Even\n":"Odd\n");The conditional (ternary) operator \texttt{condition ? a : b} gives a if the condition is true and b otherwise. The same decision with if-else:
if ((num % 2) == 0)
cout << "Even\n";
else
cout << "Odd\n";Tested with num = 7:
#include <iostream>
using namespace std;
int main() {
int num = 7;
if ((num % 2) == 0)
cout << "Even\n";
else
cout << "Odd\n";
return 0;
}Odd| Constant | Variable |
|---|---|
| A named value that cannot change while the program runs. | A named memory location whose value can change during execution. |
| Declared with const and must be given a value at declaration. | May be given a value at declaration or later, and changed any number of times. |
| \texttt{const float PI = 3.14159;} | \texttt{int radius = 2; radius = 3;} |
#include <iostream>
using namespace std;
int main() {
const float PI = 3.14159; // constant: cannot be changed
int radius = 2; // variable: can be changed
radius = 3;
cout << PI * radius * radius << endl;
return 0;
}28.2743Trying \texttt{PI = 3;} gives a compile-time error.
Purpose (2 marks)
\texttt{sizeof()} is an operator (used like a function) that returns the number of bytes a data type, variable or array occupies in memory. It helps write portable programs, because sizes may differ between computers, and it is used to find the number of elements of an array: \texttt{sizeof(arr) / sizeof(arr[0])}.
Example (1 mark)
#include <iostream>
using namespace std;
int main() {
int marks[10];
cout << sizeof(int) << " " << sizeof(char) << " " << sizeof(double) << endl;
cout << sizeof(marks) << endl; // 10 elements x 4 bytes
return 0;
}4 1 8
40The reference (address-of) operator & gives the memory address of a variable, as in \texttt{int *p = \&n;}. The same symbol is used in a declaration to create a reference variable, another name (alias) for an existing variable; a change through the reference changes the original. References are used to pass arguments by reference so a function can change them.
#include <iostream>
using namespace std;
void addBonus(int &m) { // m is a reference (another name) for the argument
m = m + 5;
}
int main() {
int marks = 70;
int &r = marks; // r refers to marks
r = 80; // changes marks
addBonus(marks);
cout << marks << endl;
return 0;
}85r = 80 changes marks to 80, and addBonus() adds 5 through its reference parameter, giving 85.
| Point | Local variable | Static (local) variable |
|---|---|---|
| Scope | Only inside the function or block where it is declared. | Also only inside its function or block. |
| Lifetime | Created when the function is called and destroyed when it returns; the value is lost. | Created once and exists until the program ends; keeps its value between calls. |
| Storage duration / initialisation | Automatic storage (stack); has garbage value unless initialised; initialised on every call. | Static storage; initialised only once (to 0 by default). |
#include <iostream>
using namespace std;
void counter() {
int local = 0; // created again on every call
static int total = 0; // created once, keeps its value between calls
local++;
total++;
cout << "local = " << local << ", static = " << total << endl;
}
int main() {
counter();
counter();
counter();
return 0;
}local = 1, static = 1
local = 1, static = 2
local = 1, static = 3| Actual parameters (arguments) | Formal parameters |
|---|---|
| Written in the function call. | Written in the function header (definition). |
| Can be constants, variables or expressions: sum(x, y), sum(4, 6). | Must be variables with data types: int a, int b. |
| Belong to the calling function. | Local to the called function; created when it is called and receive copies (or references) of the actual values. |
#include <iostream>
using namespace std;
int sum(int a, int b) { // a and b: formal parameters
return a + b;
}
int main() {
int x = 4, y = 6;
cout << sum(x, y) << endl; // x and y: actual parameters (arguments)
return 0;
}10int a (10), i;
cout>>"enter ten numbers";
for(i=0; i<10; i--)
cin << a(i);- \texttt{int a (10)} declares one integer initialised to 10, not an array: use square brackets \texttt{int a[10]}.
- cout uses the insertion operator <<, not >>.
- \texttt{i--} makes i go 0, -1, -2, ... so the loop never ends: use \texttt{i++}.
- cin uses the extraction operator >>, and array elements are written with square brackets: \texttt{cin >> a[i];}.
int a[10], i;
cout << "enter ten numbers";
for (i = 0; i < 10; i++)
cin >> a[i];#include <iostream>
using namespace std;
int main() {
int a[10], i;
cout << "enter ten numbers";
for (i = 0; i < 10; i++)
cin >> a[i];
cout << endl << "First: " << a[0] << ", last: " << a[9] << endl;
return 0;
}enter ten numbers
First: 1, last: 10| Array | String |
|---|---|
| A collection of elements of the same data type (int, float, char and so on) in consecutive memory. | A sequence of characters used to store text. |
| Has no end marker; its size is fixed when declared. | A C-string is a char array that ends with the null character \texttt{'\textbackslash 0'}; the string class manages its own length. |
| Processed element by element with a loop. | Has ready-made operations: length(), joining with +, comparison. |
| \texttt{int marks[3] = \{80, 75, 90\};} | \texttt{string name = "Ayesha";} |
#include <iostream>
#include <string>
using namespace std;
int main() {
int marks[3] = {80, 75, 90}; // array: many values of one type
string name = "Ayesha"; // string: sequence of characters
char city[] = "Lahore"; // C-string: char array ending in '\0'
cout << marks[1] << " " << name.length() << " " << sizeof(city) << endl;
return 0;
}75 6 7sizeof(city) is 7: six letters of Lahore plus the null character.
The class has public data members rollNo, name and marks, and the public member function get() that inputs them; show() displays them. Because the members are public, they can also be used directly from main().
#include <iostream>
#include <string>
using namespace std;
class Student {
public: // public data members
int rollNo;
string name;
float marks;
void get() { // member function to input the data
cin >> rollNo >> name >> marks;
}
void show() {
cout << rollNo << " " << name << " " << marks << endl;
}
};
int main() {
Student s; // object of class Student
s.get();
s.show();
return 0;
}12 Hina 88.5Function overloading means defining several functions with the same name but different parameter lists (number or types). It is a form of polymorphism.
- Readability: one meaningful name (area) is used for similar tasks instead of many names (areaSquare, areaRectangle).
- Flexibility: the same function can be called with different types or numbers of arguments; the compiler picks the right version automatically.
- Less effort and easier maintenance: the programmer remembers fewer names and related code stays together, which makes the program easier to extend.
#include <iostream>
using namespace std;
int area(int side) { return side * side; } // square
int area(int l, int w) { return l * w; } // rectangle
double area(double r) { return 3.14 * r * r; } // circle
int main() {
cout << area(4) << " " << area(5, 3) << " " << area(2.0) << endl;
return 0;
}16 15 12.56