C++ conditions and range loops

Filter a sequence while accumulating a result.

C++
#include <iostream>
#include <vector>
#include <cassert>
int main() {
    std::vector<int> values{-2, 0, 3, 5};
    int total = 0;
    for (int value : values) {
        if (value > 0) total += value;
    }
    std::cout << total << '\n';
    assert(total == 8);
}
Output
8

Explanation

A range-based for loop visits each element of a container. This version copies each int into value, which is inexpensive for a small scalar.

The condition includes only positive values. Zero and negative values leave the accumulator unchanged.

Explore the dry run
Guided walkthroughReady
1#include <iostream>
2#include <vector>
3#include <cassert>
4int main() {
5 std::vector<int> values{-2, 0, 3, 5};
6 int total = 0;
7 for (int value : values) {
8 if (value > 0) total += value;
9 }
10 std::cout << total << '\n';
11 assert(total == 8);
12}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Construct four values.values = [-2, 0, 3, 5]
—
Initialize the sum.total = 0
—
Skip -2 and 0, then add 3.total = 3
—
Add 5.total = 8
—
Print the total.total = 8
8

Cost and common mistakes

O(n) time and O(1) auxiliary space excluding the vector.

  • Use a reference loop variable if you intend to modify container elements.
  • Signed overflow is undefined behavior; use an appropriate numeric range.

Try it yourself

Change the test to value >= 0. Does this total change?

Reveal answer and reasoning

No, adding zero does not change a sum. A count of matching values would change.

Further reading