Algorithm CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumHere is an algorithm: 1. Set total = 0. 2. For each number in the list [3, 7, 2, 8]: add the number to total. 3. Output total. What does this algorithm compute?
Solution
- 1 Step 1: Trace through: total starts at 0. After 3: total = 3. After 7: total = 10. After 2: total = 12. After 8: total = 20.
- 2 Step 2: The algorithm outputs 20.
- 3 Step 3: This algorithm computes the sum of all numbers in the list.
Answer
The algorithm computes the sum of the list. Output: 20.
Tracing through an algorithm step by step helps us understand what it does. This is a fundamental skill in computational thinking and debugging.
About Algorithm
A step-by-step set of instructions for solving a problem or accomplishing a specific task. An algorithm must be precise (every step is unambiguous), finite (it terminates after a bounded number of steps), and effective (each step can actually be carried out).
Learn more about Algorithm โ