Home

Tutoring

Subjects

Live Classes

Study Coach

Essay Review

On-Demand Courses

Colleges

Games

Opening subject page...

Loading your content

AP Computer Science Principles

AP Computer Science Principles Practice Test: Practice Test 5

Practice Test 5 for AP Computer Science Principles: real questions and explanations from the Varsity Tutors practice-test pool.

0%

0 / 25 answered

Question 1 of 25

Which of the following represents a valid conditional statement structure in the AP Computer Science Principles reference sheet notation?

Question Navigator

All questions

Question 1

Which of the following represents a valid conditional statement structure in the AP Computer Science Principles reference sheet notation?

  1. WHEN(condition) { block of statements } OTHERWISE { block of statements }
  2. IF(condition) { block of statements } ELSE { block of statements } (correct answer)
  3. CHECK(condition) { block of statements } ALTERNATE { block of statements }
  4. CONDITION(expression) { block of statements } FALSE { block of statements }

Explanation: Choice B uses the correct IF-ELSE syntax as specified in the AP Computer Science Principles reference sheet. Choices A, C, and D use non-standard keywords (WHEN/OTHERWISE, CHECK/ALTERNATE, CONDITION/FALSE) that are not part of the official AP CSP notation.

Question 2

A programmer has a string variable data assigned the value "user-id:12345". They want to extract the ID number "12345". Assume SUBSTRING(str, start) returns the portion of str from the 1-based index start to the end of the string. The colon is always the 9th character. Which expression will extract the ID?

  1. SUBSTRING(data, 10) (correct answer)
  2. SUBSTRING(data, 9)
  3. SUBSTRING(data, 1)
  4. SUBSTRING(data, 5)

Explanation: The colon : is the 9th character in the string. The ID number "12345" begins at the 10th character. The expression SUBSTRING(data, 10) correctly extracts the portion of the string from the 10th character to the end, which is the desired ID.

Question 3

A programmer is developing an interactive map application. The program waits for the user to click on a specific region of the map. When a click occurs, the program displays detailed information about that region. This style of programming, where the program's execution flow is determined by user actions, is known as:

  1. Sequential programming
  2. Procedural programming
  3. Event-driven programming (correct answer)
  4. State-based programming

Explanation: In event-driven programming, program statements are executed when triggered by events like a mouse click, rather than through a strict sequential flow of control. A is incorrect because the program is not executing a fixed sequence of steps but reacting to user actions. B is a general paradigm, but 'event-driven' is the more specific and accurate term here. D is plausible, as the program has states, but the triggering mechanism is the key concept being described.

Question 4

Which of the following data types requires lossless compression if it is to be compressed at all?

  1. A high-definition movie file being prepared for a streaming service.
  2. A voice recording of a casual conversation to be emailed to a friend.
  3. A text file containing the source code for a computer program. (correct answer)
  4. A large photograph of a landscape intended for use as a website background.

Explanation: Source code is a form of text where every single character, space, and symbol is critical. Changing or removing even one character can cause the entire program to fail. Therefore, if compressed, it must be done losslessly. The other options are all forms of media where some data loss is often acceptable.

Question 5

A username is stored in the string variable user. A program needs to display a welcome message, for example, "Welcome, user123!". Which of the following DISPLAY statements will produce the correctly formatted message?

  1. DISPLAY("Welcome, " + user + "!") (correct answer)
  2. DISPLAY("Welcome, user!")
  3. DISPLAY("Welcome, " + "user" + "!")
  4. DISPLAY(Welcome, + user + !)

Explanation: This statement correctly concatenates the literal string "Welcome, ", the value stored in the user variable, and the literal string "!" to form the complete message. The other options either use the literal word "user" instead of the variable or contain syntax errors.

Question 6

A designer for a new mobile banking application draws a series of sketches that show each screen a user will see. The sketches are arranged in order to illustrate how a user would navigate from the login screen, to their account summary, to transferring funds. This set of sketches is best described as a:

  1. program specification, as it defines the technical requirements that the final application must meet.
  2. functional prototype, as it is a working model that allows users to perform actual bank transfers.
  3. storyboard, as it visually represents the sequence of user interactions and screen layouts in the application. (correct answer)
  4. user survey, as it is a tool for collecting feedback from potential customers about desired features.

