2nd Year Computer Science — MCQs & Practice Questions

112 multiple-choice questions and 84 exam-style questions with mark schemes, organised by chapter, with answers you can check as you go. Free, no sign-up.

New to a topic? Read the 2nd Year Computer Science notes first, then come back to practise.

01

Data Basics

Multiple choice · 8

Q1All the details of one student form a:

  1. Afield
  2. Brecord
  3. Ctable
  4. Ddatabase
Show answer

Correct answer: B — record

A record is every field describing one entity. A field is one of those items; a table is many records.

Q2A student's roll number should be stored as:

  1. Ainteger
  2. Btext
  3. Cdecimal
  4. Dboolean
Show answer

Correct answer: B — text

No arithmetic is done on a roll number, and it may have leading zeros or letters. The test is always whether you would ever add two of them.

Q3The same address stored in three files is an example of:

  1. Anormalisation
  2. Bdata redundancy
  3. Ca primary key
  4. Da query
Show answer

Correct answer: B — data redundancy

Redundancy is duplication. Its dangerous consequence is inconsistency, when the copies stop agreeing.

Q4Which is the most serious consequence of redundancy?

  1. Awasted disk space
  2. Binconsistent conflicting values
  3. Cslower typing
  4. Dlarger backups
Show answer

Correct answer: B — inconsistent conflicting values

Storage is cheap. Conflicting values mean no report can be trusted, because there is no way to tell which copy is correct.

Q5Data dependence means:

  1. Adata depends on other data
  2. Bprograms contain the file structure, so structural changes require rewriting them
  3. Cfields depend on records
  4. Dthe database needs internet
Show answer

Correct answer: B — programs contain the file structure, so structural changes require rewriting them

Each program embeds the layout of the file it reads, so adding a single field means editing and retesting every one of them.

Q6A price of Rs 249.99 is best stored as:

  1. Atext
  2. Binteger
  3. Ccurrency or decimal
  4. Dboolean
Show answer

Correct answer: C — currency or decimal

It has a fractional part and arithmetic will be done on it. A currency or fixed-decimal type also avoids the rounding errors a floating-point type can introduce in money.

Q7Storing a date as text causes problems because:

  1. Ait uses more space
  2. Bit sorts alphabetically rather than chronologically
  3. Cdates cannot be text
  4. Dit needs more fields
Show answer

Correct answer: B — it sorts alphabetically rather than chronologically

As text, "01/12/2025" sorts before "02/01/2024", so the system cannot determine which date came first or calculate an interval.

Q8A database centralises data, which means an incorrectly typed address is now:

  1. Aautomatically corrected
  2. Bwrong in every system at once
  3. Cstored three times
  4. Dignored
Show answer

Correct answer: B — wrong in every system at once

Centralisation removes inconsistency but also removes the accidental second opinion. Validation at the point of entry becomes more important, not less.

Exam-style questions · 6

Q1[2 marks]
Define a field, a record and a table.
Answer

A field is a single item of data, such as a student's name. A record is the complete set of fields describing one entity — all the details of one student. A table is a collection of records of the same type.

Q2[2 marks]
Why should a telephone number be stored as text rather than as a number?
Answer

A numeric type would discard a leading zero, could not store spaces or dashes, and might round the value. No arithmetic is ever performed on a telephone number, so nothing is gained by making it numeric.

Q3[2 marks]
What is data redundancy, and why is data inconsistency worse?
Answer

Redundancy is the same data stored in more than one place. Inconsistency is what happens when one copy is updated and another is not, so the system holds conflicting values. Redundancy wastes storage, which is cheap; inconsistency means no report can be trusted, because there is no way to tell which copy is correct.

Q4[4 marks]
State four disadvantages of storing data in separate flat files rather than a database.
Mark scheme
  1. Redundancy — the same data is duplicated across several files[1]
  2. Inconsistency — updating one copy and not another leaves conflicting values[1]
  3. Data dependence — the file layout is embedded in each program, so a change to the structure means editing every program[1]
  4. Poor security and sharing — access is all-or-nothing per file; also accept difficulty answering unanticipated queries[1]

Redundancy, inconsistency, data dependence, and poor security or difficult queries.

Q5[4 marks]
A shop records sales. State a suitable data type for each field and justify two of your choices: ProductCode, Quantity, Price, DateSold.
Mark scheme
  1. ProductCode — text, since it may contain letters and leading zeros and is never used in arithmetic[1]
  2. Quantity — integer, since you cannot sell a fraction of an item and it is counted[1]
  3. Price — decimal or currency, since it has a fractional part and must keep exact precisiona float can introduce rounding errors in money[1]
  4. DateSold — date, so that date arithmetic and sorting work correctly, which they would not on text[1]

Text, integer, currency, date — each justified by what will be done with it.

Q6[6 marks]
A hospital currently keeps patient details in three separate systems: reception, pharmacy and billing.
  1. Explain two problems this causes.
  2. Explain how a single database would address them.
  3. State one problem a database does NOT solve.
Mark scheme
  1. Redundancy — each patient's name, address and identifier are stored three times[1]
  2. Inconsistency — a change of address entered at reception does not reach pharmacy or billing, so the systems disagree and nobody knows which is rightin a hospital this can affect care, not just correspondence[1]
  3. A database stores each patient record once, so there is only one copy to update and no second copy to disagree with[1]
  4. All three departments read the same record, so a change is visible everywhere immediately[1]
  5. Permissions can be set per table or per field, so pharmacy sees prescriptions and billing does notbetter than all-or-nothing file access[1]
  6. A database does not fix incorrect data entry — if the address is typed wrongly it is now wrong everywhere at once, so validation at entry is still essentialthe honest limitation[1]

(a) redundancy and inconsistency (b) one stored copy, seen by all, with per-table permissions (c) it cannot prevent wrong data being entered — and now the error is everywhere

02

Basic Concepts and Terminologies of Databases

Multiple choice · 8

Q1A field that uniquely identifies each record is the:

  1. Aforeign key
  2. Bprimary key
  3. Ccomposite field
  4. Dindex
Show answer

Correct answer: B — primary key

The primary key must be unique and never empty. A foreign key refers to another table's primary key.

Q2ClassID appearing in the STUDENT table, referring to CLASS, is a:

  1. Aprimary key
  2. Bforeign key
  3. Ccandidate key
  4. Dcomposite key
Show answer

Correct answer: B — foreign key

It holds the primary key value of another table, which is exactly what makes it a foreign key and what links the two tables.

Q3A many-to-many relationship is implemented using:

  1. Atwo tables only
  2. Ba third linking table
  3. Ca composite field
  4. Dno keys
Show answer

Correct answer: B — a third linking table

A field holds a single value, so neither side can store a list of the other. The linking table turns it into two one-to-many relationships.

Q4In a one-to-many relationship, the foreign key is placed:

  1. Aon the "one" side
  2. Bon the "many" side
  3. Cin both tables
  4. Din a third table
Show answer

Correct answer: B — on the "many" side

Each record on the many side refers to exactly one record on the one side, which is a single value and therefore fits in a field.

Q5A student's grade in a course should be stored in:

  1. Athe STUDENT table
  2. Bthe COURSE table
  3. Cthe linking ENROLMENT table
  4. Da separate file
Show answer

Correct answer: C — the linking ENROLMENT table

The grade needs both keys to identify it — it belongs to that student in that course, so it is an attribute of the relationship.

Q6Which is the best primary key for a student record?

  1. AFull name
  2. BDate of birth
  3. CAn auto-generated roll number
  4. DHome address
Show answer

Correct answer: C — An auto-generated roll number

It is guaranteed unique and has no reason ever to change. Names repeat, dates of birth repeat, and addresses change.

Q7Concurrency control exists to:

  1. Aspeed up queries
  2. Bstop simultaneous updates corrupting data
  3. Ccompress the database
  4. Dencrypt records
Show answer

Correct answer: B — stop simultaneous updates corrupting data

Without it, two users saving changes to the same record at the same moment can leave the data in an inconsistent state or lose one update entirely.

Q8A composite primary key is needed when:

  1. Athe table is large
  2. Bno single field is unique
  3. Cthere are two tables
  4. Dforeign keys are used
Show answer

Correct answer: B — no single field is unique

In an ENROLMENT table neither StudentID nor CourseID is unique alone, but the pair together identifies exactly one enrolment.

Exam-style questions · 6

Q1[2 marks]
Define a primary key and state two properties it must have.
Answer

A primary key is a field, or combination of fields, that uniquely identifies each record in a table. It must be unique across all records and must never be empty. It should also never change.

Q2[2 marks]
What is a foreign key?
Answer

A field in one table that holds the primary key value of another table, creating the link between them. For example, ClassID stored in the STUDENT table refers to the primary key of the CLASS table.

Q3[2 marks]
Why is a student's name unsuitable as a primary key?
Answer

Names are not unique — two students may share one — and they can change, which would break every foreign key referring to that record. A primary key should be a meaningless, stable identifier such as a roll number.

Q4[4 marks]
State four services provided by a database management system.
Mark scheme
  1. Data integrity — validation rules and constraints reject invalid data[1]
  2. Security — access permissions per user, per table, or per field[1]
  3. Concurrency control — simultaneous updates by different users cannot corrupt the data[1]
  4. Backup and recovery, and a query language for answering unanticipated questionseither earns the mark[1]

