Q1All the details of one student form a:
- Afield
- Brecord
- Ctable
- 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.
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.
Q1All the details of one student form a:
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:
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:
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?
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:
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:
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:
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:
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.
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.
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.
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.
Redundancy, inconsistency, data dependence, and poor security or difficult queries.
Text, integer, currency, date — each justified by what will be done with it.
(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
Q1A field that uniquely identifies each record is the:
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:
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:
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:
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:
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?
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:
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:
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.
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.
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.
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.
Integrity, security, concurrency control, backup and recovery, and a query language.
Two tables, with InstructorID as a foreign key in STUDENT.
(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
Q1Which design stage depends on the DBMS chosen?
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:
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:
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:
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:
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:
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:
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:
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.
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.
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.
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.
TITLE and PUBLISHER, in a 1:M relationship, with PublisherID as a foreign key in TITLE.
A field holds one value, so a linking table with both foreign keys is required, giving two 1:M relationships.
(a) MEMBER, CLASS, INSTRUCTOR (b) instructor–class 1:M, member–class M:N (c) four tables, with ATTENDANCE linking members to classes
Q1A rule that a mark must be between 0 and 100 is a:
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:
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:
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:
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:
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:
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:
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:
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.
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.
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.
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.
Insertion, deletion and update anomalies, all caused by storing a fact in more than one row.
A transitive dependency; split into STUDENT and CLASS tables.
(a) redundancy and update anomalies (b) MEMBER, BOOK and LOAN (c) single-point updates, at the cost of joins
Q1Which Access object stores the actual data?
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:
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:
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?
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:
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:
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:
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:
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.
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.
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.
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.
>=11 And <=19the boundary values are included[1]Number/Integer, validation rule, validation text, and Required = Yes.
It blocks unmatched foreign keys and unsafe deletions; Cascade Delete removes the children instead, which is often not what is wanted.
(a) enforced integrity and linked tables (b) few concurrent users, size and platform limits (c) growth in users or a need for web access
Q1A query in Access stores:
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:
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?
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:
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:
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:
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:
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:
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.
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.
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.
Like "A*" select?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.
SELECT Name, Marksonly the requested columns[1]FROM STUDENT[1]WHERE Marks > 50no quotation marks — Marks is numeric[1]ORDER BY Marks DESCDESC is required for highest first[1]SELECT Name, Marks FROM STUDENT WHERE Marks > 50 ORDER BY Marks DESC
Is Null finds the empty ones; =0 finds the zeros[1]Null is unknown, 0 is a known value. Is Null and =0 respectively; averages treat them differently.
SELECT Title, DateDue[1]FROM BOOK INNER JOIN LOAN ON BOOK.ISBN = LOAN.ISBNjoined on the shared key[1]WHERE DateDue < #1/3/2026#dates enclosed in hash symbols[1]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
Q1Which Access object is read-only?
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:
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:
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:
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:
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:
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:
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:
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.
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.
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.
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.
Report Header, Page Header, Detail, Group and Report Footers — each printing at a different frequency.
It prevents rather than detects, stores the key while showing the name, and stays current automatically.
(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
Q1Execution of a C program begins at:
Correct answer: C — main()
Whatever order the functions appear in, the operating system calls main first.
Q2A missing semicolon produces a:
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:
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:
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:
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:
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:
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:
Correct answer: C — logical
The other three announce themselves. A logical error produces a program that builds cleanly, runs quietly and is wrong.
#include <stdio.h> and of main()?#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.
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.
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.
Preprocessing, compilation, assembly, linking.
#include <stdio.h>without it printf is undeclared[1]int main() { with a matching closing brace[1]printf statements, each ending in a semicolon, with \n for the line breaka single printf with two \n is equally acceptable[1]return 0; before the closing brace[1]include, main, two printf calls with newlines, return 0.
(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
Q1In C, int x; printf("%d", x); prints:
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:
Correct answer: C — 2
Integer division truncates towards zero, so 2.75 becomes 2. There is no rounding.
Q311 % 4 gives:
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:
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:
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:
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?
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:
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.
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.
9 / 2 and of 9 % 2 in C, given both operands are int?9 / 2 is 4 — integer division discards the fractional part. 9 % 2 is 1, the remainder.
= and ==, and why confusing them is dangerous in C.= 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.
printf("%d", 15/4); (ii) printf("%d", 15%4); (iii) printf("%f", 15.0/4); (iv) int i=5; printf("%d", i++);3 — integer division discards the remaindernot 3.75 and not 4[1]3 — the remainder when 15 is divided by 4[1]3.750000 — one operand is a float, so the division is floating point%f prints six decimal places by default[1]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
int total = 17, count = 4; float avg;. Write the line that correctly calculates the average, and explain why the obvious version fails.avg = (float) total / count;accept total / (float) count[1]avg = total / count; divides two ints, giving 4the fractional part is discarded before assignment[1]avg = (float) total / count; — the cast must come before the division, not after.
int a = 7, b = 2; float result; result = a / b; printf("%f", result);3.000000not 3.5[1]result = (float) a / b;[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
Q1Which placeholder prints an integer?
Correct answer: B — %d
%d is for int. %f is float, %c a single character and %s a string.
Q2printf("%.2f", 3.14159) outputs:
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:
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:
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:
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:
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):
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:
Correct answer: B — fgets(…)
fgets reads until a newline, keeps the spaces, and takes a length limit that prevents overflowing the array.
scanf require an ampersand before a variable name?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.
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.
%.2f do, and why is it needed?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.
#include <stdio.h> and int main() {[1]float length, width, area; with prompts before each input[1]scanf("%f", &length); and the same for width — ampersands requiredmissing & loses this mark[1]area = length * width; printf("Area = %.1f\n", area);%.1f for one decimal place[1]Declare floats, prompt and scanf with &, multiply, print with %.1f.
int age; printf("Age: "); scanf("%f", age); printf("You are %s\n", age);%f is used to read into an int — it should be %dtype mismatch in scanf[1]&agescanf needs the address[1]%s is used to print an int — it should be %dprintf would treat the number as a memory address and read from it[1]scanf("%d", &age); and printf("You are %d\n", age);[1]Wrong scanf placeholder, missing &, and wrong printf placeholder.
scanf("%s", name) is unsuitable for a full name, and state what to use instead.scanf("%s", …) stops reading at the first whitespace, so only the first word of the name is stored[1]fgets(name, 30, stdin), which reads the whole line including spaces[1]char name[30]; int m1, m2, m3; then the fgets call and scanf("%d %d %d", &m1, &m2, &m3);three placeholders, three addresses[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
Q1In C, the value −3 used as a condition is:
Correct answer: B — true
Anything non-zero is true, including negative values. Only zero is false.
Q2if (x = 3) printf("yes"); will:
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:
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:
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:
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:
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:
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:
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.
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.
if (x > 0); followed by a block do, and why?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.
break?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.
if (marks >= 80) printf("A");the most restrictive condition first[1]else if (marks >= 60) printf("B");no need to test < 80 — reaching here means the first test failed[1]else if (marks >= 40) printf("C");[1]else printf("F");, with braces used throughout[1]A descending chain of else-ifs from 80 down, with a final else.
if (x = 10) { … } (ii) a switch case with no break.= assigns rather than compares, so x is set to 10[1](i) assignment instead of comparison, always true, value destroyed (ii) fall-through runs the following cases too.
switch (ch) { case 'a': case 'e': case 'i': case 'o': case 'u':the empty cases stack[1]printf("Vowel"); break; default: printf("Not a vowel"); }one statement serves all five vowels[1]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
Q1for (i = 1; i <= 6; i++) executes how many times?
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:
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:
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:
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:
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:
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:
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"?
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.
while and a do-while loop.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.
for (i = 0; i < 5; i++) execute, and what is i afterwards?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.
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.
int total = 0; initialised before the loopinside the loop it would reset every pass[1]for (int i = 1; i <= 50; i++)<= because the count starts at 1 and 50 must be included[1] total = total + i; inside the loopaccept total += i[1]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.
int n = 10; while (n > 0) { printf("%d ", n); }n[1]n > 0 remains true for ever and the loop never terminates — an infinite loopnaming it is expected[1]n--; inside the loop bodyaccept n = n - 1[1]No decrement. Add n--; inside the loop body.
int total = 0, passes = 0, marks; declared and initialised before the loop[1]for (int i = 0; i < 10; i++) { scanf("%d", &marks); total += marks;ampersand required[1]if (marks >= 50) passes++; }the test is inside the loop, applied to each mark[1]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
Q1In int square(int n) called as square(4), the argument is:
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:
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:
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:
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:
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:
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:
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:
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.
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.
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.
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.
int larger(int a, int b) { — correct return type and two int parameters[1] if (a > b) return a;[1] else return b; }every path must return a value[1]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).
&, and declare the parameter as a pointer[1]*, 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.
#define PI 3.14159 or const float PI = 3.14159;[1]float area(float r) { return PI * r * r; }float return type and parameter[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
Q1Opening an existing file with mode "w":
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:
Correct answer: C — "a"
Append preserves the contents and writes at the end. "w" would destroy every previous record.
Q3fopen returns NULL when:
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?
Correct answer: B — fprintf
It takes the file pointer as its first argument and is otherwise identical in use.
Q5while (!feof(fp)) typically causes:
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:
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:
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:
Correct answer: B — FILE *fp;
FILE is a type defined in stdio.h, and fopen returns a pointer to it.
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.
fopen return if it fails, and why must this be checked?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".
"w" mode and "a" mode."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.
FILE *fp; int n; fp = fopen("data.txt", "r");[1]if (fp == NULL) { printf("Cannot open file\n"); return 1; }the NULL check is a mark[1]while (fscanf(fp, "%d", &n) == 1) { printf("%d\n", n); }testing the return value, not feof[1]fclose(fp);[1]Open, check NULL, loop while fscanf returns 1, close.
"w" mode instead of "a"[1]"a", which preserves the contents and appends at the end[1]The file was opened with "w", which truncates it. Use "a" to append.
fclose must be called.while (!feof(fp)) is an unreliable loop condition.while (fscanf(fp, "%s %d", name, &marks) == 2) {two items requested, two expected back[1] if (marks >= 50) count++; } then prints the count after the loopcount initialised before the loop[1]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.