Explanation: A storyboard is a tool used in the design phase that visually outlines the sequence of user interactions and screen layouts. The series of sketches showing the user's navigation path is a classic example of storyboarding.

Question 7

Based on the passage: Distributed genome workflows replicate data across nodes so alignments can resume after failures; parallel workflows focus on coordinated processors within one machine. How does distributed computing enhance fault tolerance?

  1. By preventing failures through faster processors, so recovery mechanisms are unnecessary.
  2. By using a single shared disk, ensuring all nodes depend on one storage device.
  3. By duplicating data and reassigning tasks when a node becomes unavailable. (correct answer)
  4. By merging partial results more frequently, which guarantees nodes cannot crash mid-task.

Explanation: This question tests understanding of parallel and distributed computing concepts, specifically how distributed computing achieves fault tolerance through redundancy and task reassignment. Distributed computing's fault tolerance comes from data replication across independent nodes and the ability to reassign work when nodes fail, unlike parallel computing which typically operates within a single failure domain. In this passage, distributed genome workflows are shown to replicate data across nodes so alignments can resume after failures, contrasting with parallel workflows that focus on coordinated processors within one machine. Choice C is correct because it accurately describes how distributed computing enhances fault tolerance by duplicating data and reassigning tasks when a node becomes unavailable, which are the core mechanisms of fault tolerance in distributed systems. Choice B is incorrect because using a single shared disk would create a single point of failure, eliminating fault tolerance rather than enhancing it - the opposite of distributed computing principles. To help students: Explain redundancy concepts using examples like RAID arrays or backup systems. Demonstrate how task reassignment works when nodes fail in distributed systems. Watch for: students confusing fault tolerance mechanisms with performance optimization or thinking shared resources improve fault tolerance.

Question 8

Based on the provided scenario, identify an error in the banking procedure call sequence when withdrawing funds.​

  1. Calling Withdraw before CheckSufficientFunds can create a negative balance. (correct answer)
  2. Calling PrintStatement after Withdraw prevents the withdrawal from occurring.
  3. Calling Deposit after Withdraw always doubles the account balance.
  4. Calling CheckBalance before Withdraw deletes the transaction history.

Explanation: This question tests AP Computer Science Principles skills: understanding and calling procedures. In programming, procedures are blocks of code designed to perform a specific task; they are called within a program to execute their defined operations. In the provided scenario, procedures Withdraw and CheckSufficientFunds are defined to handle banking withdrawal operations safely. Data flows through these procedures via parameters and return values, and proper sequencing is critical for maintaining data integrity. Choice A is correct because it accurately identifies a critical error: withdrawing funds before checking if sufficient funds exist could result in a negative balance, which violates basic banking constraints and data integrity. Choice B is incorrect because printing a statement after a withdrawal would not prevent the withdrawal - it would simply document the transaction that already occurred. To help students: Emphasize understanding the role of each procedure within the program and practice tracing data flow through parameters and return values. Encourage students to identify validation procedures and ensure they are called before operations that modify data.

Question 9

A student applies iterative binary search on the sorted array (ascending): index 0..9, A=[5, 9, 13, 17, 21, 25, 29, 33, 37, 41]. Target starts as 33 and ends found. Pseudocode uses mid=(low+high)/2. Steps: mid=4 (21)<33 => low=5; mid=7 (33)=target => stop. Refer to the array provided above. What is the position of the target element in the array after applying binary search?

  1. Position 6.
  2. Position 7. (correct answer)
  3. Position 8.
  4. Position 5.

Explanation: This question tests understanding of binary search algorithm application in AP Computer Science Principles. Binary search divides a sorted array in half repeatedly to efficiently locate the target element, using the midpoint to guide each iteration. In this problem, we have a 10-element array (indices 0-9) searching for the value 33, which the algorithm successfully locates at index 7. Choice B is correct because it identifies position 7 where the target 33 is found: first iteration calculates mid=4 where A[4]=21<33, adjusting low=5; second iteration calculates mid=7 where A[7]=33 equals our target. Choice A is incorrect because it suggests position 6, which would contain the value 29, not our target 33. To help students: Use array diagrams with indices clearly labeled and practice converting between array indices and positions. Emphasize that in zero-indexed arrays, position numbers match index numbers.