Integrity, security, concurrency control, backup and recovery, and a query language.

Q5[4 marks]
A driving school records instructors and students. Each student is taught by one instructor; each instructor teaches many students. Design the tables, identifying keys.
Mark scheme
  1. Relationship identified as one to many, from instructor to student[1]
  2. INSTRUCTOR(InstructorID, Name, Phone)primary key underlined or stated[1]
  3. STUDENT(StudentID, Name, Address, InstructorID)[1]
  4. InstructorID in STUDENT is a foreign key referring to INSTRUCTOR — the key goes on the "many" sideplacing it on the wrong side is the standard error[1]

Two tables, with InstructorID as a foreign key in STUDENT.

Q6[6 marks]
A college needs a database recording which students are enrolled in which courses, and the grade each student achieved in each course.
  1. Identify the relationship between STUDENT and COURSE and explain why it cannot be stored in two tables.
  2. Design the tables, showing primary and foreign keys.
  3. Explain where the grade must be stored and why.
Mark scheme
  1. Many to many — a student takes many courses and a course has many students[1]
  2. A field holds a single value, so neither table can hold a list of the other; a third table is requiredthe reason, not just the assertion[1]
  3. STUDENT(StudentID, Name) and COURSE(CourseID, Title)[1]
  4. ENROLMENT(StudentID, CourseID, Grade) with a composite primary key, both fields also being foreign keysaccept a separate EnrolmentID[1]
  5. The grade belongs in ENROLMENT[1]
  6. Because it is a property of that particular student's enrolment in that particular course — not of the student, who has many grades, nor of the course, which awards manythe reasoning is the mark[1]

(a) many to many — a field cannot hold a list (b) STUDENT, COURSE and an ENROLMENT linking table (c) the grade goes in ENROLMENT, since it belongs to the relationship

03

Database Design Process

Multiple choice · 8

Q1Which design stage depends on the DBMS chosen?

  1. AConceptual
  2. BLogical
  3. CPhysical
  4. DNone
Show answer

Correct answer: C — Physical

Data types, indexes and storage differ between products. The conceptual and logical designs are deliberately product-independent.

Q2In a description, nouns are most likely to be:

  1. Arelationships
  2. Bentities and attributes
  3. Cprimary keys
  4. Dqueries
Show answer

Correct answer: B — entities and attributes

Nouns name things; verbs describe how they relate. Sorting nouns into entities and attributes is the next step.

Q3"One student takes many subjects; one subject has many students" is:

  1. A1:1
  2. B1:M
  3. CM:N
  4. Dnot a relationship
Show answer

Correct answer: C — M:N

Both directions are "many", so it is many-to-many and requires a linking table.

Q4"One doctor has many appointments; one appointment has one doctor" is:

  1. A1:1
  2. B1:M
  3. CM:N
  4. Dundefined
Show answer

Correct answer: B — 1:M

One direction is many and the other is one. This becomes a foreign key on the appointment table.

Q5An M:N relationship requires:

  1. Aa foreign key on either side
  2. Ba linking table
  3. Ca composite field
  4. Dno keys
Show answer

Correct answer: B — a linking table

A field can hold only one value, so neither side can reference many rows on the other. The linking table turns it into two 1:M relationships.

Q6A noun should be modelled as an entity when it:

  1. Aappears more than once
  2. Bhas properties of its own to store
  3. Cis capitalised
  4. Dis in the first sentence
Show answer

Correct answer: B — has properties of its own to store

If the only thing you store about it is the value itself, it is an attribute. If it has its own attributes, it needs its own table.

Q7The date of an appointment belongs in:

  1. Athe PATIENT table
  2. Bthe DOCTOR table
  3. Cthe APPOINTMENT table
  4. Dall three
Show answer

Correct answer: C — the APPOINTMENT table

It describes that meeting, not the patient or the doctor, both of whom have many appointments on different dates.

Q8Designing directly in the software rather than on paper usually leads to:

  1. Afaster development with no drawbacks
  2. Ba structure that becomes hard to change
  3. Cbetter normalisation
  4. Dfewer tables
Show answer

Correct answer: B — a structure that becomes hard to change

Decisions get made implicitly and are then embedded in forms, queries and reports. Changing the structure afterwards means changing all of them.

Exam-style questions · 6

Q1[2 marks]
Name the three stages of database design.
Answer

Conceptual design — identifying entities, attributes and relationships. Logical design — converting these to tables with keys and normalising them. Physical design — choosing data types, indexes and storage for the particular DBMS.

Q2[2 marks]
How do you decide whether a noun in a description is an entity or an attribute?
Answer

A noun with properties of its own that must be stored is an entity and becomes a table. A noun that is simply a single property of something else is an attribute and becomes a field. "Address" is usually an attribute of a customer, but becomes an entity if the system must store a district, postcode and access notes for each one.

Q3[2 marks]
What does cardinality mean in an ER diagram?
Answer

The number of records on each side of a relationship that may be associated with one record on the other — written 1:1, 1:M or M:N. It determines the table structure, since a 1:M becomes a foreign key while an M:N requires an additional linking table.

Q4[4 marks]
From this description, identify the entities and the relationship: "A bookshop stocks many titles. Each title is supplied by one publisher, and a publisher supplies many titles."
Mark scheme
  1. Entities: TITLE and PUBLISHERbookshop is the system, not an entity[1]
  2. Relationship: one publisher supplies many titles, and each title has one publisher — 1:Mstated in both directions[1]
  3. PUBLISHER(PublisherID, Name, Address)[1]
  4. TITLE(ISBN, Title, Price, PublisherID) — the foreign key on the many sideISBN is a natural primary key here[1]

TITLE and PUBLISHER, in a 1:M relationship, with PublisherID as a foreign key in TITLE.

Q5[4 marks]
Explain why an M:N relationship cannot be implemented with two tables, and describe how it is resolved.
Mark scheme
  1. A field holds a single value, so it cannot store a list of related recordsthe fundamental reason[1]
  2. Putting a foreign key on either side would allow only one match, which contradicts "many"[1]
  3. A third linking table is created, containing the primary keys of both entities as foreign keys[1]
  4. This converts the M:N into two 1:M relationships, each of which tables can express; the linking table also holds any attribute of the relationship itself[1]

A field holds one value, so a linking table with both foreign keys is required, giving two 1:M relationships.

Q6[6 marks]
A gym records members, the classes it runs, and which members attend which classes. Each class is taught by one instructor.
  1. Identify the entities.
  2. State each relationship with its cardinality.
  3. Give the tables with their primary and foreign keys.
Mark scheme
  1. Entities: MEMBER, CLASS, INSTRUCTORgym is the system itself[1]
  2. INSTRUCTOR to CLASS is 1:M — one instructor teaches many classes, each class has one instructor[1]
  3. MEMBER to CLASS is M:N — a member attends many classes and a class has many membersstated in both directions[1]
  4. INSTRUCTOR(InstructorID, Name) and CLASS(ClassID, ClassName, Time, InstructorID)InstructorID is the foreign key on the many side[1]
  5. MEMBER(MemberID, Name, JoinDate)[1]
  6. ATTENDANCE(MemberID, ClassID, Date) — a linking table with a composite key, resolving the M:NDate belongs here, being a property of that attendance[1]

(a) MEMBER, CLASS, INSTRUCTOR (b) instructor–class 1:M, member–class M:N (c) four tables, with ATTENDANCE linking members to classes

04

Data Integrity and Normalization

Multiple choice · 8

Q1A rule that a mark must be between 0 and 100 is a:

  1. Apresence check
  2. Brange check
  3. Cformat check
  4. Dverification
Show answer

Correct answer: B — range check

It tests whether the value lies within allowed limits, which is exactly what a range check does.

Q2A date of birth typed as 1995 instead of 1985 would be caught by:

  1. Avalidation
  2. Bverification
  3. Ca range check
  4. Da type check
Show answer

Correct answer: B — verification

1995 is a perfectly reasonable date, so it passes every validation rule. Only checking it against the source — verification — reveals the error.

Q3Preventing a class from being deleted while students still refer to it is:

  1. Aentity integrity
  2. Breferential integrity
  3. Cdomain integrity
  4. Dnormalisation
Show answer

Correct answer: B — referential integrity

Referential integrity ensures foreign keys always point at records that exist, so deleting the referenced record is refused or cascaded.

Q4A table with a column holding "Maths, Physics" is not in:

  1. A1NF
  2. B2NF
  3. C3NF
  4. Dany normal form problem
Show answer

Correct answer: A — 1NF

A cell containing more than one value is a repeating group, which 1NF forbids. Later forms cannot even be assessed until this is fixed.

Q5A dependency on part of a composite key is a:

  1. Atransitive dependency
  2. Bpartial dependency
  3. Creferential constraint
  4. Dforeign key
Show answer

Correct answer: B — partial dependency

Partial dependencies are removed at 2NF. They can only exist where the primary key is made of more than one field.

Q6In STUDENT(RollNo, Name, ClassID, ClassTeacher), ClassTeacher depending on ClassID is a:

  1. Apartial dependency
  2. Btransitive dependency
  3. Cvalid design
  4. Dcomposite key
Show answer

Correct answer: B — transitive dependency

RollNo → ClassID → ClassTeacher is a chain through a non-key field, which 3NF removes by splitting out a CLASS table.

