Welcome back to our journey into the world of algorithms! In this section, we'll tackle a fundamental problem that's surprisingly common in programming: calculating the sum of a series of numbers. This might seem simple, but it's a fantastic stepping stone to understanding how computers can perform repetitive tasks efficiently.
Imagine you have a list of numbers, say 5, 10, and 3. Your goal is to find their total. In human terms, you'd just add them up: 5 + 10 + 3 = 18. An algorithm essentially automates this process for a computer, especially when the list of numbers might be very long or change frequently.
To solve this problem algorithmically, we need a way to keep track of the running total as we go through the numbers. We'll introduce a variable, let's call it sum, and initialize it to zero. This sum variable will act as our accumulator.
graph TD;
A[Start]
B[Initialize sum = 0]
C{Are there more numbers to add?}
D[Get the next number]
E[Add the number to sum]
F{Are there more numbers to add?}
G[Output sum]
H[End]
A --> B
B --> C
C -- Yes --> D
D --> E
E --> F
F -- Yes --> D
C -- No --> G
F -- No --> G
G --> H
Here's how the process works, step-by-step, using our example list of 5, 10, and 3:
- Initialization: We start by setting
sumto 0.
let sum = 0;- First Number: We take the first number, which is 5, and add it to our
sum. So,sumbecomes 0 + 5 = 5.
sum = sum + 5; // sum is now 5- Second Number: Next, we take the second number, 10, and add it to the current
sum.sumbecomes 5 + 10 = 15.