Small Steps III — Thinking with Programs

Adding values in order

Add values in order.

What you will learn

An algorithm is a procedure for finding an answer. Calculate a sum by remembering the total so far and adding the next value.

Try it

Example · example1.cpp
void small_main()
{
    Array<int> numbers = {3, 7, 2, 9, 4};
    int total = 0;

    for (int i = 0; i < numbers.length(); i = i + 1)
        total = total + numbers[i];

    print("Sum: ", total);
}

total changes from 0 → 3 → 10 → 12 → 21 → 25. The expected output is Sum: 25.

Before any values have been added, their sum is 0, so the initial value is 0. Creating total with 0 inside every iteration prevents accumulation.

Exercise

Find an Array's sum, divide by its number of values, and print the average. Make total a double so the division can produce a fractional result.

Exercise starter · exercise1_starter.cpp
void small_main()
{
    Array<int> numbers = {10, 20, 30, 40};
    double total = 0;

    // Add the values and print the average.
}

Hint

Start with double total = 0; and calculate total / numbers.length() at the end.

show solution
void small_main()
{
    Array<int> numbers = {10, 20, 30, 40};
    double total = 0;

    for (int i = 0; i < numbers.length(); i = i + 1)
        total = total + numbers[i];

    print("Average: ", total / numbers.length());
}
← Previous lessonNext lesson →