Q7Having to change a customer name in fifty rows is an:

  1. Ainsertion anomaly
  2. Bdeletion anomaly
  3. Cupdate anomaly
  4. Dintegrity constraint
Show answer

Correct answer: C — update anomaly

One fact stored in fifty places means fifty edits, and missing one leaves the database holding two different names for the same customer.

Q8One genuine cost of normalising a database is:

  1. Amore storage used
  2. Bqueries need joins across more tables
  3. Cdata becomes inconsistent
  4. Dkeys are lost
Show answer

Correct answer: B — queries need joins across more tables

Normalisation reduces storage and removes inconsistency. What it costs is query complexity — assembling a full record now means joining several tables.

Exam-style questions · 6

Q1[2 marks]
Differentiate between validation and verification.
Answer

Validation is an automatic check that entered data is reasonable — within range, of the right type, in the right format. Verification checks that the data was entered correctly, for example by double entry or by reading it back. A date typed as 1995 instead of 1985 passes validation but fails verification.

Q2[2 marks]
What is referential integrity?
Answer

The rule that a foreign key must either be empty or match an existing primary key in the related table. It prevents orphaned records — a student enrolled in a class that does not exist, or left pointing at a class after it is deleted.

Q3[2 marks]
A table is in 1NF. What must be true of it?
Answer

It contains no repeating groups — every cell holds a single, indivisible value, and there are no columns such as Subject1, Subject2, Subject3. Every record is also uniquely identifiable by a primary key.

Q4[4 marks]
Explain the three anomalies that normalisation removes, with an example of each.
Mark scheme
  1. Insertion anomaly — a fact cannot be recorded without another. A new teacher cannot be entered until a student enrols with them[1]
  2. Deletion anomaly — removing one fact destroys another. Deleting the last enrolment erases the teacher's phone number[1]
  3. Update anomaly — one change must be made in many rows[1]
  4. Missing one row leaves the database holding two different values for the same fact, so no report can be trustedthe consequence is the fourth mark[1]

Insertion, deletion and update anomalies, all caused by storing a fact in more than one row.

Q5[4 marks]
The table STUDENT(RollNo, Name, ClassID, ClassTeacher) is in 2NF but not 3NF. Explain why and correct it.
Mark scheme
  1. ClassTeacher depends on ClassID, not on the primary key RollNo[1]
  2. RollNo → ClassID → ClassTeacher is a transitive dependency through a non-key field, which 3NF forbidsnaming it is required[1]
  3. Split into STUDENT(RollNo, Name, ClassID)ClassID remains as a foreign key[1]
  4. and CLASS(ClassID, ClassTeacher) — the teacher is now stored once per class[1]

A transitive dependency; split into STUDENT and CLASS tables.

Q6[6 marks]
A table records library loans: LOAN(LoanID, MemberID, MemberName, BookISBN, BookTitle, Author, DateOut).
  1. Identify two problems with this structure.
  2. Normalise it to 3NF, showing all tables and keys.
  3. Explain one benefit and one cost of the normalised design.
Mark scheme
  1. MemberName is repeated on every loan by that member, and BookTitle and Author on every loan of that book — redundancy[1]
  2. An update anomaly follows: correcting a member's name means editing every one of their loan records, and missing one leaves contradictory dataaccept insertion: a new book cannot be recorded until it is borrowed[1]
  3. MEMBER(MemberID, MemberName)[1]
  4. BOOK(BookISBN, BookTitle, Author)[1]
  5. LOAN(LoanID, MemberID, BookISBN, DateOut) — both foreign keys, and DateOut belongs to the loan itself[1]
  6. Benefit: each fact is stored once, so updates are single edits and no contradiction is possible. Cost: retrieving a full loan report now requires joining three tables, which is more complex and slower to queryboth halves needed for the mark[1]

(a) redundancy and update anomalies (b) MEMBER, BOOK and LOAN (c) single-point updates, at the cost of joins

05

Introduction to Microsoft Access

Multiple choice · 8

Q1Which Access object stores the actual data?

  1. AQuery
  2. BForm
  3. CTable
  4. DReport
Show answer

Correct answer: C — Table

Only tables hold data. The other objects read from tables and would be empty without them.

Q2Deleting a query from an Access database:

  1. Adeletes the records it selected
  2. Bdeletes no data at all
  3. Cdeletes the table
  4. Dcorrupts the file
Show answer

Correct answer: B — deletes no data at all

A query stores only the question. Removing it removes the saved question and leaves every record untouched.

Q3The property that rejects a mark above 100 is:

  1. AFormat
  2. BInput Mask
  3. CValidation Rule
  4. DField Size
Show answer

Correct answer: C — Validation Rule

The Validation Rule tests each entered value against a condition. Format only changes how a stored value is displayed.

Q4Which property prevents a field being left empty?

  1. AIndexed
  2. BRequired
  3. CDefault Value
  4. DFormat
Show answer

Correct answer: B — Required

Required = Yes is the presence check. A Default Value would fill something in rather than refusing a blank.

Q5An AutoNumber field is a good primary key because it is:

  1. Ameaningful to users
  2. Bunique, never empty and never changing
  3. Cthe shortest field
  4. Dautomatically indexed
Show answer

Correct answer: B — unique, never empty and never changing

Those are exactly the three requirements of a primary key. Being meaningless is what guarantees the third.

Q6Enforcing referential integrity stops you:

  1. Aadding any records
  2. Bentering a foreign key that matches no primary key
  3. Cusing queries
  4. Dcreating forms
Show answer

Correct answer: B — entering a foreign key that matches no primary key

It also blocks deleting a record while others still refer to it. Both prevent orphaned records.

Q7Cascade Delete on a CUSTOMER–INVOICE relationship would:

  1. Abe a sensible default
  2. Bdelete all a customer's invoices when the customer is deleted
  3. Cprevent deletion
  4. Dcopy the invoices
Show answer

Correct answer: B — delete all a customer's invoices when the customer is deleted

That is usually the wrong outcome — invoices are financial records that must be retained even after a customer leaves.

Q8A clinic outgrowing Access would most likely be limited by:

  1. Athe number of tables
  2. Bthe number of simultaneous users
  3. Cthe length of field names
  4. Dthe number of queries
Show answer

Correct answer: B — the number of simultaneous users

Access is a file-based system designed for a handful of concurrent users. Growth in simultaneous access is the usual reason to move to a client-server DBMS.

Exam-style questions · 6

Q1[2 marks]
Name the four main objects in a Microsoft Access database and state which stores the data.
Answer

Tables, queries, forms and reports. Only tables store data; queries, forms and reports all read from the tables and hold no data of their own.

Q2[2 marks]
What is the difference between Design View and Datasheet View?
Answer

Design View defines the structure — field names, data types and properties such as validation rules. Datasheet View displays the records in rows and columns and is where data is entered and edited.

Q3[2 marks]
What is an AutoNumber field, and why does it make a good primary key?
Answer

An AutoNumber is an integer Access generates automatically, increasing for each new record. It makes a good primary key because it is guaranteed unique, is never empty, and — being meaningless — has no reason ever to change.

Q4[4 marks]
A field stores a student's age, which must be between 11 and 19 and cannot be blank. State four design settings.
Mark scheme
  1. Data Type: Number, with Field Size Integerage is counted and compared[1]
  2. Validation Rule: >=11 And <=19the boundary values are included[1]
  3. Validation Text: a clear message such as "Age must be between 11 and 19"without it the user sees a generic error[1]
  4. Required: Yes, so the field cannot be left emptythe presence check[1]

Number/Integer, validation rule, validation text, and Required = Yes.

Q5[4 marks]
Explain what enforcing referential integrity does in Access, and describe the effect of Cascade Delete.
Mark scheme
  1. It prevents a record being added whose foreign key does not match an existing primary keyno enrolment in a class that does not exist[1]
  2. And prevents a record being deleted while other records still refer to it, avoiding orphaned records[1]
  3. Cascade Delete instead allows the deletion and automatically removes every related child record[1]
  4. It must be used carefully — deleting a customer would silently delete their entire order history, which may be needed for accountsthe caution is the mark[1]

It blocks unmatched foreign keys and unsafe deletions; Cascade Delete removes the children instead, which is often not what is wanted.

Q6[6 marks]
A small clinic is choosing between Microsoft Access and a spreadsheet for its patient records.
  1. Give two advantages of Access over a spreadsheet.
  2. Give two limitations of Access the clinic should be aware of.
  3. State one situation in which the clinic would need to move to a different DBMS.
Mark scheme
  1. Access enforces data types, validation rules and referential integrity, so invalid or inconsistent data is rejected at entry — a spreadsheet accepts anything in any cell[1]
  2. Related data is stored once across linked tables rather than duplicated, and forms and reports can be built for staff who never see the raw data[1]
  3. Limitation: it supports only a small number of simultaneous users reliably[1]
  4. Limitation: the single file has a size ceiling, and it runs only on Windows — not on a phone or a web server[1]
  5. It would need to move if the number of concurrent users grew substantially, or if access were needed over the web or from mobile devices[1]
  6. A client-server DBMS such as MySQL or SQL Server would be used, and the existing table design would largely transferthe design survives the move[1]

(a) enforced integrity and linked tables (b) few concurrent users, size and platform limits (c) growth in users or a need for web access

06

Table and Query

Multiple choice · 8

