LC Computer Science study materials
LC Computer Science study resources

LC Computer Science practice questions

One question at a time. Build your LC Computer Science understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Practices and principles

In computational thinking, what is the main purpose of abstraction when building a model of a problem?

  1. To identify similarities between the current problem and previously solved ones
  2. To hide detail that is irrelevant so the model keeps only what matters Correct answer.
  3. To convert the finished design into code that a computer can execute directly
  4. To break a large problem into smaller sub-problems that are easier to solve

Explanation

Abstraction deliberately hides detail that is irrelevant to the task so the model keeps only the features needed to solve the problem. Decomposition, pattern recognition and coding are separate practices, so the other options describe different stages rather than abstraction.

Question 2Practices and principles

A student writes a sequence of steps to solve a problem. Which property must the sequence have to count as an algorithm?

  1. It must end after a finite number of steps Correct answer.
  2. It must be no longer than twenty lines
  3. It must be written in a programming language
  4. It must contain at least one loop

Explanation

An algorithm is a finite, ordered set of unambiguous steps that solves a problem, so it must stop after a limited number of steps. Language choice, loops and length are implementation details and are not required properties of an algorithm.

Question 3Practices and principles

A program runs without crashing but prints the average of a list of numbers as a value that is always too high. Which type of error is this?

  1. A syntax error in the print statement
  2. A runtime error caused by invalid input
  3. A logic error in the calculation Correct answer.
  4. An error in the compiler's optimiser

Explanation

A logic error means the program runs to completion and produces output, but the output is not what was intended, for example because the wrong formula was used. Syntax and runtime errors stop the program from running or crash it during execution, so they do not match a program that runs and prints a wrong value.

Question 4Practices and principles

A light is controlled by two switches, A and B. The light should be on only when exactly one of the switches is on. Which Boolean expression gives this behaviour?

  1. A XOR B Correct answer.
  2. A AND B
  3. NOT (A AND B)
  4. A OR B

Explanation

Exclusive OR returns true when exactly one input is true and false when both inputs are the same, which matches a light controlled by two switches. AND requires both switches on, OR allows both on, and NOT (A AND B) is still true when both switches are off.

Question 5Practices and principles

Consider this pseudocode. set total to 0 set i to 1 while i < 5 do total = total + i i = i + 1 end while What is the value of total when the loop ends?

  1. 10 Correct answer.
  2. 5
  3. 4
  4. 15

Explanation

The loop runs while i is less than 5, so it adds 1, 2, 3 and 4 before i becomes 5 and the condition fails. The running total is therefore 1 + 2 + 3 + 4 = 10, and the value 5 is never added.

Question 6Practices and principles

A function accepts an integer mark and should return 'pass' for marks from 40 to 100 inclusive and 'fail' otherwise. Which set of test inputs best checks the boundary between the two outcomes?

  1. 40, 60 and 80
  2. 0, 50 and 100
  3. 39, 40, 100 and 101 Correct answer.
  4. 41, 42 and 43

Explanation

Boundary testing checks the values at and just outside each edge of a valid range, so 39, 40, 100 and 101 exercise both ends of the pass range. Testing only middle values or only one side can miss an off-by-one mistake in a comparison operator.

Question 7Practices and principles

A team uses a version control system. A developer creates a branch to add a new feature. What is the main benefit of working on a branch rather than directly on the main branch?

  1. The branch permanently deletes conflicting changes made by teammates
  2. The new code is compiled faster than code on the main branch
  3. The feature code is automatically tested before it is written
  4. Changes can be developed and reviewed without breaking the stable main code Correct answer.

Explanation

A branch is an independent line of development, so work on it does not change the main branch until it is merged. This lets the team keep a stable main version while the feature is developed and reviewed, and then combine the changes deliberately.

Question 8Practices and principles

Consider this pseudocode. set count to 0 for each value in [3, 8, 4, 7, 10] do if value mod 2 = 0 then count = count + 1 end if end for What is count at the end?

  1. 3 Correct answer.
  2. 5
  3. 4
  4. 2

Explanation

