3.3 - 3.4 Notes
- Vocab
- What is an Algorithm?
- 3 Components of an Algorithm
- Representing Algorithms
- Arithmetic Operations
- Application of Mathematical Expressions
- Variables
- Strings
What is an Algorithm?
a set of instructions that can accomplish a specific task
3 Components of an Algorithm
- Sequencing: Algorithms do tasks in the order of specification.
- Selection: Helps choose two different outcomes based off a decision.
- Iteration: If a condition is true, then the code can repeat.
Representing Algorithms
- Flowcharts: Use shapes and arrows to represent the steps of an algorithm.
- Pseudocode: A blend of human language and coding format.
Subtraction - represented by "-"
num1 = 2 - 1
Addition - Represented by "+"
num1 = 2 + 1
Multiplication - Represented by “*”
num1 = 2 * 1
Division - Represented by “/”
num1 = 2 / 1
Getting the Remainder - Represented by “MOD” (% in python)
num1 = 5 % 2
Note: collegeboard pseudocode starts at 1
- items can be numbers or variables
num1 = 10 # "num1", "num2", etc. are variables
num2 = num1 - 25 # we can perform mathematical expressions on the variables as well
num3 = 100 * num1
num4 = num1 / num2
num5 = 9 % num4
- order of operations (same as in normal math)
num1 = 9 % 2 * ( 8 - 2 ) + 8 / ( 6 - 4 )
print(num1) # should print 10
Variables
4 Different Ways to Store Variables
- Numerical value stored in a variable
ex. score = 0
- Value of another variable stored in a variable
ex. score = newScore
- Performing mathematical expressions on a variable/Result of an operation stored in a variable
ex. score = newScore + 1
- Result of a procedure call stored in a variable
ex. avgScore = allScores(20, 60, 80)
Sequencing
- every time a new value is assigned to a variable, it overrides the last value which was assigned to the same variable
- changing order of steps changes overall outcome
num1 = 2
num2 = 4
num3 = 6
num1 = num2 + num3 # num1 is now 4 + 6, which is 10
num2 = num1 + num3 # num2 is now (the new num1) 10 + 6, which is 16
# output: num1 = 10, num2 = 16, num3 = 6
#vs.
num1 = 2
num2 = 4
num3 = 6
num2 = num1 + num3 #num2 is now 8
num1 = num2 + num3 # num1 is now 14
# output: num1 = 14, num2 = 8, num3 = 6
Tracking Variables - AP Exam Question
- make sure to account for every time a variable changes when writing code
var1 = 9
var2 = 7
var3 = 2
var = var1 + 5
var2 = var1 - var3
var1 = var2
var3 = (var1 + var2) / 2
var2 = 6
print(var1) # question would ask something like, what's the value of var1, var2, and var3
print(var2)
print(var3)
Substring Example
substring("abcdefghijkl", 2, 5) would print bcde