Q1A query in Access stores:

  1. Aa copy of the selected records
  2. Bthe question only
  3. Cthe whole table
  4. Dnothing at all
Show answer

Correct answer: B — the question only

It saves the criteria and re-runs them against the tables, which is why its results are always current.

Q2Criteria written on the same row of the design grid are combined with:

  1. AOR
  2. BAND
  3. CNOT
  4. DLIKE
Show answer

Correct answer: B — AND

Same row means all must be satisfied. Different rows are ORed, so a record need satisfy only one of them.

Q3Which returns the most records?

  1. AMarks>60 AND Class="10A"
  2. BMarks>60 OR Class="10A"
  3. CMarks>60 only
  4. DClass="10A" only
Show answer

Correct answer: B — Marks>60 OR Class="10A"

OR accepts a record satisfying either condition, so its result always contains at least as many rows as either condition alone.

Q4To find names beginning with S you would write:

  1. ALike "*S"
  2. BLike "S*"
  3. C="S"
  4. DIs Null
Show answer

Correct answer: B — Like "S*"

The asterisk stands for any characters that follow, so the S must come first. Option A finds names ending in S.

Q5To sort marks from highest to lowest you write:

  1. AORDER BY Marks
  2. BORDER BY Marks ASC
  3. CORDER BY Marks DESC
  4. DSORT Marks DOWN
Show answer

Correct answer: C — ORDER BY Marks DESC

ORDER BY defaults to ascending, so descending order must be requested explicitly with DESC.

Q6A blank Marks field and a Marks field of 0 differ because:

  1. Athey are the same
  2. Bblank means unknown, 0 means a known score of nothing
  3. C0 is invalid
  4. Dblank is faster
Show answer

Correct answer: B — blank means unknown, 0 means a known score of nothing

An average ignores blanks but includes zeros, so entering 0 for an absent student would wrongly lower the class average.

Q7A query needs two tables when:

  1. Athe tables are large
  2. Bthe required columns are stored in different tables
  3. Cthere are many records
  4. Da sort is needed
Show answer

Correct answer: B — the required columns are stored in different tables

Normalisation deliberately spread the data. A join on the shared key brings the required columns back together.

Q8Storing Total as well as Price and Quantity in a table is poor design because:

  1. Ait uses space
  2. Bthe three can disagree after an edit
  3. Ctotals cannot be stored
  4. Dqueries would fail
Show answer

Correct answer: B — the three can disagree after an edit

A derived value stored separately is redundancy: change the quantity and the stored total is silently wrong. Calculate it in the query instead.

Exam-style questions · 6

Q1[2 marks]
What is a query, and does it store data?
Answer

A query is a saved question that selects, filters, sorts or calculates from one or more tables. It stores no data — only the question — and produces its results afresh from the tables each time it runs, so the answer is always current.

Q2[2 marks]
State the difference between AND and OR in query criteria.
Answer

AND requires a record to satisfy every condition, so the result is smaller than either condition alone. OR requires only one, so the result is larger. In the Access design grid, criteria on the same row are ANDed and criteria on different rows are ORed.

Q3[2 marks]
What does the criterion Like "A*" select?
Answer

All records whose value in that field begins with A. The asterisk is a wildcard standing for any sequence of characters, so Like "*A*" would instead find values containing A anywhere.

Q4[4 marks]
Write an SQL query listing the Name and Marks of all students in the STUDENT table who scored above 50, sorted from highest to lowest.
Mark scheme
  1. SELECT Name, Marksonly the requested columns[1]
  2. FROM STUDENT[1]
  3. WHERE Marks > 50no quotation marks — Marks is numeric[1]
  4. ORDER BY Marks DESCDESC is required for highest first[1]

SELECT Name, Marks FROM STUDENT WHERE Marks > 50 ORDER BY Marks DESC

Q5[4 marks]
Explain the difference between a field that is Null and a field containing 0, and state a criterion to find each.
Mark scheme
  1. A Null field is empty — the value is unknown or was never entered[1]
  2. A field containing 0 holds a known value, namely zeroa real mark of nothing, not a missing one[1]
  3. Criterion Is Null finds the empty ones; =0 finds the zeros[1]
  4. The distinction matters because an average ignores nulls but includes zeros, giving two different answers from the same columnthe consequence is the fourth mark[1]

Null is unknown, 0 is a known value. Is Null and =0 respectively; averages treat them differently.

Q6[6 marks]
A library database has BOOK(ISBN, Title, Author) and LOAN(LoanID, ISBN, MemberID, DateDue).
  1. Write a query listing the Title and DateDue of all books due before 1 March 2026.
  2. Explain why this query needs both tables.
  3. Describe how you would produce a count of loans per member.
Mark scheme
  1. SELECT Title, DateDue[1]
  2. FROM BOOK INNER JOIN LOAN ON BOOK.ISBN = LOAN.ISBNjoined on the shared key[1]
  3. WHERE DateDue < #1/3/2026#dates enclosed in hash symbols[1]
  4. Title is stored only in BOOK and DateDue only in LOAN, so neither table alone can produce both columnsa direct consequence of normalisation[1]
  5. Use a totals query: group by MemberID[1]
  6. and apply Count to LoanID, giving one row per member with their number of loansaccept SELECT MemberID, Count(LoanID) FROM LOAN GROUP BY MemberID[1]

(a) a join on ISBN with a date criterion (b) the two columns live in different tables (c) a totals query grouping by MemberID with Count

07

Microsoft Access Forms and Reports

Multiple choice · 8

Q1Which Access object is read-only?

  1. ATable
  2. BForm
  3. CQuery
  4. DReport
Show answer

Correct answer: D — Report

Reports present data for printing and cannot change it, which is what makes them safe to distribute.

Q2A control offering a list of existing classes to choose from is a:

  1. Atext box
  2. Bcombo box
  3. Clabel
  4. Dcommand button
Show answer

Correct answer: B — combo box

A combo box restricts entry to values that exist, usually drawn from a related table.

Q3A subform is used to show:

  1. Aa second copy of the same record
  2. Bthe "many" side of a one-to-many relationship
  3. Ca printed report
  4. Dthe table design
Show answer

Correct answer: B — the "many" side of a one-to-many relationship

The main form shows the one record and the subform shows its related many records, linked automatically on the shared key.

Q4Column headings on a multi-page report belong in the:

  1. AReport Header
  2. BPage Header
  3. CDetail
  4. DReport Footer
Show answer

Correct answer: B — Page Header

The Page Header prints at the top of every page. In the Report Header they would appear once and be missing from page two onwards.

Q5A class average in a report grouped by class belongs in the:

  1. ADetail section
  2. BGroup Footer
  3. CPage Footer
  4. DReport Header
Show answer

Correct answer: B — Group Footer

The Group Footer prints once at the end of each group, which is exactly where a per-class figure is wanted.

Q6A grand total placed in the Page Footer would:

  1. Aprint correctly once
  2. Bprint on every page and be wrong
  3. Cnot print at all
  4. Dprint in the header
Show answer

Correct answer: B — print on every page and be wrong

The Page Footer runs at the bottom of every page, so the total appears repeatedly and is only correct on the final one.

Q7The main advantage of a combo box over validation is that it:

  1. Ais faster to design
  2. Bprevents invalid entry rather than detecting it
  3. Cuses less storage
  4. Dworks without a table
Show answer

Correct answer: B — prevents invalid entry rather than detecting it

The user cannot type a value that is not in the list, so no error occurs to be caught. It also keeps the foreign key valid automatically.

Q8A form is preferable to entering data in the datasheet because it can:

  1. Astore more records
  2. Bhide irrelevant fields and prevent invalid entry
  3. Crun faster
  4. Dprint better
Show answer

Correct answer: B — hide irrelevant fields and prevent invalid entry

Forms shape what the user sees and what they are able to type. The datasheet exposes every field with no control over entry.

Exam-style questions · 6

Q1[2 marks]
State two differences between a form and a report.
Answer

A form is designed for the screen, usually shows one record at a time, and can edit the data. A report is designed for printing, shows many records grouped and totalled, and is read-only.

Q2[2 marks]
Give two reasons for entering data through a form rather than directly into a table.
Answer

A form can display only the fields a particular user should see and arrange them to match the paper form being copied from, reducing errors. It can also use controls such as a combo box, which makes an invalid entry impossible rather than merely detecting it afterwards.

Q3[2 marks]
What is a subform used for?
Answer

To display the "many" side of a one-to-many relationship inside the form showing the "one" side — the order lines within an order. Access links them on the shared key, so only the related records appear and new ones automatically receive the correct foreign key.

Q4[4 marks]
Name four sections of an Access report and state what should be placed in each.
Mark scheme
  1. Report Header — the title and date, printed once at the very beginning[1]
  2. Page Header — column headings, printed at the top of every page[1]
  3. Detail — the fields of each record, printed once per record[1]
  4. Group Footer — a subtotal or average, printed at the end of each group; or Report Footer for the grand total[1]

Report Header, Page Header, Detail, Group and Report Footers — each printing at a different frequency.

Q5[4 marks]
Explain why a combo box bound to a related table is better than a text box with a validation rule.
Mark scheme
  1. A text box lets the user type anything, and the validation rule rejects it afterwards[1]
  2. A combo box offers only the values that exist, so an invalid entry cannot be made in the first placeprevention rather than detection[1]
  3. It can display a readable name while storing the underlying key value, so the foreign key is always valid[1]
  4. The list updates automatically when the related table changes, whereas a validation rule listing permitted values must be edited by handmaintenance is the fourth mark[1]