The loop examines every value and increments count only when value mod 2 equals 0, which is true for 8, 4 and 10. The odd values 3 and 7 are skipped, so count finishes at 3.

Question 9Practices and principles

A nested loop performs one operation for every pair (i, j), where i ranges from 1 to n and j ranges from 1 to n. If n is doubled from 50 to 100, by what factor does the number of operations grow?

  1. It grows by a factor of about 4 Correct answer.
  2. It grows by a factor of about 2
  3. It stays the same
  4. It grows by a factor of about 100

Explanation

The inner statement runs once for every pair of i and j, so the total number of operations is n x n, which is quadratic. Doubling n gives (2n) squared, which is 4n squared, so the work grows by a factor of about four rather than two.

Question 10Practices and principles

A login check rejects a user unless both a valid username u and a valid password p are supplied. Using u and p, which expression correctly represents the condition for rejecting the login?

  1. u AND (NOT p)
  2. (NOT u) AND (NOT p)
  3. (NOT u) OR (NOT p) Correct answer.
  4. NOT (u OR p)

Explanation

The user is rejected whenever it is not the case that both u and p are true. By De Morgan's law this is equivalent to (NOT u) OR (NOT p), so the login is rejected if the username is invalid, the password is invalid, or both are invalid.

Question 11Practices and principles

A student is building a quiz application. She divides the work into separate parts: loading questions from a file, checking answers, tracking the score and displaying results. Which computational-thinking technique is she mainly using?

  1. Abstraction, because the file format is hidden from the player
  2. Pattern recognition, because each part repeats the same steps
  3. Decomposition Correct answer.
  4. Algorithm design, because each part is completed in turn

Explanation

Decomposition is the computational-thinking technique of breaking a large, complex problem into smaller sub-problems that can be planned, written and tested separately. The four parts described each handle one concern of the quiz application and can be joined together once each one works. Abstraction, pattern recognition and algorithm design are related techniques, but none of them describes splitting the project up in this way.

Question 12Practices and principles

A developer finishes a working change, saves it to the project history with a short message describing what was done, and can return to that state later. Which version control operation is this?

  1. A merge, which combines work from two branches
  2. A commit, which records a snapshot with a message Correct answer.
  3. A clone, which copies the repository to a new machine
  4. A tag, which labels a particular point in the history

Explanation

A commit records a snapshot of the tracked files together with the author, the time and a message, and it becomes part of the project history that can be reviewed or restored. Merging combines the changes made on different branches, cloning copies a whole repository, and a tag is only a fixed label on an existing commit rather than a record of new work.

Question 13Practices and principles

Before a feature is merged, a team asks a second developer to read the new code and comment on it. What is the main purpose of this code review?

  1. To catch defects and improve quality early Correct answer.
  2. To compile the source code into an executable program
  3. To raise the execution speed of the finished program
  4. To remove the need for testing the feature

Explanation

Code review is a collaborative inspection in which other developers read a pending change to spot logic errors, unclear code, missing tests and style problems before it is integrated. It supports testing rather than replacing it, because a reviewer cannot execute every path through the code. Reviewing source has no effect on how fast the compiled program will run.

Question 14Practices and principles

A function `discount(age)` should return 10 when age is under 18 and 0 otherwise. Which set of test inputs best checks the decision?

  1. {17, 18}
  2. {5, 17, 18, 65} Correct answer.
  3. {18, 30, 45}
  4. {0, 100}

Explanation

Good test data includes typical values from each branch plus the boundary values where behaviour changes. Here 17 and 18 sit either side of the boundary and 5 and 65 are ordinary values within each branch, so both outcomes and the boundary itself are exercised. Boundary values alone test less, and inputs drawn from a single branch can leave the other branch unchecked.

Question 15Practices and principles

A list `scores` holds n values, indexed 1 to n in the pseudocode. A student writes: set total to 0 for i = 1 to n - 1 do total = total + scores[i] end for The total is always too small. Which change fixes the fault?

  1. Change the loop to `for i = 1 to n do` Correct answer.
  2. Move the line `total = total + scores[i]` outside the loop
  3. Change the loop to `for i = 1 to n - 2 do`
  4. Initialise total to scores[1] before the loop

