Algorithms & Variables
An algorithm is a step-by-step sequence of instructions designed to solve a specific problem or perform a calculation. Variables serve as containers that store and update values as the algorithm executes. Together, algorithms and variables form the foundation of computational problem-solving, where each instruction modifies variable values according to predetermined rules.
Why it matters
Algorithms and variables power everything from GPS navigation systems that calculate optimal routes through millions of possible paths, to banking software that processes over 150 billion transactions annually. Search engines use algorithms with thousands of variables to rank web pages in milliseconds. In manufacturing, robotic assembly lines follow algorithmic instructions while tracking variables like temperature (within 2-degree tolerances) and production counts. Video games update player scores, health points, and inventory items through variable assignments executed 60 times per second. Financial trading algorithms analyze market variables and execute trades worth $5 trillion daily. Even simple applications like calculating tax on a $47.50 purchase rely on algorithmic steps that update price variables through multiplication and addition operations.
How to solve algorithms & variables
Algorithms
- An algorithm is a step-by-step set of instructions to solve a problem.
- Must be precise, unambiguous, and have a clear end.
- Flowcharts use shapes: oval (start/end), rectangle (process), diamond (decision).
- Trace through algorithms with sample inputs to check correctness.
Example: Find max of a, b: if a > b → max = a, else max = b.
Worked examples
x = 10; x = x - 2. What is x?
Answer: 8
- Set initial value → x = 10 — x starts at 10.
- Subtract 2 → x = 10 - 2 = 8 — x becomes 8.
score = 17; if score <= 20: score = score - 5. What is score?
Answer: 12
- Check the condition → Is 17 <= 20? Yes — 17 <= 20 is true.
- Execute if true → x = 12 — Subtract 5: 17 - 5 = 12
x = 0; repeat 4 times: x = x + 3. What is x?
Answer: 12
- Trace each iteration → 0 -> 3 -> 6 -> 9 -> 12 — Add 3 each time, 4 times.
- Or use shortcut → 3 x 4 = 12 — Adding 3 a total of 4 times equals 3 x 4.
Common mistakes
- Confusing the assignment operator with equality: writing x = 5 to mean 'x equals 5' when it actually means 'assign 5 to x', leading to errors like thinking x = x + 1 is impossible instead of recognizing it updates x by adding 1
- Forgetting to trace variable updates step-by-step: jumping from x = 3 through a loop that adds 4 three times and incorrectly stating x = 7 instead of the correct x = 15
- Misunderstanding conditional execution: assuming score = score - 5 always executes when the condition is if score > 20, missing that score = 18 would remain unchanged at 18
- Mixing up loop iteration counts: believing 'repeat 5 times: x = x × 2' starting with x = 1 gives x = 10 instead of x = 32