It prevents rather than detects, stores the key while showing the name, and stays current automatically.

Q6[6 marks]
A school needs a printed report showing every student's marks, grouped by class, with each class's average and an overall average.
  1. State which report sections you would use and what each contains.
  2. Explain why the overall average must not be placed in the Page Footer.
  3. Explain why a report rather than a form is the right object here.
Mark scheme
  1. Report Header: the title and the date produced. Page Header: column headings for name and marks[1]
  2. Group Header: the class name, printed once per classgrouping by ClassID[1]
  3. Detail: each student's name and marks, once per record[1]
  4. Group Footer: the class average. Report Footer: the overall average[1]
  5. The Page Footer prints at the bottom of every page, so an overall average placed there would appear repeatedly and be incorrect on every page but the last[1]
  6. A report is designed for printing many grouped records with totals, and is read-only — so it can be distributed without any risk of the marks being alteredthe read-only point is the strongest reason[1]

(a) header, page header, group header, detail, group footer, report footer (b) it would print once per page and be wrong (c) reports print many grouped records and cannot be edited

08

Getting Started with C

Multiple choice · 8

Q1Execution of a C program begins at:

  1. Athe first line of the file
  2. Bthe #include line
  3. Cmain()
  4. Dthe last function
Show answer

Correct answer: C — main()

Whatever order the functions appear in, the operating system calls main first.

Q2A missing semicolon produces a:

  1. Alogical error
  2. Bsyntax error
  3. Cruntime error
  4. Dlinker error
Show answer

Correct answer: B — syntax error

It breaks the rules of the language, so the compiler reports it and refuses to build the program.

Q3A program that compiles and runs but gives wrong answers has a:

  1. Asyntax error
  2. Blogical error
  3. Clinker error
  4. Dpreprocessor error
Show answer

Correct answer: B — logical error

The code is valid C; it simply does the wrong thing. Nothing in the toolchain can detect this.

Q4An "undefined reference" message with no line number indicates a:

  1. Asyntax error
  2. Blinker error
  3. Cruntime error
  4. Dlogical error
Show answer

Correct answer: B — linker error

Compilation succeeded, so the source is valid. The linker could not find the definition of something that was declared.

Q5The preprocessor is responsible for:

  1. Atranslating C to assembly
  2. Bhandling lines beginning with #
  3. Cproducing the executable
  4. Drunning the program
Show answer

Correct answer: B — handling lines beginning with #

It pastes in header files and substitutes defined constants before the compiler sees the code at all.

Q6In C, using a variable that was never declared is:

  1. Aallowed
  2. Ba syntax error caught by the compiler
  3. Ca runtime error
  4. Da warning only
Show answer

Correct answer: B — a syntax error caught by the compiler

C is statically typed and requires declaration before use, so the compiler rejects it rather than the program failing later.

Q7return 0; at the end of main indicates:

  1. Athe program produced zero output
  2. Bthe program completed successfully
  3. Can error occurred
  4. Dnothing at all
Show answer

Correct answer: B — the program completed successfully

The value is returned to the operating system, and zero conventionally means success. A non-zero value signals a failure.

Q8The hardest kind of error to find is:

  1. Asyntax
  2. Bruntime
  3. Clogical
  4. Dlinker
Show answer

Correct answer: C — logical

The other three announce themselves. A logical error produces a program that builds cleanly, runs quietly and is wrong.

Exam-style questions · 6

Q1[2 marks]
What is the purpose of #include <stdio.h> and of main()?
Answer

#include <stdio.h> instructs the preprocessor to insert the standard input/output header, making functions such as printf and scanf available. main() is the entry point — execution of every C program begins there.

Q2[2 marks]
Differentiate between a syntax error and a logical error.
Answer

A syntax error breaks the rules of the language — a missing semicolon — and is found by the compiler, which refuses to build the program. A logical error is valid C that does the wrong thing, such as using + where * was intended: it compiles, runs, and produces an incorrect result that nothing reports.

Q3[2 marks]
What is the difference between a compiler error and a linker error?
Answer

A compiler error is a fault in the source code itself — a syntax or type mistake — and is reported with a line number. A linker error occurs after successful compilation, when a function that was declared cannot be found, and names no line because the fault is a missing definition rather than bad code.

Q4[4 marks]
Describe the four stages between source code and an executable program.
Mark scheme
  1. Preprocessor — processes # directives, inserting header files and substituting defined constants[1]
  2. Compiler — translates the C into assembly, reporting syntax and type errors[1]
  3. Assembler — converts assembly into machine code, producing an object file[1]
  4. Linker — combines the object file with library code to produce the final executable[1]

Preprocessing, compilation, assembly, linking.