Explanation

The loop stops at n - 1, so the final element scores[n] is never added and the total is short by one value. Running the loop to n includes every element, which is correct for a 1-indexed list of n items. The other changes either skip more values, double-count the first value, or add a single value once.

Question 16Practices and principles

A student builds a school app that stores user accounts. Which practice best protects the users' passwords if the database is later stolen?

  1. Encrypt the passwords with a key kept in the source code
  2. Store the passwords in a table that ordinary users cannot see
  3. Store each password in plain text so that it can be recovered
  4. Store each password as a salted hash Correct answer.

Explanation

A salted hash is one-way, so the stored value cannot be turned back into the password, and a unique salt per user stops identical passwords producing identical stored values or being matched against precomputed tables. Plain text, hidden tables and encryption keys kept beside the data all leave the passwords recoverable to anyone who obtains the database or the program.

Question 17Practices and principles

A program must repeatedly look up surnames in a list of 50,000 names that is already sorted alphabetically. Which search method is most suitable, and why?

  1. Binary search, because it does not need the list to be in order
  2. Linear search, because it works on a list in any order without preparation
  3. Linear search, because it checks every name exactly once
  4. Binary search, because each comparison halves the sorted range Correct answer.

Explanation

Binary search works only on ordered data, but it needs roughly log2(50,000), about 16 comparisons per lookup rather than up to 50,000, because each comparison discards half of the remaining range. Linear search is simpler and needs no ordering, yet on a large sorted list it is far slower for repeated searches.

Question 18Practices and principles

A program is meant to delete every negative number from a list. It uses an index `i` that starts at 0 and increases by 1 after each pass; when the element at `i` is negative it is deleted and `i` is not changed. Some negative numbers remain in the list. Why?

  1. Deleting shifts later elements left, so the element that slides into index i is skipped Correct answer.
  2. Deleting an element changes the length, so every index after the deletion point becomes invalid
  3. Negative numbers are compared incorrectly because the loop uses an integer index
  4. Modifying a list inside a loop is not permitted in most programming languages

Explanation

Removing an item shifts every later item one position to the left, so the item that was at i + 1 moves to i just as the index advances past it, and that element is never examined. The usual fixes are to step through the list backwards or to decrement the index after each deletion. The list length does change, but indexes are recalculated on each pass, so the shift is the real cause.

Question 19Practices and principles

A loop is written as `while i < length(items) and items[i] <> target do`. If the two conditions were swapped, what would happen when the target is not in the list?

  1. The loop would end early and so would never examine the final element of the list
  2. The loop would still work correctly for every possible input
  3. items[i] would be read before the bounds check, so an out-of-range error could occur Correct answer.
  4. The program would run more slowly than before but would produce exactly the same result

Explanation

Most languages evaluate `and` from left to right and stop as soon as one condition is false, so the length test must come first to guard the list access. Swapping the order means items[i] is evaluated when i has reached length, which is outside the list and raises an index error. This is a run-time failure, not merely a slowdown or a missed final element.

Question 20Practices and principles

A student's function begins with `def calc(a, b):` and has no documentation. Six months later teammates cannot tell what it does. Which change best improves maintainability?

  1. Add the comment `# this function calculates` at the top of the function
  2. Rename it `calc2` so that it is clearly the newer version of the function
  3. Rename it `rectangle_area(length, width)` and document what it returns Correct answer.
  4. Add extra blank lines and comment markers so the function stands out from the code around it

Explanation

Descriptive names for the function and its parameters make its purpose clear at the point of call, and a short docstring records what it expects and returns, which is exactly what future maintainers need. A comment that only restates that the function calculates something adds no information. Layout changes such as blank lines and comment banners affect appearance only.

Question 21Practices and principles

A student desk-checks an algorithm by hand before running it. Why does the student record the value of each variable after every step in a trace table?

  1. To prove that the algorithm uses the fewest possible lines of code.
  2. To confirm that every variable has been declared with the correct data type.
  3. To estimate how many processor cycles the algorithm will need on the target machine.
  4. To compare values with the expected results and find where they diverge. Correct answer.

