bhylu.com

Advertisements

C++ Exercises

Filter a mixed batch, retain a valid zero and report the accepted total without changing the input.

Your brief

Your task is to accept parcel counts from zero through one hundred, reject values outside that range and report both the accepted count and total. Predict the result before opening the solution. Zero is a valid count, so it must not be used as a missing-data sentinel. The five-element fixture bounds the maximum possible total at five hundred, making the accumulator choice easy to justify. A stream with no maximum record count would need an explicit size or arithmetic limit.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror exercises.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Worked solution

Show the worked solution
C++20 · exercises.cpp

#include <iostream>
#include <vector>

int main() {
    const std::vector<int> input{4, -1, 0, 101, 7};
    int total{0}; std::size_t accepted{0};
    for (int count : input) {
        if (count < 0 || count > 100) { continue; }
        total += count; ++accepted;
    }
    std::cout << "Accepted: " << accepted << "; total: " << total << '\n';
}

Expected result

Accepted: 3; total: 11

Four, zero and seven are retained. The negative and over-limit values are skipped before accumulation. The input remains unchanged because the loop visits copied ints from a const vector. A valid task extension is a mean over accepted records, but it must handle an accepted count of zero before division and choose whether fractional counts have any useful meaning.

Extend and test

Test an empty vector, all rejected values, only zero and the maximum allowed count. Explain the expected accepted count before running each case.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.

Advertisements