Summing with an Accumulator

Two common loop tasks

There are two common tasks that use for loops:
1. Summing
2. Counting
This set is about summing. Counting comes next, and the two share a shape you will start to recognise.

Summing values

Write a segment of code that solves the problem 1 + 2 + 3 + ... + 98 + 99 + 100.
We need a variable that accumulates the sum at each iteration of the loop. This variable should be initialized to 0.

Writing a function to sum

Now write a function that accepts a non-negative integer parameter n and returns the sum of integers from 1 to n (including n).

Conditional summing

Write a segment of code that computes the sum of all numbers from 1 to 100 that are multiples of 3. Loop over everything, but only add when a certain condition is true.

Back to the opening problem

Here is the repetitive five-input program from the start of this unit, rewritten with a for loop.