Explanation

A trace table records the state of each variable after every step of a hand-run algorithm. Comparing those recorded values with the expected results shows exactly where the logic first goes wrong, which is the purpose of desk checking. It is not a measure of performance, line count or declaration correctness.

Question 22Practices and principles

A developer checks a single function by calling it with several chosen inputs and comparing each returned value with the expected result before the function is used in the full program. Which term describes this activity?

  1. Integration testing
  2. Unit testing Correct answer.
  3. Usability testing
  4. Acceptance testing

Explanation

Unit testing checks one function or module in isolation, using chosen inputs with known expected outputs. Integration testing then checks how components work together, while acceptance and usability testing involve users and the complete system rather than a single function.

Question 23Practices and principles

A program contains variables named `a`, `b`, `x1` and `temp2`. Which revision best supports later maintenance of the program?

  1. Rename each variable to describe the value it stores, such as `totalScore`. Correct answer.
  2. Replace the names with single letters chosen in alphabetical order.
  3. Add a comment above every line that uses one of the variables.
  4. Shorten the names further so the lines of code are easier to read quickly.

Explanation

Identifiers that describe the stored value make code self-documenting, so a maintainer can understand an assignment without tracing every use. Comments can help but often drift out of date, while shortening names or using single letters makes the meaning harder to recover.

Question 24Practices and principles

A developer pauses a running program at a chosen line inside a loop using a debugger. Which task does this pause make easiest?

  1. Removing syntax errors from the source file before compilation.
  2. Checking that the source file is stored in version control.
  3. Inspecting the current values of variables at that point in the loop. Correct answer.
  4. Measuring the total runtime of the completed program.

Explanation

A breakpoint suspends execution at a chosen line so the developer can inspect current variable values and step through subsequent statements one at a time. Syntax errors must be fixed before a program can run, and total runtime is measured by timing tools rather than breakpoints.

Question 25Practices and principles

An online form asks for a date and immediately rejects `31/02/2010` because February never has 31 days. Which term best describes this check?

  1. Compilation
  2. Authentication
  3. Validation Correct answer.
  4. Verification

Explanation

Validation checks that input is reasonable and obeys allowed rules, such as a date that actually exists, before the data is processed. Verification is the separate activity of confirming that the finished system meets its requirements, so it does not describe a check on one entered value.

Question 26Practices and principles

A program must read a data file that may be missing on the user's computer. Which approach best keeps the program robust when the file is absent?

  1. Read the file at the very end of the program so any error is less noticeable.
  2. Declare the file name as a global variable so every procedure can access it.
  3. Check that the file can be opened and handle failure with a clear message. Correct answer.
  4. Assume the file will always be present, because the programmer created it on the development machine.

Explanation

Defensive programming checks that a needed resource such as a file is available and handles failure gracefully, for example with a message or a fallback path. Assuming the file exists or postponing the read leaves the user facing an unhandled exception instead of a useful response.

Question 27Practices and principles

A single module in a program loads pupil records, checks them, prints reports and writes log entries. Which change best improves the design of this module?

  1. Split the four tasks into separate modules, each with one clear responsibility. Correct answer.
  2. Move all four tasks into the main program so the module becomes shorter.
  3. Add comments explaining each of the four tasks inside the module.
  4. Keep the four tasks together but rename the module to show that it does many things.

Explanation

High cohesion means each module has one well-defined responsibility, which makes it easier to test, reuse and change without side effects. Grouping unrelated tasks together, even with comments or a new name, keeps the module hard to understand and maintain.

Question 28Practices and principles

After fixing a bug in a function, a developer reruns the full set of tests that already passed before the change. What is the main purpose of rerunning them?

  1. To confirm the fix has not broken behaviour that already worked. Correct answer.
  2. To replace the need for a code review of the change.
  3. To prove that the fixed function will never fail on any future input.
  4. To measure how many additional features the bug fix has introduced to users.

Explanation