Q5[4 marks]
Write a C program that prints your name and the number 2026 on separate lines.
Mark scheme
  1. #include <stdio.h>without it printf is undeclared[1]
  2. int main() { with a matching closing brace[1]
  3. Two printf statements, each ending in a semicolon, with \n for the line breaka single printf with two \n is equally acceptable[1]
  4. return 0; before the closing brace[1]

include, main, two printf calls with newlines, return 0.

Q6[6 marks]
A student writes a C program that compiles without any error but prints an average of 0 for every set of marks entered.
  1. State the type of error and explain how you know.
  2. Give two plausible causes.
  3. Describe how you would locate the fault.
Mark scheme
  1. A logical error[1]
  2. It compiled successfully, so the syntax is valid, and it runs without crashing — so the fault is in what the program does rather than in how it is writtenthe reasoning is the mark[1]
  3. Cause: integer division — dividing two integers in C discards the fractional part, so 7/2 gives 3 and a total smaller than the count gives 0the classic C trap[1]
  4. Cause: the total is being reset inside the loop, or the division uses the wrong variableany second plausible cause[1]
  5. Trace the program by hand with two or three marks whose average you already know[1]
  6. Or add temporary printf statements showing the total and the count immediately before the division, to see which value is wrong[1]

(a) logical — it compiles and runs but is wrong (b) integer division, or the total reset inside the loop (c) hand trace with known data, or print the intermediate values

09

Elements of C

Multiple choice · 8

Q1In C, int x; printf("%d", x); prints:

  1. A0
  2. Ban unpredictable value
  3. Can error
  4. Dnothing
Show answer

Correct answer: B — an unpredictable value

C does not initialise variables. The declaration reserves memory and whatever was already there is what you read.

Q211 / 4 with both operands int gives:

  1. A2.75
  2. B3
  3. C2
  4. D2.8
Show answer

Correct answer: C — 2

Integer division truncates towards zero, so 2.75 becomes 2. There is no rounding.

Q311 % 4 gives:

  1. A2
  2. B3
  3. C2.75
  4. D0
Show answer

Correct answer: B — 3

The % operator returns what is left over: 11 = 4 × 2 + 3, so the remainder is 3. Note it works on integers only — applying % to a float is a compile error in C, unlike in some other languages.

Q4int i = 3; printf("%d", ++i); prints:

  1. A3
  2. B4
  3. C5
  4. D2
Show answer

Correct answer: B — 4

The pre-increment adds first and then uses the new value. i++ would have printed 3.

Q5if (x = 0) in C:

  1. Ais a syntax error
  2. Bsets x to 0 and the condition is always false
  3. Ccompares x with 0
  4. Dalways runs the block
Show answer

Correct answer: B — sets x to 0 and the condition is always false

It assigns 0 and then uses that as the condition. Zero is false, so this particular version never runs — while if (x = 5) always would.

Q6To get 2.5 from 5 / 2 you should write:

  1. Afloat r = 5 / 2;
  2. B(float) 5 / 2
  3. Cint r = 5 / 2;
  4. D5 % 2
Show answer

Correct answer: B — (float) 5 / 2

The cast makes one operand a float before the division. Declaring the destination as float does not change how the division itself is performed.

Q7Which is preferable for a constant, and why?

  1. A#define, because it is faster
  2. Bconst, because it has a type and obeys scope
  3. Cneither
  4. Da normal variable
Show answer

Correct answer: B — const, because it has a type and obeys scope

#define is a blind textual substitution before compilation. const declares a real typed entity the compiler can check and name in errors.

Q8Combining an int and a float in one expression causes:

  1. Aa compile error
  2. Bthe int to be promoted to float automatically
  3. Cthe float to be truncated
  4. Dundefined behaviour
Show answer

Correct answer: B — the int to be promoted to float automatically

This is implicit conversion, and it promotes to the larger type. Explicit casting is needed only when you want something other than the default.

Exam-style questions · 6

Q1[2 marks]
Why must a variable be initialised before it is read?
Answer

A declared but uninitialised variable contains whatever data happened to already be in that memory location — not zero. Reading it gives an unpredictable value that may differ between runs, producing bugs that appear and disappear.

Q2[2 marks]
What is the value of 9 / 2 and of 9 % 2 in C, given both operands are int?
Answer

9 / 2 is 4 — integer division discards the fractional part. 9 % 2 is 1, the remainder.

Q3[2 marks]
Explain the difference between = and ==, and why confusing them is dangerous in C.
Answer

= assigns a value; == tests equality. if (x = 5) assigns 5 to x and then treats the result as the condition, which is non-zero and therefore always true — so the branch always runs and x has been changed. C accepts this without error, so nothing warns you.

Q4[4 marks]
State the output of each: (i) printf("%d", 15/4); (ii) printf("%d", 15%4); (iii) printf("%f", 15.0/4); (iv) int i=5; printf("%d", i++);
Mark scheme
  1. (i) 3 — integer division discards the remaindernot 3.75 and not 4[1]
  2. (ii) 3 — the remainder when 15 is divided by 4[1]
  3. (iii) 3.750000 — one operand is a float, so the division is floating point%f prints six decimal places by default[1]
  4. (iv) 5 — the post-increment uses the value first and increments afterwardsi becomes 6 after the printf[1]

(i) 3 (ii) 3 (iii) 3.750000 (iv) 5

Q5[4 marks]
A program has int total = 17, count = 4; float avg;. Write the line that correctly calculates the average, and explain why the obvious version fails.
Mark scheme
  1. avg = (float) total / count;accept total / (float) count[1]
  2. Writing avg = total / count; divides two ints, giving 4the fractional part is discarded before assignment[1]
  3. Assigning that to a float then stores 4.0, so the float type does not rescue itthe damage is already done[1]
  4. The cast converts total to float before the division, so floating-point division is used and the answer is 4.25[1]

avg = (float) total / count; — the cast must come before the division, not after.

Q6[6 marks]
Consider this fragment: int a = 7, b = 2; float result; result = a / b; printf("%f", result);
  1. State the output and explain why.
  2. Give two different ways to correct it.
  3. Explain the difference between implicit and explicit type conversion.
Mark scheme
  1. Output is 3.000000not 3.5[1]
  2. Both a and b are int, so integer division is performed and gives 3; converting 3 to float afterwards produces 3.0the conversion happens too late[1]
  3. Fix 1: cast one operand — result = (float) a / b;[1]
  4. Fix 2: declare a or b as float, or divide by a float literal such as 2.0any second valid approach[1]
  5. Implicit conversion is performed automatically by the compiler when types are mixed, promoting the smaller type[1]
  6. Explicit conversion is requested by the programmer with a cast, and is needed when the automatic behaviour is not what you want — as here[1]

(a) 3.000000, because int/int is evaluated first (b) cast an operand, or make one a float (c) implicit is automatic promotion; explicit is a programmer-requested cast

10

Input and Output

Multiple choice · 8

Q1Which placeholder prints an integer?

  1. A%f
  2. B%d
  3. C%c
  4. D%s
Show answer

Correct answer: B — %d

%d is for int. %f is float, %c a single character and %s a string.

Q2printf("%.2f", 3.14159) outputs:

  1. A3.14159
  2. B3.14
  3. C3.141590
  4. D3
Show answer

Correct answer: B — 3.14

The .2 fixes the output at two decimal places. Plain %f would print six.

Q3The ampersand in scanf("%d", &n) supplies:

  1. Athe value of n
  2. Bthe address of n
  3. Ca pointer type
  4. Dthe size of n
Show answer

Correct answer: B — the address of n

scanf must write into the caller's variable, and C passes by value — so it needs the address rather than a copy of the value.

Q4Reading a string with scanf uses no ampersand because:

  1. Astrings are special-cased
  2. Ban array name already evaluates to an address
  3. Cstrings cannot be changed
  4. Dit is a compiler bug
Show answer

Correct answer: B — an array name already evaluates to an address

The array name is already the address of its first element, which is exactly what scanf requires.

Q5scanf("%s", name) with input "Ali Khan" stores:

  1. AAli Khan
  2. BAli
  3. CKhan
  4. Dnothing
Show answer

Correct answer: B — Ali

It stops at the first whitespace. "Khan" remains in the buffer and will be consumed by the next input operation, usually with confusing results.

Q6Writing 50 characters into a 20-character array causes:

  1. Aautomatic resizing
  2. Ba buffer overflow
  3. Ca compile error
  4. Dtruncation to 20
Show answer

Correct answer: B — a buffer overflow

C performs no bounds checking. The extra characters overwrite whatever memory follows the array, which is both a bug and a security vulnerability.

Q7printf("%d", 3.7):

  1. Aprints 3.7
  2. Bprints 3
  3. Cfails to compile
  4. Dcompiles and prints nonsense
Show answer

Correct answer: D — compiles and prints nonsense

printf trusts the placeholder and interprets the bits of the double as though they were an int. Nothing checks the mismatch.

Q8To read a full line of text including spaces you should use:

  1. Ascanf("%s", …)
  2. Bfgets(…)
  3. Cprintf(…)
  4. Dgetchar() once
Show answer

Correct answer: B — fgets(…)

fgets reads until a newline, keeps the spaces, and takes a length limit that prevents overflowing the array.

Exam-style questions · 6

Q1[2 marks]
Why does scanf require an ampersand before a variable name?
Answer

C passes arguments by value, so a function receives a copy and cannot alter the caller's variable. The & supplies the variable's address instead, and scanf writes the input through that address into the original variable.

Q2[2 marks]
Why is no ampersand used when reading a string with scanf?
Answer

An array name in C already evaluates to the address of its first element, so name is already what scanf needs. Writing &name would supply the address of the array itself, which is a different type.

Q3[2 marks]
What does %.2f do, and why is it needed?
Answer

It prints a floating-point value to exactly two decimal places. Plain %f prints six by default, so a price would appear as 249.990000 instead of 249.99.

Q4[4 marks]
Write a C program that reads the length and width of a rectangle as floats and prints the area to one decimal place.
Mark scheme
  1. #include <stdio.h> and int main() {[1]
  2. float length, width, area; with prompts before each input[1]
  3. scanf("%f", &length); and the same for width — ampersands requiredmissing & loses this mark[1]
  4. area = length * width; printf("Area = %.1f\n", area);%.1f for one decimal place[1]

Declare floats, prompt and scanf with &, multiply, print with %.1f.

Q5[4 marks]
Identify three faults in this fragment: int age; printf("Age: "); scanf("%f", age); printf("You are %s\n", age);
Mark scheme
  1. Fault 1: %f is used to read into an int — it should be %dtype mismatch in scanf[1]
  2. Fault 2: the ampersand is missing — it should be &agescanf needs the address[1]
  3. Fault 3: %s is used to print an int — it should be %dprintf would treat the number as a memory address and read from it[1]
  4. Corrected: scanf("%d", &age); and printf("You are %d\n", age);[1]

Wrong scanf placeholder, missing &, and wrong printf placeholder.

Q6[6 marks]
A program must read a student's full name and three subject marks, then display a formatted result line.
  1. Explain why scanf("%s", name) is unsuitable for a full name, and state what to use instead.
  2. Write the input section of the program.
  3. Explain what a buffer overflow is in this context and how it is avoided.
Mark scheme
  1. scanf("%s", …) stops reading at the first whitespace, so only the first word of the name is stored[1]
  2. The remainder stays in the input buffer and is picked up by the next scanf, corrupting the marksthe knock-on effect is the point[1]
  3. Use fgets(name, 30, stdin), which reads the whole line including spaces[1]
  4. char name[30]; int m1, m2, m3; then the fgets call and scanf("%d %d %d", &m1, &m2, &m3);three placeholders, three addresses[1]
  5. A buffer overflow occurs when more characters are written than the array can hold, overwriting adjacent memory[1]
  6. It is avoided by using a function that takes a length limit — fgets does, plain scanf("%s") does notthe limit is the defence[1]

(a) it stops at a space and leaves the rest to corrupt the next input; use fgets (b) fgets plus scanf with three ampersands (c) writing past the end of the array; fgets limits the length

11

Decision Constructs

Multiple choice · 8

Q1In C, the value −3 used as a condition is:

  1. Afalse
  2. Btrue
  3. Can error
  4. Dundefined
Show answer

Correct answer: B — true

Anything non-zero is true, including negative values. Only zero is false.

Q2if (x = 3) printf("yes"); will:

  1. Anever print
  2. Balways print, and set x to 3
  3. Cprint only when x is 3
  4. Dfail to compile
Show answer

Correct answer: B — always print, and set x to 3

The assignment produces 3, which is non-zero and therefore true. C compiles this silently, which is what makes it so dangerous.

Q3A stray semicolon in if (a > b); means the following block:

  1. Anever runs
  2. Bruns only if the condition is true
  3. Cruns every time
  4. Dcauses a compile error
Show answer

Correct answer: C — runs every time

The semicolon is the entire body of the if. The block that follows is unattached and executes unconditionally.

Q4Omitting break in a switch case causes:

  1. Aa compile error
  2. Bexecution to fall into the next case
  3. Cthe switch to restart
  4. Dthe default to run
Show answer

Correct answer: B — execution to fall into the next case

Execution continues through subsequent cases until it meets a break or the closing brace, producing several outputs where one was expected.

Q5A switch statement cannot test:

  1. Aan int variable
  2. Ba char variable
  3. Ca range of values
  4. Da constant
Show answer

Correct answer: C — a range of values

Each case must be a single constant value. A range needs ten separate cases or, more sensibly, an if with a && condition.

Q6In if (n != 0 && 100/n > 5), when n is 0 the division:

  1. Acauses a crash
  2. Bis never evaluated
  3. Creturns zero
  4. Dreturns infinity
Show answer

Correct answer: B — is never evaluated

Short-circuit evaluation stops as soon as the left operand is false, so the division is never attempted. This idiom is used precisely to prevent the crash.

Q7In a grading chain, testing marks >= 40 before marks >= 80 would:

  1. Awork correctly
  2. Bgive the lowest grade to everyone above 40
  3. Ccause a compile error
  4. Dskip the else
Show answer

Correct answer: B — give the lowest grade to everyone above 40

The chain stops at the first true condition, so a mark of 95 satisfies >= 40 first and never reaches the test for A.

Q8Stacked cases such as case 'a': case 'e': with no statements between them:

  1. Aare a syntax error
  2. Blet several values share one action
  3. Ceach need a break
  4. Drun only the first
Show answer

Correct answer: B — let several values share one action

This is deliberate fall-through: the empty cases run straight on into the first statement, so all the listed values do the same thing.

Exam-style questions · 6

Q1[2 marks]
What values does C treat as true and false in a condition?
Answer

Zero is false and any non-zero value is true. A comparison such as x > 5 produces 1 when true and 0 when false, but any non-zero number — including a negative one — is accepted as true.

Q2[2 marks]
What does if (x > 0); followed by a block do, and why?
Answer

The semicolon forms an empty statement which becomes the entire body of the if. The block that follows is then an ordinary block, unattached to the if, and executes every time regardless of x.

Q3[2 marks]
Why must each case in a switch normally end with break?
Answer

Without it, execution falls through into the following case and continues until a break or the closing brace is reached, so several cases run when only one was intended.

Q4[4 marks]
Write a C fragment that reads a mark and prints A for 80 and above, B for 60–79, C for 40–59 and F below 40.
Mark scheme
  1. if (marks >= 80) printf("A");the most restrictive condition first[1]
  2. else if (marks >= 60) printf("B");no need to test < 80 — reaching here means the first test failed[1]
  3. else if (marks >= 40) printf("C");[1]
  4. else printf("F");, with braces used throughout[1]

A descending chain of else-ifs from 80 down, with a final else.

Q5[4 marks]
Explain what is wrong with each: (i) if (x = 10) { … } (ii) a switch case with no break.
Mark scheme
  1. (i) = assigns rather than compares, so x is set to 10[1]
  2. The result, 10, is non-zero and therefore true, so the block always executes and the original value of x is lostboth consequences[1]
  3. (ii) Execution falls through into the next case[1]
  4. and continues through subsequent cases until a break or the closing brace, so multiple outputs appear where one was expected[1]

(i) assignment instead of comparison, always true, value destroyed (ii) fall-through runs the following cases too.

Q6[6 marks]
A program must classify a character as a vowel, a consonant, a digit, or something else.
  1. State whether a switch or an if-else chain is more suitable, with a reason.
  2. Write the vowel test using a switch, showing the use of fall-through.
  3. Explain why the digit test cannot use the same switch approach conveniently.
Mark scheme
  1. A switch suits the vowel test, since it compares one character variable against a small set of fixed constant values[1]
  2. An if-else chain would need five separate == comparisons joined with ||, which reads worse[1]
  3. switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u':the empty cases stack[1]
  4. printf("Vowel"); break; default: printf("Not a vowel"); }one statement serves all five vowels[1]
  5. A digit is a range — anything from '0' to '9' — and switch can only match individual constant values[1]
  6. Ten separate cases would be needed, so if (ch >= '0' && ch <= '9') is clearerthe range test is the point[1]