Question 10

A platform game uses random values to spawn coins, health packs, or enemies in new locations each level. Randomness helps the game feel different because players cannot memorize exact patterns. One playthrough may have many coins nearby, while another has more enemies blocking paths. This uncertainty changes the best strategy from run to run. In the context of the problem, how do random values affect the outcome of this game?

  1. They create different item and enemy placements, changing difficulty and player decisions each run. (correct answer)
  2. They ensure the same enemies spawn in the same spots, making the game fair every time.
  3. They mainly increase the game’s frame rate by reducing the amount of rendering needed.
  4. They turn random numbers into exact probabilities, so outcomes are fully pre-calculated.

Explanation: This question tests understanding of the use of random values in algorithms, specifically in AP Computer Science Principles. Random values are used in algorithms to introduce variability and simulate real-world uncertainty, crucial in applications like simulations and security. In the given scenario, random values are used to spawn game elements in different locations each playthrough, affecting player strategy and game difficulty. Choice A is correct because it accurately reflects how random values create different item and enemy placements that change difficulty and require new player decisions each run, demonstrating an understanding of their necessity for creating replayability. Choice B is incorrect because it suggests randomness ensures the same spawns every time, which contradicts the fundamental purpose of randomness - this is a common error when students misunderstand that randomness creates variability, not consistency. To help students: Emphasize the role of randomness in creating unpredictability and enhancing gameplay experiences. Practice identifying situations where random values are essential, such as in games where memorization would reduce challenge and engagement.

Question 11

What is a primary trade-off associated with building a fault-tolerant system using redundancy?

  1. A decrease in the overall speed of the system because of the complexity of managing duplicate components.
  2. An increase in costs and complexity due to the need for additional hardware, software, and maintenance. (correct answer)
  3. A reduction in system security, as redundant components can provide more points of entry for attackers.
  4. A limit on the system's ability to scale, since redundancy works best for small, contained networks.

Explanation: Implementing redundancy involves duplicating components (like servers, network paths, power supplies), which adds to the initial cost and the ongoing complexity of managing the system. This is a key trade-off against the benefit of increased reliability.

Question 12

A researcher is analyzing a dataset of website user activity, which includes a timestamp for every click. The researcher uses a program to transform the raw timestamps into broader categories like "Morning", "Afternoon", and "Evening". What is the primary benefit of this transformation for generating new knowledge?

  1. It can help reveal patterns in user engagement based on the time of day, which are not immediately obvious from precise timestamps. (correct answer)
  2. It significantly reduces the storage size of the dataset by using shorter text strings instead of long numerical timestamp values.
  3. It filters out all user activity that occurs overnight, which is considered irrelevant to the primary research questions.
  4. It cleans the data by automatically removing any incorrect or invalid timestamp entries that were recorded due to system errors.

Explanation: Transforming data into categories is a way to abstract details and reveal higher-level patterns. By grouping precise timestamps into general time-of-day categories, the researcher can more easily identify trends, such as whether users are more active in the evening.

Question 13

A weather simulation program picks a random temperature from 40–95°F and random precipitation type each day. Randomness represents changing conditions that the program cannot know ahead of time. Some days become hot and sunny, while others become cool with rain or snow. The program repeats this for many days to show different possible weekly forecasts. Based on the scenario above, why is randomness important in the context of this simulation?

  1. Random values make the forecast identical each week, so results are easier to compare.
  2. Random values add realistic variability, so many different weather outcomes can be simulated. (correct answer)
  3. Random values mainly reduce storage needs by keeping fewer days of weather data.
  4. Random values guarantee the simulation always predicts the most likely weather correctly.

Explanation: This question tests understanding of the use of random values in algorithms, specifically in AP Computer Science Principles. Random values are used in algorithms to introduce variability and simulate real-world uncertainty, crucial in applications like simulations and security. In the given scenario, random values are used to simulate unpredictable weather conditions by selecting temperatures and precipitation types, affecting the variety of possible weather outcomes. Choice B is correct because it accurately reflects how random values create realistic variability to simulate many different weather outcomes, demonstrating an understanding of their necessity for modeling uncertainty. Choice A is incorrect because it suggests randomness makes forecasts identical, which is the opposite of what randomness achieves - this is a common error when students confuse randomness with determinism. To help students: Emphasize the role of randomness in creating unpredictability and modeling real-world variability. Practice identifying situations where random values are essential, such as in weather simulations where conditions cannot be known in advance.