Regression testing reruns existing tests after a change to confirm that previously working behaviour still works. A fix can unintentionally affect other code paths, and no finite test suite can prove that a function will never fail.

Question 29Practices and principles

Two developers edit the same lines of the same file in separate branches. The first change is merged into the main branch. When the second developer tries to merge, the version control system reports a conflict. What must the second developer do?

  1. Revert the first developer's merge so that only one set of changes remains in the file.
  2. Delete the second branch and recreate it from the main branch, discarding its changes.
  3. Edit the conflicting lines to combine the intended changes, then commit the resolved file. Correct answer.
  4. Ask the version control system to select the newer of the two versions automatically.

Explanation

A merge conflict happens when both branches changed the same lines, so the version control system cannot decide which version to keep. The developer must edit the file to combine the intended changes and commit the resolved result; discarding or reverting work loses valid changes.

Question 30Practices and principles

A recursive function has a base case, but its recursive calls never reach that base case for some inputs. What is the most likely result when such an input is used?

  1. The program stops with a stack overflow after many nested calls. Correct answer.
  2. The function returns 0 automatically when the base case is missed.
  3. The compiler reports a syntax error before the program runs.
  4. The function runs more quickly because the base case is never evaluated.

Explanation

If the recursive calls never reach the base case, the function keeps calling itself and each call occupies stack space until the runtime aborts with a stack overflow. A missing or unreachable base case is a logic error, so it is not caught by the compiler and no default value is returned.

Question 31Practices and principles

A programmer writes one `calculateGrade` function and calls it from three separate menus, instead of copying the same fifteen lines into each menu. Which benefit of this practice is most direct?

  1. The shared function always runs faster than copied lines.
  2. The shared function removes the need to test the menus.
  3. Each menu can apply a different grading rule without editing the function.
  4. A grading-rule change is made in one place. Correct answer.

Explanation

Placing the rule in one function centralises the logic, so a later change is made once and every caller receives it. Reuse does not remove the need for testing, does not guarantee faster execution, and does not let callers change the rule without editing the function.

Question 32Practices and principles

A procedure declares a local variable `score` and sets it to 10. The main program has a separate variable also named `score`, currently set to 3. After the procedure is called, what is the value of the main program's `score`?

  1. It cannot be determined, because both variables share one name.
  2. 13, because the two values are added together.
  3. 10, because the procedure assigns the new value.
  4. 3, because the procedure changed only its local variable. Correct answer.

Explanation

A local variable exists only inside the procedure, so assigning 10 to the procedure's `score` does not affect the main program's separate `score`. The two variables have different scope even though their identifiers are spelled the same.

Question 33Practices and principles

A bank's website asks a customer to type a new password twice and checks that both entries match before saving it. Which term best describes this check?

  1. Validation
  2. Verification Correct answer.
  3. Authentication
  4. Encryption

Explanation

Verification checks that data is consistent or accurately entered, here by comparing two entries of the same password. Validation checks whether data is acceptable in format or range, while authentication confirms identity and encryption protects stored data.

Question 34Practices and principles

A student calls a library procedure `shuffle(cards)` to randomise a list. She does not know which randomising algorithm the procedure uses inside. Which term best describes her use of `shuffle`?

  1. Abstraction Correct answer.
  2. Decomposition
  3. Iteration
  4. Validation

Explanation

Abstraction means using a component through its interface while hiding the internal details, which is exactly what happens when the student calls `shuffle` without knowing its algorithm. Decomposition splits a problem into parts, iteration repeats steps, and validation checks input.

Question 35Practices and principles

A program asks the user for a whole number and then calculates 100 divided by that number. A user enters 0. Which change best prevents the program from crashing at that point?

  1. Move the division into a separate procedure and call it once from the main program.
  2. Store the user's number in a global variable before performing the division.
  3. Add a comment above the division explaining that zero is not allowed.
  4. Catch the division error with a try/except block. Correct answer.

Explanation

Division by zero raises a runtime error, and an exception handler can catch it so the program continues with a useful message. Moving or storing the value does not handle the error, and a comment does not affect execution.