(a) switch, for a fixed set of values (b) five stacked cases sharing one statement (c) a digit is a range, and switch cannot express ranges

12

Loop Constructs

Multiple choice · 8

Q1for (i = 1; i <= 6; i++) executes how many times?

  1. A5
  2. B6
  3. C7
  4. D1
Show answer

Correct answer: B — 6

i takes 1, 2, 3, 4, 5, 6 — six values. Counting from 1 with <= gives exactly the upper bound as the count.

Q2for (i = 0; i <= 10; i++) executes:

  1. A10 times
  2. B11 times
  3. C9 times
  4. Dinfinitely
Show answer

Correct answer: B — 11 times

i takes 0 to 10 inclusive, which is eleven values. Starting from 0 should normally use < rather than <=.

Q3A loop guaranteed to run at least once is:

  1. Afor
  2. Bwhile
  3. Cdo-while
  4. Dnone of them
Show answer

Correct answer: C — do-while

It tests the condition after the body, so the body has already executed by the time the test is first evaluated.

Q4A while loop that never ends usually means:

  1. Athe condition is too complex
  2. Bnothing inside changes what the condition tests
  3. Cthe loop is nested
  4. Dbreak was used
Show answer

Correct answer: B — nothing inside changes what the condition tests

The condition can only become false if something inside the loop moves it towards false. If nothing does, it stays true for ever.

Q5Initialising total = 0 inside the loop instead of before it means:

  1. Ano difference
  2. Bthe total resets every pass and ends as the last value only
  3. Ca compile error
  4. Dthe loop runs twice
Show answer

Correct answer: B — the total resets every pass and ends as the last value only

Each pass wipes the accumulated value, so after the final pass the total holds only the contribution of that last iteration.

Q6After for (i = 0; i < 5; i++) completes, i holds:

  1. A4
  2. B5
  3. C0
  4. Dundefined
Show answer

Correct answer: B — 5

The loop ends when the test fails, and the test fails at i = 5. The last value actually used in the body was 4.

Q7Two nested loops running 8 and 5 times execute the inner body:

  1. A13 times
  2. B40 times
  3. C8 times
  4. D5 times
Show answer

Correct answer: B — 40 times

The inner loop runs completely for every pass of the outer one: 8 × 5 = 40.

Q8Which loop best suits "display a menu until the user chooses Exit"?

  1. Afor
  2. Bwhile
  3. Cdo-while
  4. Dnested for
Show answer

Correct answer: C — do-while

The menu must be shown before the user can choose anything, including Exit — so the body must run before the condition is tested.

Exam-style questions · 6

Q1[2 marks]
State the key difference between a while and a do-while loop.
Answer

A while loop tests its condition before the body, so it may run zero times. A do-while tests after the body, so it always runs at least once.

Q2[2 marks]
How many times does for (i = 0; i < 5; i++) execute, and what is i afterwards?
Answer

Five times, with i taking the values 0, 1, 2, 3 and 4. Afterwards i holds 5 — the test must fail for the loop to end, so i finishes one beyond the last value used.

Q3[2 marks]
Why is a do-while loop suitable for a menu?
Answer

The menu must be displayed before the user can choose an option, including the option to quit. A do-while runs the body first and tests afterwards, so the menu always appears at least once.

Q4[4 marks]
Write a C program that prints the sum of the numbers from 1 to 50.
Mark scheme
  1. int total = 0; initialised before the loopinside the loop it would reset every pass[1]
  2. for (int i = 1; i <= 50; i++)<= because the count starts at 1 and 50 must be included[1]
  3. total = total + i; inside the loopaccept total += i[1]
  4. printf("%d", total); after the loop, giving 1275inside the loop it would print fifty lines[1]

total = 0 before, the for loop accumulating, and the print after — output 1275.

Q5[4 marks]
This loop is intended to count down from 10 to 1 but never ends. Identify and fix the fault. int n = 10; while (n > 0) { printf("%d ", n); }
Mark scheme
  1. Nothing inside the loop changes n[1]
  2. So n > 0 remains true for ever and the loop never terminates — an infinite loopnaming it is expected[1]
  3. Add n--; inside the loop bodyaccept n = n - 1[1]
  4. It must be inside the braces; placed after the loop it would never runthe placement point is a mark[1]

No decrement. Add n--; inside the loop body.

Q6[6 marks]
A program must read ten marks, count how many are 50 or above, and report the count and the average.
  1. State which loop is appropriate and why.
  2. Write the program.
  3. Explain two placement decisions that affect whether it works.
Mark scheme
  1. A for loop, because the number of marks is known in advance to be tenthe reason is required[1]
  2. int total = 0, passes = 0, marks; declared and initialised before the loop[1]
  3. for (int i = 0; i < 10; i++) { scanf("%d", &marks); total += marks;ampersand required[1]
  4. if (marks >= 50) passes++; }the test is inside the loop, applied to each mark[1]
  5. The accumulators must be initialised before the loop; inside, they would reset on every pass and the total would end as the last mark only[1]
  6. The printf statements must come after the loop, and the average must use total / 10.0 so that floating-point division is performedinteger division would truncate[1]

(a) for, since ten is known (b) accumulators before, loop reads and tests, output after (c) initialise before, print after, and divide by 10.0

13

Functions in C

Multiple choice · 8

Q1In int square(int n) called as square(4), the argument is:

  1. An
  2. B4
  3. Cint
  4. Dsquare
Show answer

Correct answer: B — 4

4 is the actual value supplied at the call. n is the parameter that receives it.

Q2C passes arguments to functions:

  1. Aby reference
  2. Bby value
  3. Cby name
  4. Dby address always
Show answer

Correct answer: B — by value

The function receives a copy, which is why changing a parameter leaves the caller's variable untouched.

Q3void f(int x) { x = 99; } called with f(a) where a is 5 leaves a as:

  1. A99
  2. B5
  3. C0
  4. Dundefined
Show answer

Correct answer: B — 5

x is a copy. Assigning to it changes only that copy, which is discarded when the function returns.

Q4To let a function modify the caller's variable you pass:

  1. Athe value
  2. Bthe address
  3. Ca global
  4. Da copy