Question 14

In a machine learning lab, a student uses the Scikit-learn library (prewritten ML tools) to classify emails as spam or not spam. After from sklearn.neighbors import KNeighborsClassifier, they write model = KNeighborsClassifier(n_neighbors=3) and later model.fit(XTrain, yTrain). Based on the scenario described, which function best trains the classifier on labeled data?

  1. model.fit(XTrain, yTrain) (correct answer)
  2. model.plot(XTrain, yTrain)
  3. model.read_csv("train.csv")
  4. model = KNeighborsClassifier[XTrain, yTrain]

Explanation: This question tests understanding of programming libraries and their application in computational tasks, a key concept in AP Computer Science Principles. Libraries provide pre-written code that programmers can use to perform common tasks efficiently, such as data manipulation, visualization, and complex calculations. In this scenario, the Scikit-learn library is used to classify emails using machine learning, leveraging its KNeighborsClassifier to simplify and optimize the classification process. Choice A is correct because it accurately describes how model.fit(XTrain, yTrain) from Scikit-learn fulfills the task requirements by training the classifier on labeled training data. Choice D is incorrect because it uses incorrect syntax with square brackets instead of parentheses, a common error when students confuse object instantiation with method calls. To help students: Walk through the machine learning workflow step-by-step, emphasizing the distinction between creating a model and training it. Encourage practice with simple classification tasks to reinforce the pattern. Watch for: Confusion between different stages of the ML pipeline, particularly instantiation versus training.

Question 15

What will be the result of executing this code when num = 15?

IF(num MOD 2 = 0) { DISPLAY("Even") } ELSE { IF(num MOD 5 = 0) { DISPLAY("Multiple of 5") } ELSE { DISPLAY("Odd") } }

  1. Even
  2. Multiple of 5 (correct answer)
  3. Odd
  4. Both Even and Multiple of 5

Explanation: When num = 15, first we check if 15 MOD 2 = 0. Since 15 MOD 2 = 1, this is false, so we go to the ELSE block. In the nested IF, we check if 15 MOD 5 = 0. Since 15 MOD 5 = 0, this is true, so "Multiple of 5" is displayed. Choice A is incorrect because 15 is odd. Choice C is incorrect because we don't reach that ELSE. Choice D is incorrect because only one path executes.

Question 16

Researchers develop an artificial intelligence program to diagnose a certain type of skin cancer. The program is trained exclusively using a dataset of medical images from patients of a single ethnic background.

What is the most likely consequence if this program is used on a broader patient population?

  1. The program will be unable to store images from patients of other ethnic backgrounds due to privacy restrictions.
  2. The program will be highly accurate for all patients because it learned the fundamental features of the disease.
  3. The program will run much more slowly when analyzing images of patients from different backgrounds.
  4. The program's diagnostic accuracy will likely be lower for patients from ethnic backgrounds not included in the training data. (correct answer)

Explanation: Correct. The appearance of skin conditions can vary significantly across different skin tones. By training on data from only one group, the program has not learned to recognize these variations. This data bias will likely lead to reduced accuracy and potentially harmful misdiagnoses for underrepresented groups.

  • A is incorrect. Privacy restrictions are a legal and data management issue, not a direct consequence of the biased training method.
  • B is incorrect. The 'fundamental features' of a visual disease are often tied to how they appear on different skin types, so the model's learning is incomplete and biased.
  • C is incorrect. The program's speed of execution is generally not affected by the content of the image in this way; the issue is with the accuracy of its analysis.

Question 17

A user is watching a live video stream, but the connection is slow. The video player decides to lower the video quality to ensure the stream can continue without interruption. This decision is based on the current data transfer rate. What network characteristic is being measured to make this adjustment?

  1. Path
  2. Bandwidth (correct answer)
  3. Protocol
  4. Scalability

Explanation: Bandwidth refers to the maximum rate of data transfer across a network. When streaming video, if the available bandwidth is insufficient for high-quality video, the application may reduce the video's data rate (lower its quality) to match the available bandwidth and prevent buffering. (CSN-1.A.7)

Question 18

