AP® Computer Science Principles Notes - Scholarly Wings
AP® Computer Science Principles Notes - Scholarly Wings
Science Principles
Notes
Jesus Barrios
Author
AP® is a registered trademark of of the College Board, which is not affiliated with Dove’s Library and was not
involved in the production of, and does not endorse, this product.
Table of Contents
Create Task: Tips and Resources
1. User Input and Output: The app must allow for user interaction through
input and output mechanisms.
2. Data Storage: Implement a list or array to store multiple data items.
3. Function with Parameters: Develop at least one function that takes
parameters and performs operations such as iteration and conditional
checks.
Suggested Project Idea: For those looking to complete the task with a
straightforward project, consider building a simple calculator. This application
meets the criteria by involving user input, output, and basic data handling.
● User Interface: Ensure your application has clear input and output fields.
● Data Handling: Use a list or array to manage data within the app.
● Functional Operation: Include a function that accepts parameters. Within
this function, use a loop (e.g., a 'for' loop) to iterate through the list and
conditional statements (if/else) to handle different scenarios based on the
data.
Additional Tips:
Resources: For further examples and inspiration, review the sample CSP Create
Tasks available on the College Board website. These examples can provide a
clearer picture of what is expected and how to structure your project to meet the
AP criteria.
4
Create Task: Tips and Resources
Example of My Create Task Submission: Jumping Game
In the 2023-2024 school year, I developed a game where the gameplay involved
a dog that jumps when the player presses an arrow key, the space bar, or a
mouse button. This game was coded in JavaScript, showcasing effective use of
programming skills aligned with AP Computer Science Principles
requirements.
● User Input: The game responds to keyboard and mouse inputs, allowing
the dog to jump.
● Output: The game visually represents the character's jumps and displays
scores.
● Data Management: An array stores the scores, and a specific procedure
determines and displays the highest score achieved.
5
Create Task: Tips and Resources
Submitting Your Code to CollegeBoard
For an effective and organized submission of your code to the College Board,
consider using the following website:
6
Create Task: Tips and Resources
● Assistance from AI or Peers:
○ If your project involved assistance from AI tools or peers, it's
important to acknowledge this collaboration clearly within your code
comments.
These practices not only ensure transparency but also help in upholding the
principles of fair use and academic honesty in your submissions. Always check
the latest AP guidelines and your school's policy on collaborative work to make
sure you're in compliance.
7
Create Task: Tips and Resources
Acceptable Programming Languages and Products: For the AP Computer
Science Principles course, students can choose from a wide range of
programming languages and development environments. Here is a list of
acceptable options, as mentioned on page 130 of the course materials:
8
Big Idea 1:
Creative
Development
Computing innovations are constantly evolving, driven by human creativity and the
ever-present desire to improve technology. These innovations can originate from virtually
anywhere, reflecting the diverse needs and challenges of society.
Computing technology not only enhances functionality but also aids in modeling real-world
scenarios and predicting outcomes by analyzing different variables. This integration of
computing has contributed to increased creativity across multiple domains, including
medicine, engineering, communications, and the arts.
While both elements are crucial, the essence of most computing innovations lies in the
software, driving functionality and user interaction.
Moore's Law observes that the number of transistors on a microchip doubles approximately
every two years, while the cost of computers is halved. This principle has seen computers
evolve from large machines occupying up to 1000 square feet and weighing nearly 50 tons
to devices that fit comfortably in one's pocket. 10
Big Idea 1: Creative Development
Understanding Collaboration
1. Skill Enhancement:
○ Group programming allows individuals to pair their strengths with others'
weaknesses, leading to a more robust and comprehensive product.
2. Increased Efficiency:
○ Multiple perspectives can streamline problem-solving processes and
introduce innovative solutions faster.
3. Learning and Development:
○ Collaboration is not just about completing tasks but also about personal
growth and development in communication, negotiation, and conflict
resolution.
4. Resource Sharing:
○ Combining different resources and talents from individuals enhances the
quality and scope of projects.
5. Remote Collaboration:
○ Modern tools like Google Docs, Zoom, and Slack enable programmers to
collaborate effectively regardless of geographical barriers, ensuring that
physical location is no longer a limitation.
11
Big Idea 1: Creative Development
Collaboration's Impact on Product Development:
The collective experience and expertise of a group often surpass what an individual
can achieve alone. This shared knowledge base leads to more creative solutions and
innovations, proving that the whole can indeed be greater than the sum of its parts.
This example illustrates how a simple input can be processed to yield a specific
output, demonstrating the fundamental operation of a software program.
//Input: A number
number ← 5
DISPLAY(square)
12
Big Idea 1: Creative Development
The Importance of Collaboration in Debugging
Program Abstraction
Consider a smart home system that adjusts the lighting based on the
natural light input received through sensors:
13
Big Idea 1: Creative Development
Here’s a simple diagram illustrating the input and output process in a
typical application:
14
Big Idea 1: Creative Development
Understanding the Development Process in Computing
Example of Iteration: After testing, you may discover that additional features
are necessary or certain functionalities are not user-friendly, prompting a
return to the "Investigating and Reflecting" phase to reconsider these aspects.
This cycle might repeat multiple times, refining the application until it meets
the desired standards or until development time expires.
● Process: This approach involves breaking down the software project into
smaller, manageable components or increments. Each part is developed,
tested, and finalized before moving on to the next, ensuring that each
component functions correctly as part of the whole.
15
Big Idea 1: Creative Development
Understanding the Design Process
● User Interviews: Engaging with potential users to gather insights about their needs
and preferences.
● Market Research: Analyzing similar applications to understand common features and
user expectations.
● Feedback Loops: Implementing initial designs with a small group of users to collect
feedback and make necessary adjustments.
Benefits of Documentation:
● Memory Aid: Helps programmers recall their thought processes or decisions made
during development.
● Collaboration Support: Essential in team settings, allowing all members to
understand each part of the program.
● Maintenance and Updating: Facilitates future changes and debugging by providing a
clear understanding of the program’s functionality.
Forms of Documentation:
● Comments: Non-executable text within the code that explains functions, variables,
and algorithms. Comments are crucial for maintaining readability and do not impact
the runtime or speed of the program.
● External Documents: These might include requirement specifications, design
diagrams, and user manuals, providing broader context and guidelines for using and
modifying the program.
//This is a comment
16
Big Idea 1: Creative Development
Understanding the types of errors that can occur during programming is crucial for
developing efficient and reliable software. Additionally, how these errors are
documented varies based on the programming language and project requirements.
Below, we explore the three common types of programming errors along with
examples, and discuss documentation practices.
1. Logic Error:
● Description: A logic error occurs when there is a flaw in the algorithm that
causes the program to operate incorrectly or produce unintended results.
2. Syntax Error:
● Description: A syntax error occurs when the code violates the grammatical
rules of the programming language, leading to a failure in compiling or
interpreting the code.
3. Runtime Error:
17
Big Idea 2:
Data
Complex Data Representation: Larger and more complex data types require
multiple bits. For example, a simple color in an image might need 24 bits - 8
bits for each of the red, green, and blue components.
Abstractions in Computing
19
Big Idea 2: Data
High-Level Programming Languages
let sum = 3 + 5
Analog Data: Analog signals are continuous; they change smoothly over time.
Common examples of analog data include:
Digital Data: Digital signals break information into discrete steps. By sampling
analog signals at regular intervals (samples), digital signals can closely
approximate their analog counterparts. The more frequent the sampling rate,
the more accurately the digital signal represents the analog signal.
20
Big Idea 2: Data
Understanding Variables and Data Types
21
Big Idea 2: Data
Understanding Integer Representation and Number Systems in
Programming
Integer Overflow: Trying to store a number beyond this range can lead to
an overflow error, where numbers wrap around to negative values due to
exceeding the maximum limit:
22
Big Idea 2: Data
Example of a Binary to Decimal Conversion:
Step-by-Step Conversion:
Assign decimal values to each position (from right to left, starting with
2^0):
1 1 110
16 8 4 2 1
Tutorial Explanation:
23
Big Idea 2: Data
Converting from Decimal to Binary
Understanding how to convert decimal numbers to binary is a key skill for the
AP Computer Science Principles exam. Below, I'll repeat the strategy used for
binary to decimal conversion, but in reverse, showing how to convert decimal
numbers into binary.
Let's convert the decimal numbers 30, 15, 7, 5, 3, and 1 into binary:
1. Decimal Number: 30
○ Binary Representation: 11110
2. Decimal Number: 15
○ Binary Representation: 1111
3. Decimal Number: 7
○ Binary Representation: 111
4. Decimal Number: 5
○ Binary Representation: 101
5. Decimal Number: 3
○ Binary Representation: 11
6. Decimal Number: 1
○ Binary Representation: 1
Explanation:
● For each number, start from the largest power of two within the number.
For 30, I’d start from 2^4 because 2^5 is over 32 which is over, meaning it
won’t work.
● Write out the powers of two from the largest to the smallest. So from here,
we write out 16 8 4 2 1.
● Place a '1' over the powers of two that sum to the decimal number and '0'
where not needed.
● The sequence of '1's and '0's forms the binary representation.
24
Big Idea 2: Data
Adding Decimal and Binary Numbers
Overflow Errors
25
Big Idea 2: Data
Roundoff Errors
Explanation of Roundoff Errors: Roundoff errors occur when real numbers are
approximated because their exact decimal representation requires more digits
than the computer can handle. For example, the fraction ⅓ might be
represented differently depending on the precision level of the computer:
This variation means that ⅓ on one system does not exactly equal ⅓ on
another, leading to discrepancies in calculations and results.
Lossy Compression:
Lossless Compression:
26
Big Idea 2: Data
Choosing the Right Compression:
● Quality vs. Size: Choose lossy compression when file size reduction is
more important than quality. Opt for lossless compression when
quality or fidelity to the original is critical.
● Use Case Consideration: For everyday use like emails or casual
photography, lossy compression is sufficient. For archival purposes or
where data integrity is paramount, use lossless compression.
27
Big Idea 2: Data
Combining Disciplines for Insight: Gaining meaningful insights from
data involves a blend of skills:
28
Big Idea 2: Data
Challenges with Large Data Sets:
29
Big Idea 2: Data
Leveraging Data for Strategic Decisions
30
Big Idea 2: Data
Importance of Data Visualization
● Column Charts and Bar Charts: Useful for comparing quantities across
categories.
● Line Graphs and XY Charts: Ideal for displaying data trends over time or
relationships between variables.
● Pie Charts: Effective for showing proportional distributions.
● Radar Charts: Helpful in comparing multiple variables.
● Histograms: Used for depicting the distribution of numerical data.
● Waterfall Charts: Good for visualizing sequential changes in data.
Privacy Concerns: With the mass collection of data, privacy becomes a significant
concern. The content of collected data can contain sensitive personal information which
necessitates careful handling, especially in terms of storage and transmission.
● Using an email service like Gmail to order shoes may result in targeted
advertisements for similar products appearing in your search results or social
media feeds.
Understanding Metadata:
31
Big Idea 3:
Programming and
Algorithms
1. DISPLAY(expression):
○ This procedural abstraction displays the value of an expression.
2. RANDOM(a, b):
○ This function generates a random number between a and b, inclusive 33
Big Idea 3: Programming and Algorithms
Procedural Abstraction Examples on the AP Exam
1. DISPLAY(expression)
2. RANDOM(a, b)
● Explanation: This function generates a random number between the integers a and b
(inclusive). It abstracts the complexity of random number generation, providing a
simple interface for getting random values.
Relational Operators
Relational operators, often called relational operators, are used to compare two values or
expressions. The result of such a comparison is a Boolean value, true or false.
34
Big Idea 3: Programming and Algorithms
Chart of Common Relational Operators and Their Uses:
+ Addition 3 + 2 //5
- Subtraction 3 - 2 //1
* Multiplication 3 * 2 //6
/ Division 3 / 2 //1.5
= Equal 4 = 5 //false
35
Big Idea 3: Programming and Algorithms
Modulus Operator Example
Special Cases:
● Example: a ← 3 MOD 4
○ Explanation: If the divisor is larger than the dividend (3 divided by 4),
the remainder is the dividend itself, so a would be 3.
● Dividing by Zero: a ← 6 MOD 0
○ Result: This operation will result in an error as division by zero is
undefined in mathematics and programming. If this was the other
way around, it would be 0.
● Parentheses
● Exponents
● Multiplication and Division (from left to right)
● Addition and Subtraction (from left to right)
● Modulus is treated like division and multiplication in terms of precedence.
36
Big Idea 3: Programming and Algorithms
Variable Assignment and Reassignment Example
Explanation: This example shows how variables can be set and then
changed within a program. Understanding that the latest assignment is
what defines the variable’s value is crucial.
37
Big Idea 3: Programming and Algorithms
Understanding Percentage Chance in Programming with Examples
Explanation:
This calculation reflects basic probability principles where the likelihood of an event
occurring is the ratio of favorable outcomes to the total number of possible outcomes.
Explanation:
In this case, because there are three numbers (1, 2, and 3) that satisfy the condition a <= 3 out
of ten possible numbers, the probability is 30%. This example teaches how to account for
multiple favorable outcomes when calculating the likelihood of an event.
38
Big Idea 3: Programming and Algorithms
Concept of Data Abstraction
Lists enhance readability and manageability of code by reducing the need for
multiple individual variables and allowing complex data manipulations
through built-in methods and functions.
Using a list simplifies these operations by providing a flexible and efficient way
to store, access, and manipulate data. Lists enable easier implementation of
functions and operations over the data set, significantly reducing the
complexity and enhancing the maintainability of the program.
39
Big Idea 3: Programming and Algorithms
Basic Concepts of Lists
Indexing in Lists:
In this example, scores[1] accesses the first element of the list, which is 11,
adhering to the AP exam's indexing rule.
When you try to access an index that is less than 1 or greater than the
length of the list, it results in an "index out of bounds" error. On the AP
exam, attempting to access a non-existent index will terminate the
program, unlike some programming languages that might return
undefined or throw an exception without terminating the program.
40
Big Idea 3: Programming and Algorithms
Inserting Elements into a List
The INSERT(list, i, item) function is used to insert an item into the list at a
specified index i. This function modifies the list by placing the new item at
the index i and shifting elements at index i and higher to the right.
● Before Insertion: The list words contains ["Hey", "How", "Are", "You"]
● After Insertion: The item "Green" is inserted at the third position:
○ New list after insertion: ["Hey", "How", "Green", "Are", "You"]
The element "Green" is added to the list at index 3, while "Are" (previously
at index 3) and "You" (previously at index 4) are shifted right to indices 4
and 5, respectively.
41
Big Idea 3: Programming and Algorithms
List Operations in Programming: Append, Insert, and Remove
Given an initial setup and a series of operations, let's walk through how
these modify a list. The operations we will explore are APPEND, INSERT,
and REMOVE.
Using REMOVE
42
Big Idea 3: Programming and Algorithms
Explanation of What Happened:
Removal Operations:
43
Big Idea 3: Programming and Algorithms
Understanding Conditionals in Programming
Structure of Conditionals
IF condition
{
LOG("Condition met")
} ELSE
{
LOG("Condition not met")
}
44
Big Idea 3: Programming and Algorithms
Examples of Conditional Statements
45
Big Idea 3: Programming and Algorithms
Example 3: Using the Logical AND Operator
The logical AND operator (&&) is used in conditions to check if all of the
given conditions are true. It returns true only if all conditions evaluate to
true.
Note: You might see && instead of “and” on the AP Exam especially if its in
text.
46
Big Idea 3: Programming and Algorithms
Loops are fundamental constructs in programming that allow repetitive tasks
to be executed efficiently. Let's explore two common types of loops: the
"Repeat n Times" loop and the "Repeat Until Condition" loop.
This loop type executes a block of statements a specified number of times. This
is a straightforward way to perform a task multiple times without manually
writing the code repeatedly.
Explanation:
This loop continues to execute as long as a condition is false and stops once
the condition becomes true. This is somewhat opposite to a typical while loop
seen in languages like Python, which continues as long as the condition is true.
Explanation:
● Operation: The loop starts with counter set to 1 and repeats the block of
statements until counter exceeds 5.
● Behavior: Inside the loop, it displays the current value of counter and then
increments counter by 1. The loop stops when counter becomes 6, having
printed values from 1 to 5.
47
Big Idea 3: Programming and Algorithms
Key Points to Remember:
48
Big Idea 3: Programming and Algorithms
Loop 3: Looping Through a List
Looping through a list or an array allows you to perform operations on each element in the
collection sequentially. This type of loop, often referred to as a "FOR EACH" loop, is incredibly
useful for handling collections of items without manually indexing each element.
In a FOR EACH loop, a temporary variable is assigned to each element in the list, one at a
time, from the first to the last. The block of statements within the loop then operates on
each of these elements.
This structure simplifies operations on arrays or lists by abstracting the process of iterating
over each element, thereby avoiding manual loop controls and index management.
How It Works:
● Iteration: Each element in the array text is passed in turn to the function defined
inside the forEach. The function then executes, logging each item.
● Flexibility: This method is useful for any operation that needs to be applied to each
element of an array, such as transforming data, filtering, or aggregating information.
49
Big Idea 3: Programming and Algorithms
Practical Use and Efficiency
Using a FOR EACH loop is especially advantageous when you need to ensure
that every element of a list or array is accessed and processed, as it
automatically handles the traversal of the collection. This eliminates potential
errors from manual index handling and makes the code cleaner and easier to
read.
FOR EACH loops are particularly well-suited for collections where the operation
does not need to modify the list's structure (i.e., not adding or removing
elements during iteration), as it purely focuses on accessing each element.
In this version of looping through a list, you use a counter to control the
number of iterations based on the length of the list. This approach is a
traditional method used in many programming languages, especially when
specific indexing is necessary or when manipulating the index directly is part of
the logic.
The provided pseudo code demonstrates how to calculate the sum of all
numbers in a list by iterating through each element using a counter-controlled
loop:
50
Big Idea 3: Programming and Algorithms
Step-by-Step Breakdown:
1. Initialization:
○ sum is initialized to 0. This variable will accumulate the total of
all numbers in the list.
○ n is set to the length of the list, determining how many times
the loop will execute.
○ index starts at 1, assuming list indexing begins at 1 (as per AP
Computer Science Principles guidelines).
2. Loop Execution:
○ The loop is set to REPEAT n TIMES, equal to the number of
elements in the list.
○ Inside the loop:
■ The current item in the list list[index] is added to sum.
■ index is then incremented by 1 to move to the next item in
the list on the subsequent iteration.
3. Display the Result:
○ After the loop completes (having iterated through each element
of the list), the total sum is displayed using DISPLAY(sum).
51
Big Idea 3: Programming and Algorithms
Explanation of What’s Happening:
● Use Pencil and Paper: As you suggested, using pencil and paper to
track the values through each iteration can be incredibly helpful.
Write down the current value of sum and index at each step to
visualize the process and ensure accuracy.
52
Big Idea 3: Programming and Algorithms
What is a Procedure?
Procedures are used to avoid repetition of the same code lines across a
program. By encapsulating a sequence of instructions into a single,
reusable procedure, you can:
53
Big Idea 3: Programming and Algorithms
Example of Procedure
Let's create two procedures as examples: one that doubles each value in a
list, and another that adds all the numbers in a list.
Explanation:
54
Big Idea 3: Programming and Algorithms
⭐ Common Algorithms on AP Exam ⭐ (Page 57 - 67)
The purpose of this algorithm is to compute the total sum of all elements
in a list. This operation is frequently used in data analysis, financial
calculations, and anywhere you need to aggregate numerical data.
1. Initialization:
○ sum ← 0: We start by initializing sum to 0. This variable will hold
the cumulative total of the numbers as we iterate through the
list.
2. Loop Through Each Element:
○ FOR EACH item IN scores: This loop iterates over each element
in the list scores. The variable item takes on the value of each
element in the list one by one.
3. Accumulate the Sum:
○ sum ← sum + item: Inside the loop, we add the current element
(item) to the running total (sum). Each iteration updates sum to
include the value of the current item.
4. Return the Total:
○ RETURN sum: After the loop has processed all elements in the
list, the procedure returns the total sum accumulated. 55
Big Idea 3: Programming and Algorithms
Understanding What’s Happening
56
Big Idea 3: Programming and Algorithms
Understanding the Algorithm: Finding the Average of a List
Step-by-Step Explanation:
1. Initialization of sum:
○ sum ← 0: Start with a sum of zero to which the values from the list will be
added.
2. Iterating Through the List:
○ FOR EACH item IN list: This loop goes through each item in the list one by
one.
○ sum ← sum + item: In each iteration, the current item's value is added to
sum.
3. Calculating the Average:
○ RETURN(sum / LENGTH(list)): After all items are added to sum, the
average is calculated by dividing sum by the number of items in the list
LENGTH(list). The RETURN statement outputs the result of this division,
which is the average.
57
Big Idea 3: Programming and Algorithms
Implementation 2: Using REPEAT n TIMES Loop
Step-by-Step Explanation:
1. Initialization:
○ sum ← 0: Initializes the sum to zero.
○ n ← LENGTH(list): Stores the number of items in the list in n.
○ index ← 1: Starts the index at 1, considering the AP exam's 1-based
indexing.
2. Looping Through the List:
○ REPEAT n TIMES: The loop is set to iterate n times, which is the
length of the list.
○ Inside the loop:
■ sum ← sum + list[index]: Adds the value at the current index of
the list to sum.
■ index ← index + 1: Increments the index to move to the next
item in the list.
3. Returning the Average:
○ RETURN sum/n: After all iterations, the loop has summed all
elements in the list. Dividing this sum by n (the total number of
items) gives the average. This value is then returned.
58
Big Idea 3: Programming and Algorithms
Understanding Both Implementations
59
Big Idea 3: Programming and Algorithms
Understanding the Algorithm: Finding the Maximum of a List
Finding the maximum value in a list is a common task that involves comparing each
element of the list to determine the largest one. Here, we'll break down two
implementations of a procedure to find the maximum value in a list.
Step-by-Step Explanation:
1. Initialize Maximum:
○ max ← list[1]: Start by assuming that the first item in the list is the maximum.
This sets a baseline for comparison.
2. Iterate Through the List:
○ FOR EACH item IN list: Loop through each element in the list.
○ IF(item > max): Check if the current item is greater than the current maximum
(max).
○ max <- item: If the current item is greater, update max to this new value.
3. Return the Maximum:
○ RETURN(max): After finishing the loop, return the value of max, which now
holds the maximum value found in the list.
● The use of a FOR EACH loop simplifies the process of iterating over each element and
focuses on the logic of comparing and updating the maximum value.
● This implementation is straightforward and very readable, making it easy to
understand the logic of finding the maximum value. 60
Big Idea 3: Programming and Algorithms
Finding the Maximum of a List (Implementation #2)
Step-by-Step Explanation:
1. Initialize Variables:
○ max ← list[1]: Initialize max as the first element in the list.
○ n ← LENGTH(list): Determine the number of elements in the list and store it in n.
○ count ← 1: Start a counter at 1 to use for indexing through the list.
2. Loop Through the List Using a Counter:
○ REPEAT n TIMES: Use a repeat loop to go through the list n times, once for each
element.
○ IF(list[count] > max): Inside the loop, check if the current element list[count] is greater
than the current maximum.
○ max ← list[count]: If true, update max to this new larger value.
○ count ← count + 1: Increment count to move to the next element in the list.
3. Return the Maximum Value:
○ RETURN(max): After completing the loop, max will hold the highest value found, which
is then returned.
● This method explicitly manages the indexing of elements, making it clear how each element is
accessed.
● The REPEAT n TIMES structure allows precise control over how many iterations occur,
matching the exact length of the list.
● Manually handling the index with count gives flexibility if modifications to the looping
mechanism are needed, such as skipping elements or other conditions based on the index. 61
Big Idea 3: Programming and Algorithms
Analysis of a Common Error in Finding the Maximum Value
The provided pseudo code contains a typical error that can easily lead to incorrect results,
especially when working with specific types of data such as all-negative lists. Let's break
down the error and understand why it happens.
The error in this code lies in the initialization of the max variable to 0. This approach assumes
that the maximum value in any list will be at least 0, which is not always the case, particularly
with lists containing all negative numbers.
Step-by-Step Breakdown with the Given List [-1, -1, -35, -6]:
1. Initialization:
○ max is initialized to 0. This is intended to provide a starting point for comparison.
2. Loop Through Each Item in the List:
○ The loop iterates over each element in the list: -1, -1, -35, -6.
○ The conditional IF(item > max) checks if the current item is greater than max.
3. Condition Evaluation:
○ For each item in the list [-1, -1, -35, -6], the condition item > max is evaluated
against max = 0.
○ None of these items is greater than 0, so the condition never evaluates to true.
○ Consequently, max remains unchanged at 0.
4. Return Value:
○ The function returns max, which remains 0, not reflecting any of the actual
values in the list.
62
Big Idea 3: Programming and Algorithms
The Logical Error (previous example continued):
The logical error is setting max to 0 at the start. For lists that contain only negative numbers, no
element will ever be greater than 0, so max remains incorrectly set to 0. The algorithm fails to
accurately assess the maximum in cases where all elements are below the initialized value of max.
The pseudocode provided for the procedure to find the minimum value in a list contains a significant
logical error that results in an incorrect outcome. Let's dissect the error and explain why it occurs.
The fundamental error in this code is in the ELSE branch of the conditional statement, which sets
min to 0 whenever the current item is not less than the current minimum. This logic is flawed and
will generally result in the minimum being incorrectly set to 0 unless the list exclusively contains
negative numbers.
1. Initialization:
○ min is initialized to the first element of the list, which is 1. This is a good start as it
represents a real value from the list.
2. Loop Through Each Item:
○ The loop iterates over each element in the list.
3. Condition Evaluation and Update:
○ First Iteration (item ← 1): Since 1 is not less than min (which is 1), the ELSE block
executes, setting min to 0.
○ Subsequent Iterations (items ← 1, 35, 6): For each of these items, since none of them
are less than 0 (the newly set value of min), min remains 0.
4. Return Value:
○ The function returns min, which is now 0, clearly not the minimum value of the original
list.
63
Big Idea 3: Programming and Algorithms
Explanation of What's Happening:
Corrected Approach:
The correct implementation should only update min when a smaller item
is found and do nothing otherwise. The corrected pseudocode would look
like this:
● Eliminating the ELSE Clause: By removing the ELSE block, min only
updates when a truly smaller value is found. If no smaller value is
found, min remains correctly at the smallest value encountered.
64
Big Idea 3: Programming and Algorithms
Analyzing the Procedure to Find a Word in a List of Words
The provided pseudocode describes a procedure for finding the index of a specific word within a list.
This is a fundamental search operation in computer science, often used to determine whether and
where a particular element exists within a collection.
Step-by-Step Breakdown:
1. Initialization:
○ index ← 1: Initializes the index to 1, assuming a list indexing starts at 1, which is typical for
the AP exam format.
2. Iterate Through the List:
○ FOR EACH item IN list: Iterates through each item in the list sequentially.
3. Check Each Item:
○ IF(item = word): Checks if the current item matches the word we are searching for.
■ If true, RETURN index: Immediately returns the current index, indicating where
the word was found in the list.
○ ELSE:
■ index ← index + 1: Increments the index by one. This step is necessary to move to
the next item's index in the list.
4. Word Not Found:
○ After the loop completes and if the word has not been found, RETURN “word not in the
list”: This statement is executed if the word is not found in any iteration of the loop.
65
Big Idea 3: Programming and Algorithms
Understanding How to Swap Items in Arrays
To simplify the concept of swapping items in an array, think of it like trading seats in a
classroom:
Analogy:
Think of it as swapping lunch boxes between two friends. You don't want to mix up
the contents, so you use an extra lunch box (the temporary variable) to hold the
contents of one friend's lunch box while you swap them.
66
Big Idea 3: Programming and Algorithms
Understanding Robot Movement and Rotation Commands
To help students grasp the concept of robot movement and orientation, we can illustrate
these actions using simple tables. These commands are commonly used in programming
exercises, particularly in contexts like robotics and simulations, where directional control and
movement are key aspects.
The MOVE_FORWARD() command moves the robot forward in the direction it is currently
facing. To prevent the robot from moving into an obstacle or off the map, we use conditional
checks.
67
Big Idea 3: Programming and Algorithms
Explanation:
Reaching a Goal
Explanation:
(Next page)
69
Big Idea 3: Programming and Algorithms
Step-by-Step Approach to Determine Possible Landing Spots
● First REPEAT Loop: The robot could rotate 0, 1, or 2 times to the left. Each
rotation changes the robot's facing direction:
○ 0 times: Faces original direction.
○ 1 time: Faces 90 degrees counterclockwise from the original.
○ 2 times: Faces 180 degrees from the original.
● Second REPEAT Loop: The robot moves 0, 1, or 2 tiles forward in the
direction it faces after the rotations.
● Draw a Grid: Start with a 5x5 grid, and mark the robot's starting position
at the center (column 3, row 3).
● Mark Rotations: For each possible rotation scenario (0, 1, 2 times), use an
arrow to indicate the new facing direction from the center.
● Simulate Moves: For each facing direction, draw lines corresponding to
moving forward 0, 1, or 2 tiles. Mark the end of each line. These are
potential landing spots.
● Eliminate Impossible Moves: If a move would take the robot off the grid,
mark it as invalid.
● Count Valid Landing Spots: Note all the grid squares where the robot
could potentially stop.
By physically drawing these paths on paper, you can visually track where the
robot might end up based on different sequences of actions.
70
Big Idea 3: Programming and Algorithms
Analyzing Robot Movement on a Grid with Random Actions
In this scenario, a robot on a 5x5 grid performs a series of random rotations and
movements. The randomness in both rotations and movements introduces
multiple possible outcomes, making it essential to systematically analyze the
potential results. Here’s a step-by-step guide on how to figure out the robot's
possible landing spots based on the given pseudocode.
71
Big Idea 3: Programming and Algorithms
Step 1: Analyze the Rotation Command
● Command: ROTATE_LEFT()
● Randomness: The robot will rotate left between 1 and 3 times. Each ROTATE_LEFT() rotates
the robot 90 degrees counterclockwise.
Possible Rotations:
● Command: MOVE_FORWARD()
● Randomness: The robot will move forward between 1 and 2 steps in whatever direction it is
currently facing after the rotations.
1. Draw the Grid: Sketch a 5x5 grid and mark the starting position in the middle (position C3, if
using column-row notation).
2. Mark Possible Rotations: From the center position, draw arrows in the directions the robot
could potentially face after its rotations (West, South, East).
3. Simulate the Movements:
○ If facing West:
■ Move 1 step west to B3.
■ Move 2 steps west to A3 (if it doesn't exceed grid boundaries).
○ If facing South:
■ Move 1 step south to C2.
■ Move 2 steps south to C1.
○ If facing East:
■ Move 1 step east to D3.
■ Move 2 steps east to E3 (ensure it stays within the grid).
● For each direction the robot could face, use different colored pencils or markers to plot the
1-step and 2-step moves. This helps to visually differentiate the possible ending spots based on
the number of steps taken.
● Boundary Checks: Ensure that none of the movements take the robot off the grid. If a move
would exceed the grid limit, it should not be considered a valid ending spot.
● Overlap Areas: There may be scenarios where different paths lead to the same grid cell. Mark
these overlaps distinctly as they represent higher probability landing spots.
72
Big Idea 3: Programming and Algorithms
Understanding Linear Search
Linear search, also known as sequential search, is a fundamental search algorithm used
in computing to find a specific element within a list. It works on both sorted and
unsorted lists, making it one of the most straightforward searching techniques. Let's
break down the process and how to calculate the number of comparisons needed to find
an element.
Linear search begins at the first element of the list and sequentially checks each
subsequent element until the desired element is found or the list ends. This method is
simple and does not require the list to be sorted, unlike more complex algorithms like
binary search.
Key Points:
● Best Case Scenario: The best case occurs when the target element is the first item
in the list. Here, only one comparison is needed.
● Worst Case Scenario: The worst case happens when the target is at the end of the
list or not present at all. In such cases, the number of comparisons equals the
number of elements in the list (n).
numList ← [“11”, “35”, “2”, “1”, “56”, “76”, “3”, “33”, “90”, “180”]
73
Big Idea 3: Programming and Algorithms
Calculating the Number of Comparisons Using Index
If you know the position (index) of an element in the list, you can directly
determine the number of comparisons needed in a linear search:
numList ← [“11”, “35”, “2”, “1”, “56”, “76”, “3”, “33”, “90”, “180”]
Binary search is an efficient algorithm for finding an element in a sorted list by repeatedly
dividing the search interval in half. It is significantly faster than linear search, especially for
large lists, because it reduces the search space exponentially at each step.
Binary search operates under the assumption that the list is sorted in increasing order. This
sorting allows the algorithm to decisively eliminate half of the search space after each
comparison, based on whether the target value is greater or lesser than the middle element.
Here’s the intuitive logic for why binary search works effectively:
● Initial Middle Comparison: Start by comparing the target value with the middle
element of the list.
● Decision Process:
○ If the target value is equal to the middle element, the search is successful.
○ If the target value is less than the middle element, then it must be in the left half
of the list (because the list is sorted in increasing order).
○ If the target value is greater than the middle element, then it must be in the
right half.
● Repeat Process: This process of halving the list is repeated on the new half (either left
or right), continually narrowing down the possible locations of the target until it is
found or the search space is exhausted.
74
Big Idea 3: Programming and Algorithms
Example of a Binary Search in Steps
Target to Find: 23
1. Initial Middle: The middle element of [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
is 16 (at index 4).
2. Comparison: 23 is greater than 16, so we eliminate the left half of the
array including 16.
3. New Search Space: [23, 38, 56, 72, 91]
4. New Middle: The middle of [23, 38, 56, 72, 91] is 56 (at index 2 of the
new subarray).
5. Comparison: 23 is less than 56, so we eliminate the right half of the
array including 56.
6. New Search Space: [23, 38]
7. New Middle: The middle of [23, 38] is 23.
8. Comparison: 23 equals 23, so the search is successful.
If you attempted binary search on this unsorted array, the logic of halving
based on greater or lesser comparisons breaks down. For example, finding
23 in this unsorted array via binary search would lead to incorrect
eliminations and potentially not finding the target at all.
75
Big Idea 3: Programming and Algorithms
Understanding Flowcharts in Program Design
Flowcharts are essential tools in programming for visualizing the flow of logic in
algorithms and processes. They use various standardized symbols to represent different
types of actions or steps in a program. Let’s define these symbols and how they're used in
a flowchart, and then look at an example flowchart with its corresponding trace.
1. Follow the Path: Start at the 'Start' symbol and follow the paths according to the
input and decisions made at each diamond shape.
2. Understand Decisions: Pay close attention to the decision symbols (diamonds).
Ensure you understand the condition being tested.
3. Look for Loops: If the flowchart contains loops, make sure to understand how
many times the loop runs and under what conditions it stops.
4. Check for Multiple Endpoints: Some flowcharts may have multiple end points
depending on decisions made; ensure to trace each possibility based on different
inputs.
5. Use Scratch Paper: Write down or sketch the path you're following along with any
variables' values to keep track of the process and outcomes.
76
Big Idea 3: Programming and Algorithms
77
Big Idea 3: Programming and Algorithms
Algorithmic Efficiency: Some problems do not have efficient algorithms capable
of solving them within a reasonable timeframe. For these problems, algorithms
with polynomial efficiency (constant, linear, square, cube, etc.) are typically
considered efficient as they can be executed quickly on modern processors.
However, many important and practical problems lack known polynomial-time
algorithms and are tackled using algorithms with exponential or factorial
efficiencies, which are generally too slow to be practical for large datasets.
78
Big Idea 4:
Computer Systems
and Network
Networking Concepts:
Internet Infrastructure:
80
Big Idea 4: Computer Systems and Network
Protocols and Internet Functionality:
● Protocol: A set of agreed-upon rules that dictate how data is transmitted across a
network. Protocols ensure reliable and standardized communication between devices.
● Internet Protocol (IP): IP is crucial for addressing and routing. It assigns unique
addresses (IP addresses) to each device on the internet, facilitating precise data
routing.
● Scalability: This refers to the ability of a network or system to expand and adapt to
increased demands. The internet's design allows it to scale up efficiently,
accommodating more devices and data traffic without losing performance.
● Evolution of Protocols: Internet protocols have evolved to support the growing scale
and complexity of global networks. This evolution is necessary to handle the increasing
number of devices and the vast amount of data transmitted over the internet.
As technology advances and the number of devices connected to the internet increases, the
protocols and infrastructure that support network communication must evolve. Here's an
overview of the transition from IPv4 to IPv6, the roles of TCP and UDP, and the concepts of
fault tolerance and redundancy in network systems.
● Address Length: Uses 32 bits for IP addresses, allowing for approximately 4.29 billion
unique addresses (2^32).
● Limitation: The explosive growth of the internet and connected devices has nearly
exhausted the address capacity of IPv4, leading to the need for a more robust system.
● Address Length: Utilizes 128 bits, which significantly increases the number of possible
IP addresses to about 3.4 x 10^38 (2^128). This expansion addresses the limitations of
IPv4 and supports an expansive future growth of internet-connected devices.
● Benefits: Besides providing a larger address space, IPv6 includes enhancements for
security, routing efficiency, and auto-configuration.
Know for AP Exam: 2^96 times as many addresses can be represented with IPv6.
81
Big Idea 4: Computer Systems and Network
TCP and UDP Protocols
● Functionality: Unlike TCP, UDP is connectionless and does not guarantee the
delivery of packets, meaning it does not resend lost packets. This makes it faster
but less reliable.
● Use Cases: Suitable for applications where speed is more critical than reliability,
such as streaming audio/video or gaming, where missing a few packets might not
disrupt the user experience.
Fault Tolerance:
Redundancy:
The Internet: Refers to the global network of physical hardware — such as computers,
routers, and cables — that allows billions of devices to connect and communicate.
The World Wide Web: Is a service built on top of the internet. It uses the HTTP protocol
to transmit data and is made up of interconnected web pages and web applications.
82
Big Idea 4: Computer Systems and Network
Understanding Sequential vs. Parallel Computing
Sequential Computing
Definition:
Example Calculation:
Parallel Computing
Definition:
83
Big Idea 4: Computer Systems and Network
Example Calculation of Parallel Processing Time:
● If the same task is split where the longest sub-task takes 9 seconds,
then the parallel processing time is 9 seconds.
Speedup Calculation
84
Big Idea 4: Computer Systems and Network
Understanding Distributed Computing
Distributed Computing:
85
Big Idea 5:
Impact of Computing
The "digital divide" refers to the disparities in access to digital technologies, particularly
computers and the internet. This divide can significantly impact various aspects of life,
including education, economic opportunity, and social inclusion.
● Infrastructure: Not all regions have the necessary infrastructure for internet access,
which can be a significant barrier in rural or underdeveloped areas.
● Education: Access to technology isn't enough if individuals lack the education
necessary to use it effectively. Digital literacy is crucial for maximizing the benefits
of internet access.
● Indifference: Some individuals may have access to technology but choose not to
use it, either because they see no personal benefit or due to cultural reasons.
● Cost: The expense associated with securing reliable internet access and
maintaining digital devices can be prohibitive for many people, continuing the
cycle of the digital divide.
● Beneficial Effects: Innovations can improve efficiency, enhance safety, and provide
significant conveniences. For example, GPS technology in vehicles allows drivers to
estimate travel times more accurately, plan routes efficiently, and avoid traffic,
contributing to time management and fuel savings.
● Harmful Effects: The same innovations can have negative repercussions. In the
case of GPS, while it aids in navigation, it can also lead to privacy concerns, such as
unauthorized tracking or data collection by third parties, including law
enforcement or advertisers.
● Benefit: GPS provides real-time location data, helping drivers navigate unfamiliar
areas, which enhances safety and efficiency on the road.
● Harm: However, if this data is accessed by others without consent, it can lead to
privacy violations and potentially enable unwanted surveillance.
87
Big Idea 5: Impact of Computing
The Impact of Bias in Computing Innovations and the Role of Open Access
Influence of Bias:
Mitigating Bias:
Crowdsourcing:
Citizen Science:
Open Access:
● Open access refers to the practice of making research outputs freely available
online without any access restrictions. This approach enhances the visibility and
usability of research findings, accelerating scientific discovery and innovation.
Creative Commons:
● Open Source: Software like the Firefox browser and OpenOffice, which are
made freely available and can be modified and redistributed by anyone.
● Open Access: Scholarly articles and databases that are accessible online
without financial, legal, or technical barriers.
Security:
Privacy:
● Privacy concerns the right of individuals to control their data and restrict its
dissemination to third parties. Measures to protect personally identifiable
information (PII) are critical in maintaining an individual's privacy.
PII Examples:
● Names, social security numbers, biometric records, and any other data that can
uniquely identify an individual.
89
Big Idea 5: Impact of Computing
Privacy, Data Security, and Authentication in Computing
PII Management:
● Economic Value: PII is a valuable asset that can be analyzed, processed, and
often sold by businesses to advertisers, forming a core part of many companies'
business models. This includes details such as name, address, email, and more
sensitive data that can identify an individual.
● Privacy Concerns: The handling and sharing of PII by companies have led to
significant privacy concerns, particularly regarding how securely and
transparently this information is managed.
Metadata Implications:
90
Big Idea 5: Impact of Computing
Authentication Measures
● Goal: Authentication measures are crucial for protecting devices and digital
assets from unauthorized access, ensuring that only verified users can access
sensitive information.
● Implementation: Effective authentication methods help safeguard against
unauthorized data breaches and cyber attacks.
Types of Authentication:
1. Passwords:
○ Criteria: A strong password is crucial for basic security hygiene. It should
be memorable for the user but complex enough to resist guessing or
automated attacks.
○ Best Practices: Use a mix of upper and lower case letters, numbers, and
special characters to increase password strength.
2. Multi Factor Authentication (MFA):
○ Mechanism: MFA enhances security by requiring multiple forms of
verification before granting access. This typically involves two or more of
the following:
■ Knowledge: Something the user knows (e.g., password, PIN).
■ Possession: Something the user has (e.g., a mobile device, security
token).
■ Inherence: Something the user is (e.g., biometric data like
fingerprints or facial recognition).
91
Big Idea 5: Impact of Computing
Digital Certificates and Certificate Authorities
Digital Certificates:
● Digital certificates are used to validate the ownership of encrypted keys that
enable secure communications between parties. They serve as a form of
identity verification for websites or entities engaged in digital transactions or
communications.
● CAs are trusted entities that issue digital certificates. They confirm the identity
of the certificate holder and associate that identity with a public key. In the trust
model, CAs play a crucial role in ensuring that communications and
transactions are secure and that the entities involved are verifiably trustworthy.
Encryption:
● Encryption is the process of converting data into a format that can't be read by
unauthorized users. Cryptographic algorithms are used to transform plain text
into encrypted text, which is known as ciphertext.
Decryption:
● Decryption is the reverse process, where ciphertext is turned back into readable
data using a key.
Types of Encryption:
Definition of Malware:
Computer Viruses:
93
Big Idea 5: Impact of Computing
Understanding Unauthorized Access and Common Cybersecurity Threats
Phishing
Phishing Explained:
Prevention Tips:
1. Verify the Source: Always check the sender's email address and the URL of any
links included in the message to ensure they are legitimate.
2. Do Not Click on Suspicious Links: Avoid clicking on links in unsolicited emails
or messages.
3. Use Anti-Phishing Tools: Employ email filters and browser security tools that
help detect and block phishing attempts.
Keylogging
Keylogging Explained:
Prevention Tips:
Prevention Tips:
95