Show answer

Correct answer: B — the address

The address gives the function a route back to the original storage, which is exactly what the & in scanf provides.

Q5A function prototype is placed:

  1. Aafter main
  2. Bbefore main
  3. Cinside main
  4. Din a separate program
Show answer

Correct answer: B — before main

It must appear before any call, and C reads the file from the top, so above main is the conventional place.

Q6A variable declared inside a function is:

  1. Aglobal
  2. Blocal, existing only during the call
  3. Cpermanent
  4. Dshared with all functions
Show answer

Correct answer: B — local, existing only during the call

It is created when the function starts and destroyed when it returns, which is what keeps functions independent of each other.

Q7Global variables are discouraged because:

  1. Athey are slower
  2. Bany function can change them, making faults hard to trace
  3. Cthey use more memory
  4. DC does not allow them
Show answer

Correct answer: B — any function can change them, making faults hard to trace

When a global holds a wrong value, the culprit could be any function in the program. Parameters and return values keep the effects visible.

Q8A recursive function without a base case will:

  1. Areturn 0
  2. Brun until memory is exhausted
  3. Crefuse to compile
  4. Dcall itself once
Show answer

Correct answer: B — run until memory is exhausted

Each call makes another, and every one consumes stack space. Eventually the stack overflows and the program crashes.

Exam-style questions · 6

Q1[2 marks]
State two advantages of using functions.
Answer

Reusability — code written once can be called many times, so a correction is made in one place. Testability and readability — each function can be understood and tested on its own, and a long program becomes a set of short comprehensible pieces.

Q2[2 marks]
Differentiate between a parameter and an argument.
Answer

A parameter is the variable named in the function definition, which receives a value. An argument is the actual value supplied at the point of call. In square(6) calling int square(int n), n is the parameter and 6 is the argument.

Q3[2 marks]
Why is a function prototype needed?
Answer

C processes a file from top to bottom, so a function called before its definition appears has not yet been seen by the compiler. A prototype placed above main declares the name, return type and parameter types in advance, allowing the call to be checked.

Q4[4 marks]
Write a C function that takes two integers and returns the larger, and show how it is called.
Mark scheme
  1. int larger(int a, int b) { — correct return type and two int parameters[1]
  2. if (a > b) return a;[1]
  3. else return b; }every path must return a value[1]
  4. Called as int max = larger(7, 3); with the returned value stored or usedcalling it without using the result wastes it[1]

int larger(int a, int b) with an if-else returning a or b, called as larger(7, 3).

Q5[4 marks]
Explain why a C function cannot normally change a variable belonging to the caller, and how it can be made to.
Mark scheme
  1. C passes arguments by value — the function receives a copy of the argument[1]
  2. The parameter is a separate variable, so assigning to it changes only the copy, which is discarded when the function ends[1]
  3. To change the original, pass its address using &, and declare the parameter as a pointer[1]
  4. The function then writes through that address with *, reaching the caller's variable — which is exactly what scanf doesthe scanf connection earns the mark[1]

Pass by value means the function gets a copy. Pass the address instead and write through the pointer.

Q6[6 marks]
A program calculates the area of several circles.
  1. Write a function that takes a radius and returns the area, using a constant for π.
  2. Explain the difference between a local and a global variable, and which the function should use.
  3. Explain what would happen if the function were called before being declared or defined.
Mark scheme
  1. #define PI 3.14159 or const float PI = 3.14159;[1]
  2. float area(float r) { return PI * r * r; }float return type and parameter[1]
  3. A local variable is declared inside a function and exists only while it runs; a global is declared outside all functions and is visible everywhere[1]
  4. The radius should be a parameter and any working values local, so the function depends only on what it is given and cannot be affected by the rest of the program[1]
  5. C reads the file top to bottom, so calling it earlier with no prototype means the compiler has not seen the declaration[1]
  6. The compiler reports an error, or in older C assumes a default return type of int and produces a wrong result silentlythe silent-failure case is the sharper point[1]

(a) float area(float r) returning PI * r * r (b) local for working values; parameters for input (c) an error, or in older C a silent wrong result from an assumed int return

14

File Handling in C

Multiple choice · 8

Q1Opening an existing file with mode "w":

  1. Aappends to it
  2. Berases its contents
  3. Cfails with NULL
  4. Dopens it read-only
Show answer

Correct answer: B — erases its contents

It truncates the file to zero length at the moment of opening, before anything has been written.

Q2To add a record without losing existing ones, use mode:

  1. A"r"
  2. B"w"
  3. C"a"
  4. D"x"
Show answer

Correct answer: C — "a"

Append preserves the contents and writes at the end. "w" would destroy every previous record.

Q3fopen returns NULL when:

  1. Athe file is empty
  2. Bthe file cannot be opened
  3. Cthe file is large
  4. Dreading succeeds
Show answer

Correct answer: B — the file cannot be opened

It may be missing, locked, or in a location you lack permission for. Using the NULL pointer afterwards crashes the program.

Q4Which is the file version of printf?

  1. Afput
  2. Bfprintf
  3. Cwritef
  4. Dprintfile
Show answer

Correct answer: B — fprintf

It takes the file pointer as its first argument and is otherwise identical in use.

Q5while (!feof(fp)) typically causes:

  1. Aan infinite loop
  2. Bthe last record to be processed twice
  3. Ca compile error
  4. Dthe file to be erased
Show answer

Correct answer: B — the last record to be processed twice

feof only becomes true after a read has already failed, so the body executes once more using the values from the previous successful read.

Q6The reliable way to loop until the end of a file is to:

  1. Acount the lines first
  2. Btest the return value of the read
  3. Cuse feof
  4. Dread the file twice
Show answer

Correct answer: B — test the return value of the read

The read itself reports how many items it obtained, so the loop ends exactly when a read fails rather than one pass later.

Q7Omitting fclose after writing may result in:

  1. Anothing at all
  2. Bbuffered data never reaching the disk
  3. Cthe file being deleted
  4. Da compile error
Show answer

Correct answer: B — buffered data never reaching the disk

Writes are buffered for speed. fclose flushes the buffer, and without it the most recent data may be lost when the program ends.

Q8A file pointer is declared as:

  1. Aint fp;
  2. BFILE *fp;
  3. Cchar fp[];
  4. Dfile fp;
Show answer

Correct answer: B — FILE *fp;

FILE is a type defined in stdio.h, and fopen returns a pointer to it.

Exam-style questions · 6

Q1[2 marks]
Why are files needed when a program already has variables?
Answer

Variables are held in RAM, which is volatile — their contents are lost the moment the program ends or the power fails. A file is stored on secondary storage, so the data persists and can be read by the same program on another day or by a different program entirely.

Q2[2 marks]
What does fopen return if it fails, and why must this be checked?
Answer

It returns NULL. Using a NULL file pointer in any subsequent read or write causes the program to crash, so the check turns an unexplained failure into a clear message such as "cannot open file".

Q3[2 marks]
State the difference between opening a file in "w" mode and "a" mode.
Answer

"w" erases the entire contents of an existing file the moment it is opened, then writes from the beginning. "a" preserves the contents and adds new data at the end. Both create the file if it does not exist.

Q4[4 marks]
Write a C fragment that opens "data.txt" for reading, checks it opened, reads and prints integers until the end, and closes it.
Mark scheme
  1. FILE *fp; int n; fp = fopen("data.txt", "r");[1]
  2. if (fp == NULL) { printf("Cannot open file\n"); return 1; }the NULL check is a mark[1]
  3. while (fscanf(fp, "%d", &n) == 1) { printf("%d\n", n); }testing the return value, not feof[1]
  4. fclose(fp);[1]

Open, check NULL, loop while fscanf returns 1, close.

Q5[4 marks]
A program should add a new record to an existing file but instead the file contains only the newest record. Explain the fault and its correction.
Mark scheme
  1. The file has been opened in "w" mode instead of "a"[1]
  2. "w" truncates the file to zero length as soon as it is opened, destroying every existing recordthe truncation happens on opening[1]
  3. The new record is then written into an empty file, which is why only it remains[1]
  4. Correct it by opening with "a", which preserves the contents and appends at the end[1]

The file was opened with "w", which truncates it. Use "a" to append.

Q6[6 marks]
A school stores student marks in a text file, one record per line as a name followed by a mark.
  1. Write the code to read the file and count how many students scored 50 or above.
  2. Explain why fclose must be called.
  3. Explain why while (!feof(fp)) is an unreliable loop condition.
Mark scheme
  1. Opens the file in "r" mode and checks the pointer is not NULL[1]
  2. while (fscanf(fp, "%s %d", name, &marks) == 2) {two items requested, two expected back[1]
  3. if (marks >= 50) count++; } then prints the count after the loopcount initialised before the loop[1]
  4. fclose flushes the output buffer, so data still held in memory is actually written to disk[1]
  5. It also releases the file handle, a limited operating-system resource that would otherwise run out[1]
  6. feof becomes true only after a read has already failed, so the loop body runs one extra time and the previous values are processed twicetesting the read's return value avoids this[1]

(a) open, check, loop on fscanf == 2 counting passes (b) flushes the buffer and releases the handle (c) feof is set after a failed read, so the last record is processed twice

These questions come from the 2nd Year Computer Science lessons — each topic has its own notes, worked examples and an interactive diagram.