What condition would cause the code to follow the 0.00 discount path?

// Inputs: isMember, total, isSeasonSale IF isMember IF total >= 100 IF isSeasonSale discount = 0.20 ELSE discount = 0.10 ELSE discount = 0.05 ELSE IF isSeasonSale AND total >= 150 discount = 0.15 ELSE discount = 0.00

  1. Not a member and (not season sale or total < 150) (correct answer)
  2. Member and total < 100 and season sale
  3. Member and total >= 100 and season sale
  4. Not a member and season sale and total >= 100

Explanation: This question tests understanding of nested conditionals in AP Computer Science Principles, focusing on identifying conditions that lead to specific outcomes. Nested conditionals create multiple execution paths, and understanding which combinations lead to each outcome requires careful logical analysis. In this scenario, the 0.00 discount only occurs in the outermost ELSE block when the customer is not a member AND the nested condition fails. Choice A is correct because discount = 0.00 occurs when isMember is false (entering the outer ELSE) AND either isSeasonSale is false OR total < 150, which can be expressed as 'not a member and (not season sale or total < 150)' using logical operators. Choice D is incorrect because if total >= 100 (not 150), a non-member during a season sale would still get 0.00 discount since the threshold for non-members is 150. To help students: Practice converting code paths to logical expressions, use truth tables to verify complex conditions, and work backwards from outcomes to determine required inputs. Emphasize the importance of understanding both positive conditions (what must be true) and negative conditions (what must be false).

Question 19

Identify the error in the nested conditionals that prevents "Severe Storm" from printing.

// Inputs: isThunderstorm, wind IF isThunderstorm IF wind <= 30 PRINT "Severe Storm" ELSE PRINT "Storm" ELSE PRINT "No Alert"

  1. The wind check should use wind >= 30 (correct answer)
  2. The outer IF should check wind, not isThunderstorm
  3. The ELSE should print "Heat Advisory"
  4. The code needs a loop to repeat checks

Explanation: This question tests understanding of nested conditionals in AP Computer Science Principles, focusing on debugging logical errors in condition statements. Nested conditionals require careful attention to comparison operators and logical flow to ensure desired outcomes are achievable. The code attempts to categorize storm severity based on wind speed, but contains a logical error preventing the intended output. Choice A is correct because the condition "wind <= 30" means "Severe Storm" only prints when wind is 30 or LESS during a thunderstorm, which is backwards - severe storms should have HIGH winds, so it should be "wind >= 30". Choice B is incorrect because checking wind first would change the entire logic structure and wouldn't specifically fix the severe storm categorization issue. To help students: Teach them to verify that conditions match real-world logic, use test cases with boundary values, and check that all desired outputs are actually reachable. Emphasize the importance of using the correct comparison operators (<, >, <=, >=) to match the intended logic.

Question 20

Which of the following describes a situation where citizen science would be a particularly effective approach?

  1. A study requiring precise measurements inside a secure, controlled laboratory environment.
  2. A project that needs to collect geographically widespread environmental data, like rainfall levels. (correct answer)
  3. An analysis of classified government documents that requires a high-level security clearance.
  4. A task that involves writing a complex piece of software to simulate particle physics.

Explanation: Citizen science excels when research requires data collection over a large geographic area, which would be prohibitively expensive or time-consuming for a small team of professional scientists. Distributed volunteers can collect this data efficiently.

Question 21

A weather program calculates the average temperature for a month. Input: tempsList of daily readings, where some entries may be missing (null). Output: average of available readings. Constraints: list length is 28–31, and missing values should not count. Based on the described problem, which part of the algorithm handles input constraints?

  1. Include null entries as 000 so every day contributes equally.
  2. Skip null entries and divide by the count of non-null readings. (correct answer)
  3. Sort the temperatures and return the middle value as the average.
  4. Return the maximum temperature to avoid underestimating the month.

Explanation: This question tests algorithm development skills, specifically understanding and selecting appropriate algorithms for given problems in AP Computer Science Principles. Algorithm development involves designing step-by-step procedures to solve problems efficiently and correctly, considering constraints and input specifications. In this problem, the scenario involves calculating an average temperature while handling missing (null) data entries, which requires understanding of data validation and mathematical operations. Choice B is correct because skipping null entries and dividing by the count of non-null readings ensures an accurate average that only considers valid data points, properly handling the constraint. Choice A is incorrect because treating null as 0 would artificially lower the average temperature, a common error when students don't properly handle missing data. To help students: Encourage careful consideration of edge cases and invalid data handling. Practice implementing algorithms that validate input before processing. Watch for: misconceptions about handling missing data and the impact on mathematical calculations.

