C++ conditions and range loops
Filter a sequence while accumulating a result.
On this page
Variables, vectors, and basic output.
- Filter a sequence while accumulating a result.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
#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);
}8
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#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);}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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
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.