Question 36Practices and principles

A tester designs test cases by reading a function's source code and identifying every branch in its `if` statements. Which testing approach is being used?

  1. Acceptance testing
  2. Regression testing
  3. White-box testing Correct answer.
  4. Black-box testing

Explanation

White-box testing uses knowledge of the code's internal structure, such as branches and paths, to choose test cases. Black-box testing ignores the code and uses the specification, acceptance testing checks business requirements, and regression testing reruns existing tests after a change.

Question 37Practices and principles

A developer starts building a new login page while teammates keep fixing bugs on the main branch. Which version-control practice best keeps the unfinished login page out of the main branch?

  1. Commit each small login edit directly to the main branch as it is saved.
  2. Delete the main branch until the login page has been finished and tested.
  3. Create a feature branch and merge it when the page is complete. Correct answer.
  4. Email the changed files to teammates instead of committing them.

Explanation

A feature branch isolates unfinished work, so the main branch stays stable while the login page is developed and tested. Direct commits to main would expose incomplete work, and the other options either disrupt the team or abandon version control.

Question 38Practices and principles

A school collects pupils' names and tutor groups to print library cards. The form also asks for home addresses, medical notes and parent income, which the card printing does not need. Which principle best argues for removing those extra fields?

  1. Code reuse
  2. Data minimisation Correct answer.
  3. Lossless compression
  4. Open-source licensing

Explanation

Data minimisation says personal data should be limited to what is necessary for the stated purpose. Addresses, medical notes and income are not needed to print library cards, so collecting them increases privacy risk without a clear benefit.

Question 39Practices and principles

A student finds an image-processing library on the web released under the MIT licence and wants to publish a school project that includes it. What does the MIT licence require her to do?

  1. Keep the original copyright notice and licence text. Correct answer.
  2. Remove the author's name from the library source files before publishing.
  3. Pay the author a fee for each person who uses the published project.
  4. Release her entire project under the same MIT licence as the library.

Explanation

The MIT licence is permissive: it allows reuse, modification and redistribution provided the original copyright notice and permission notice are kept. It does not charge a fee or force the whole project to use the same licence, unlike a strong copyleft licence.

Question 40Practices and principles

A company trains a model to rank job applicants using ten years of its own hiring decisions. Most past hires came from one university. What is the most likely risk in the model's rankings?

  1. It will be more accurate simply because it uses a larger amount of data.
  2. The model will rank all applicants in a random order.
  3. It may repeat the historical preference for that university. Correct answer.
  4. The model will automatically ignore the university field.

Explanation

A model learns patterns present in its training data, so a historical skew toward one university can be learned and repeated as if it were a qualification. More data does not remove bias, and the model will not automatically ignore a field that correlates with past decisions.

Question 41Practices and principles

A mapping app shows only motorways when a user zooms out to view a whole country, then adds side roads as the user zooms in. Which computational-thinking concept does this zooming behaviour demonstrate?

  1. Algorithm design
  2. Decomposition
  3. Pattern recognition
  4. Abstraction Correct answer.

Explanation

Abstraction means hiding detail that is not needed for the current purpose while keeping the features that matter. Changing the zoom level changes which road detail is relevant, so the app is abstracting the map at each scale.

Question 42Practices and principles

A team building a school timetabling system splits the work into separate parts: reading teacher availability, allocating rooms, and detecting clashes. Each part is written and tested on its own before the parts are joined. Which term describes this approach?

  1. Inheritance
  2. Iteration
  3. Abstraction
  4. Decomposition Correct answer.

Explanation

Decomposition means breaking a large problem into smaller sub-problems that can be solved and tested separately. The timetabling system is divided into availability, room allocation and clash detection, then the parts are combined.

Question 43Practices and principles

A developer has finished a working change to a file and wants to save a labelled snapshot in the local repository before starting the next feature. Which Git action should the developer take?

  1. Push the changes to the remote repository
  2. Stash the uncommitted changes
  3. Commit the changes with a descriptive message Correct answer.
  4. Clone the repository again

Explanation