Question 22

A marketing company legally obtains data about a user's geolocation from a mapping app, their purchase history from an e-commerce site, and their stated interests from a social media profile. What is the primary privacy risk of combining these disparate data sets?

  1. The data sets could be stored inefficiently, taking up a large amount of digital space.
  2. The aggregation of this information can create a detailed personal profile, revealing sensitive patterns about the user's life. (correct answer)
  3. The user will receive less relevant advertisements, as the combined data will be too confusing for algorithms to process.
  4. The user's device will perform more slowly due to the increased amount of data being tracked.

Explanation: The aggregation of seemingly unrelated data can create a comprehensive profile of an individual's habits, preferences, and daily routines. This knowledge can be exploited in ways the user never intended, posing a significant privacy risk.

Question 23

A program simulates daily weather for a class project using random values for temperature and precipitation. Temperatures range from 40°F to 95°F, and precipitation can be none, rain, or snow. Randomness models real-world uncertainty, since weather changes without a fixed pattern. Some weeks become mostly sunny, while others include several rainy days. Based on the scenario above, how do random values affect the outcome of this weather simulation?

  1. They make each simulated day vary, so temperature and precipitation change across runs and across weeks. (correct answer)
  2. They ensure identical weather every time, so the simulation always matches last week’s results.
  3. They speed up the program by skipping calculations for temperature and precipitation entirely.
  4. They are only used to make the output look nicer, without changing any predicted conditions.

Explanation: This question tests understanding of the use of random values in algorithms, specifically in AP Computer Science Principles. Random values are used in algorithms to introduce variability and simulate real-world uncertainty, crucial in applications like simulations and security. In the given scenario, random values are used to generate daily weather conditions including temperature and precipitation, affecting the simulation's ability to model realistic weather patterns. Choice A is correct because it accurately reflects how random values create variation across simulation runs and time periods, demonstrating an understanding of their necessity for modeling unpredictable natural phenomena. Choice B is incorrect because it suggests randomness produces identical results, which is a common error when students misunderstand the fundamental nature of random number generation. To help students: Emphasize the role of randomness in creating realistic simulations of natural systems. Practice identifying situations where random values are essential, such as in weather modeling where outcomes cannot be predetermined.

Question 24

Based on the code snippet for student grading: IF score > 90 grade="A" ELSE IF score >= 80 grade="B" ELSE grade="C". What is the output when score is 90?

  1. grade becomes "A" because 90≥9090 \ge 9090≥90.
  2. grade becomes "B" because 909090 is not >90>90>90. (correct answer)
  3. grade becomes "C" because 90 is a boundary case.
  4. No grade is assigned because conditions conflict.

Explanation: This question tests understanding of conditionals in AP Computer Science Principles, specifically the critical difference between > (greater than) and >= (greater than or equal to) operators. Conditionals evaluate conditions precisely as written, and boundary values often reveal student understanding of comparison operators. Choice B is correct because when score is 90, the first condition (score > 90) is false since 90 is not greater than 90, but the second condition (score >= 80) is true, so grade becomes "B". Choice A is incorrect because it confuses > with >=, a common error when students don't pay attention to boundary conditions. To help students: Use number lines to visualize the difference between > and >= operators. Create exercises specifically testing boundary values and emphasize reading operators carefully.

Question 25

What will be the output of the following code segment when age is 16?

IF(age >= 18) { DISPLAY("Adult") } ELSE { DISPLAY("Minor") }

  1. Adult
  2. Minor (correct answer)
  3. Both Adult and Minor will be displayed
  4. No output will be produced

Explanation: When age is 16, the condition (age >= 18) evaluates to false since 16 is not greater than or equal to 18. Therefore, the ELSE block executes, displaying "Minor". Choice A is incorrect because the condition is false. Choice C is incorrect because only one block executes in an IF-ELSE statement. Choice D is incorrect because the ELSE block will execute.