A commit records the staged changes as a snapshot in the local repository and attaches a message describing them. Pushing later uploads commits to a remote, while stashing only shelves unfinished changes temporarily.

Question 44Practices and principles

A function accepts an integer mark and returns a grade; valid marks are 0 to 100 inclusive. A tester wants to use boundary value analysis. Which set of marks should be tested to check the boundaries?

  1. 1, 2, 99, 100
  2. 0 and 100 only
  3. -1, 0, 100, 101 Correct answer.
  4. 0, 50, 100

Explanation

Boundary value analysis tests values at and just outside the edges of each valid range, because faults often occur there. With a valid range of 0 to 100 inclusive, the tests should include 0 and 100 as valid boundaries and -1 and 101 as invalid neighbours.

Question 45Practices and principles

A tester is given a compiled function that converts a temperature from Celsius to Fahrenheit, with no access to its source code. The specification states F = C × 9/5 + 32. Which testing approach is the tester using when choosing inputs such as −40, 0, 37 and 100 and checking the outputs against the formula?

  1. Black-box testing Correct answer.
  2. Integration testing
  3. White-box testing
  4. Regression testing

Explanation

Black-box testing derives test cases from the specification and observable behaviour, without using knowledge of the source code. The tester knows the conversion formula and chosen inputs but cannot see the internal implementation.

Question 46Practices and principles

Two modules have each passed their own unit tests: one calculates a pupil's average mark and the other formats that average for a report. When they are joined, the report shows 0 for every pupil because the calculator returns a decimal and the formatter expects an integer. Which type of testing would most directly have found this fault?

  1. Unit testing
  2. Integration testing Correct answer.
  3. Acceptance testing
  4. Regression testing

Explanation

Unit tests check modules in isolation, so both modules can pass while their interface still fails. Integration testing combines modules and exercises the data passed between them, which is where the decimal-to-integer mismatch appears.

Question 47Practices and principles

Before merging a branch, a developer asks a colleague to read the changed code and look for unclear logic, missing error checks and possible security problems. Which practice is this?

  1. Debugging
  2. Code review Correct answer.
  3. Profiling
  4. Unit testing

Explanation

A code review is a systematic examination of source code by other developers before it is merged. Reviewers look for unclear logic, missing error handling and security weaknesses that automated tests may not catch.

Question 48Practices and principles

A website stores user passwords exactly as typed in its database. Which change best reduces the harm if the database is later stolen?

  1. Store passwords in a separate text file
  2. Email each user their password once a month
  3. Store a salted hash of each password instead Correct answer.
  4. Ask users to choose longer passwords

Explanation

A salted hash is a one-way transformation, so a stolen database does not reveal the original passwords. The salt makes precomputed lookup tables ineffective, whereas longer passwords or separate files do not remove the plaintext exposure.

Question 49Practices and principles

A sorted list contains 1,000 pupil names. A developer uses a linear search from the start of the list; a colleague uses a binary search. In the worst case, approximately how many comparisons does each method need?

  1. About 500 comparisons for linear search and about 10 for binary search
  2. About 1,000 comparisons for linear search and about 500 for binary search
  3. About 1,000 comparisons for linear search and about 10 for binary search Correct answer.
  4. About 10 comparisons for linear search and about 1,000 for binary search

Explanation

A linear search may examine every one of the 1,000 entries in the worst case. Binary search repeatedly halves the remaining search space, so about log2(1000) ≈ 10 comparisons are needed for 1,000 sorted entries.

Question 50Practices and principles

An algorithm for finding a name in an unsorted list of 1,000 entries checks each entry in turn. A second algorithm first sorts the list and then uses binary search. When is the first algorithm likely to be the better choice?

  1. When the list is very large, because sorting becomes cheaper than a linear search as n grows
  2. When only one search is needed on a list that is not already sorted Correct answer.
  3. When the list is already sorted before searching begins
  4. When the list contains many duplicate names

Explanation

A linear search costs O(n), while sorting first costs O(n log n) and then each binary search costs O(log n). For one search on unsorted data, the sorting overhead is not repaid, so linear search is likely better.