Thuta Learning
C++
AdvancedProgrammingBeginner

Mini Project

C++Lesson 3040 min

What you'll walk away with

  • Split a program into data structs, calculation functions and a single place that prints
  • Handle an empty list explicitly instead of letting a division produce nan
  • Combine a vector, std::ranges::sort with a projection, count_if and std::format into a small report
  • Test boundary values (exactly 80, just below 40, empty) before trusting the output

Explain it simply

The mini project in plain language

This lesson is not new material; it is a place to use everything so far at once. You will build an analyzer that takes a group of students' marks, works out each average, labels it Excellent, Pass or Fail, sorts from the highest average down and prints a small table.

A project is not just more code; it is a decision about how to split the work. Think of a restaurant: when one person stores ingredients, another cooks and another plates, it is easy to see who made a mistake. In our program, data, calculation and output should be separate places in the same way. There is no keyboard input; the program runs on data written in main, so every run gives the same answer.

Problem → Why → Solution

The problem: an ungraded student is marked as failing

The first version looks complete: it stores marks in a vector, averages them in a function and decides Pass or Fail with if/else. It works for every student in the demo class. Then a new student arrives whose marks have not been entered yet, and the report says "Average mark: nan" followed by "Result: Fail". Nothing crashed and no warning appeared, yet a student who has not been graded was just labelled as failing.

empty_marks.cpp
double calculateAverage(std::vector<int> marks) {   // copies the whole vector
    int total = 0;
    for (int mark : marks) total += mark;
    return static_cast<double>(total) / marks.size();   // 0.0 / 0 when empty
}

std::vector<int> noMarks;                    // student not graded yet
double average = calculateAverage(noMarks);  // nan
if (average >= 80) {
    std::cout << "Result: Excellent\n";
} else if (average >= 40) {
    std::cout << "Result: Pass\n";
} else {
    std::cout << "Result: Fail\n";         // nan fails both tests, so this runs
}

Why nan turns into Fail

Dividing a double by zero is not an error in C++; the result is nan, 'not a number'. Every comparison with nan is false, so both average >= 80 and average >= 40 fail and the else branch runs. A bug that produces a plausible-looking wrong answer is worse than a crash, because nobody notices it. The fix is not clever code; it is deciding up front what an empty list means and handling it in one place.

Core concept: keep data, rules and output apart

The score analyzer has three jobs: hold the data, calculate from it, and show the result. Keep each in its own place. Student and ReportRow are plain structs that only hold data. calculateAverage and resultFor are small functions that take values and return values, with no printing and no input, so you can try them with any numbers. Printing happens in main and nowhere else.

PartResponsibilityExample
Structonly holds dataStudent, ReportRow
Pure functionvalues in, value out, no printingcalculateAverage, resultFor
mainbuilds data, calls functions, printsthe roster, the table

Scripted data replaces keyboard input. A std::vector<Student> written directly in main makes the program behave the same way on every run, which is exactly what you want while you are still checking that it is correct; reading with std::cin can be added later without touching the calculation functions. Note the const: the roster is never modified, and const& parameters let the functions read it without copying.

Decide the edge cases before writing the loop. What is the average of no marks? This program makes the decision explicit in two places: calculateAverage returns 0.0 for an empty vector, and main skips such a student with a message instead of ranking them. Boundaries matter too: with >= 80, an average of exactly 80 is Excellent; with > it would be Pass.

Finally, reuse the standard library instead of writing sorting and counting by hand. std::ranges::sort with a projection orders the report rows by average; std::ranges::greater makes it descending, so the first row is the top student; count_if with a lambda counts the passes. std::format builds aligned columns: {:<6} left-aligns in 6 characters, and {:>8.1f} right-aligns a double with one decimal place in 8. Structs for data, small functions for rules, one place for output: that is the whole recipe.

The report as an assembly line
  1. Scripted roster supplies Students
  2. No marks? Skip with a message
  3. calculateAverage then resultFor
  4. Sort, count, print the table

Only main decides what gets printed; the other functions just return values, so each can be tested on its own.

General pattern

cpp
struct Record { /* only data members */ };

Result compute(const std::vector<Item>& items) {
    if (items.empty()) return /* an explicit, documented answer */;
    /* loop or algorithm */
    return result;
}

int main() {
    const std::vector<Record> input{ /* scripted data */ };
    for (const Record& r : input) { /* call compute, collect rows */ }
}                                  // sort the rows, then print once

A data struct, a calculation function with its own edge-case check, then a main that builds, calls and prints: almost any larger project can start from this shape.

Worked example: a complete student report

The roster holds four students, one with no marks yet. The program skips that student and sorts the others from the highest average down. Notice that calculating the average, deciding the result and printing are separate pieces. The bug from the problem section is closed by one guard in calculateAverage and one skip in main.

score_analyzer.cpp
#include <algorithm>
#include <format>
#include <functional>
#include <iostream>
#include <string>
#include <vector>

struct Student {
    std::string name;
    std::vector<int> marks;
};

struct ReportRow {
    std::string name;
    double average;
    std::string result;
};

double calculateAverage(const std::vector<int>& marks) {
    if (marks.empty()) return 0.0;               // avoid dividing by zero
    int total = 0;
    for (int mark : marks) total += mark;
    return static_cast<double>(total) / marks.size();
}

std::string resultFor(double average) {
    if (average >= 80) return "Excellent";
    if (average >= 40) return "Pass";
    return "Fail";
}

int main() {
    const std::vector<Student> students{
        {"Aye", {80, 72, 65, 90, 58}},
        {"Ko", {92, 88, 79}},
        {"Su", {35, 42, 28, 41}},
        {"Min", {}},                             // no marks entered yet
    };

    std::vector<ReportRow> report;
    for (const Student& s : students) {
        if (s.marks.empty()) {
            std::cout << s.name << ": no marks yet, skipped\n";
            continue;
        }
        double avg = calculateAverage(s.marks);
        report.push_back({s.name, avg, resultFor(avg)});
    }

    std::ranges::sort(report, std::ranges::greater{}, &ReportRow::average);

    std::cout << std::format("{:<6}{:>8}  {}\n", "Name", "Average", "Result");
    for (const ReportRow& row : report) {
        std::cout << std::format("{:<6}{:>8.1f}  {}\n",
                                 row.name, row.average, row.result);
    }

    auto passed = std::ranges::count_if(report, [](const ReportRow& r) {
        return r.result != "Fail";
    });
    std::cout << "Passed: " << passed << " of " << report.size() << '\n';
    if (!report.empty()) {
        std::cout << "Top student: " << report.front().name << '\n';
    }
}

Code breakdown

  1. Plain structs hold the datastruct Student {

    Student holds only a name and marks, with no functions. ReportRow just gathers the values one table line needs, so when it is sorted the whole row moves together.

  2. A guarded calculationif (marks.empty()) return 0.0;

    This line stops the nan from the problem section: an empty vector returns 0.0 before the division is reached. The parameter is const&, so the vector is not copied either.

  3. The rule lives in one placeif (average >= 80) return "Excellent";

    The two thresholds, 80 and 40, exist only inside resultFor. To change them you edit this one place, and because it uses >=, a student with exactly 80 is Excellent.

  4. Skip instead of guessingif (s.marks.empty()) {

    For a student with no marks, main prints "no marks yet, skipped" and moves on with continue. That is why Min never appears in the table as a failure.

  5. Sort by a projectionstd::ranges::sort(report, std::ranges::greater{}, &ReportRow::average);

    &ReportRow::average pulls just the average out of each row, and greater orders those doubles from highest to lowest. You never write a comparison operator for ReportRow itself.

  6. Aligned outputstd::format("{:<6}{:>8.1f} {}\n",

    {:<6} left-aligns the name and {:>8.1f} right-aligns the average with one decimal place, so Ko's 86.333... prints as 86.3 and the columns line up.

You should see
Min: no marks yet, skipped
Name   Average  Result
Ko        86.3  Excellent
Aye       73.0  Pass
Su        36.5  Fail
Passed: 2 of 3
Top student: Ko
How each student travels into the report
  1. Take one Student from the scripted roster
  2. No marks? Print a message and skip
  3. calculateAverage returns a double
  4. resultFor returns Excellent, Pass or Fail
  5. Add a ReportRow; sort and print afterwards

average >= 80

Excellent

40 <= average < 80

Pass

average < 40

Fail

Probing the boundaries instead of trusting

Because the rules live in small functions, you can probe them without a whole roster. The program below calls them with the values that matter most: exactly on a threshold (80, 40), just below it (79.9, 39.9), the extremes (100, 0), and then no marks, one mark, and a pair whose average has a fractional part.

boundary_checks.cpp
#include <iostream>
#include <string>
#include <vector>

std::string resultFor(double average) {
    if (average >= 80) return "Excellent";
    if (average >= 40) return "Pass";
    return "Fail";
}

double calculateAverage(const std::vector<int>& marks) {
    if (marks.empty()) return 0.0;
    int total = 0;
    for (int mark : marks) total += mark;
    return static_cast<double>(total) / marks.size();
}

int main() {
    const double averages[] = {100.0, 80.0, 79.9, 40.0, 39.9, 0.0};
    for (double a : averages) {
        std::cout << a << " -> " << resultFor(a) << '\n';
    }
    std::cout << "empty -> " << calculateAverage({}) << '\n';
    std::cout << "one mark -> " << calculateAverage({63}) << '\n';
    std::cout << "70, 71 -> " << calculateAverage({70, 71}) << '\n';
}

The output is 100 -> Excellent, 80 -> Excellent, 79.9 -> Pass, 40 -> Pass, 39.9 -> Fail, 0 -> Fail, then empty -> 0, one mark -> 63 and 70, 71 -> 70.5. The last line proves the static_cast is doing its job: without it, integer division would give 70.

In real projects

This shape in real projects

The shape of data structs, side-effect-free calculation functions and a single place to print reaches far beyond a gradebook. Only the data changes; the way of working stays the same:

  • Report card and gradebook systems compute each course's average, a list of students below the line and a top-student list exactly the way this project does.
  • Invoices and sales reports store line items in a struct, let a function compute totals and tax, sort by product and print a table.
  • Monitoring and metrics average each server's response time, and there too a server with no data yet must be skipped rather than reported as healthy.
  • Automated tests call functions such as calculateAverage with expected values; they are a bigger version of this project's boundary checks.

Common mistakes

Common mistakes in a project like this

Dividing by size() without checking for empty

With empty marks, static_cast<double>(total) / marks.size() is 0.0 / 0 and gives nan (some platforms print it as -nan). Nothing crashes, so a Fail label sneaks in unnoticed. Check if (marks.empty()) at the top of the function and decide what to return.

Dividing two ints and storing into a double

In double avg = total / count; both total and count are ints, so the division happens without decimals first and only then the result is stored in a double. 141 / 2 gives 70, not 70.5. Cast one operand with static_cast<double> first; the double on the left does not help.

Copying thresholds into several places

If 80 is written in the print line, the counting line and resultFor, someone edits one place and the others quietly disagree. Keep the thresholds in resultFor alone and call that function. Check >= versus > by testing exactly 80 and 79.9.

Passing the vector by value

double calculateAverage(std::vector<int> marks) copies every mark on each call. With five marks you will not notice, but in a report of hundreds of thousands of records it is a pile of needless allocations. For read-only access, use const std::vector<int>&.

Best practices

Best practices

  • Give each function one job: a calculating function does not print, and printing code does not calculate.
  • Before writing the loop, list the three kinds of edge case, empty, a single item and boundary values, and handle each one.
  • Keep magic numbers in one named place so a rule change is a single edit.
  • Do not just eyeball the output; compare it with a hand-worked example, such as Ko = (92 + 88 + 79) / 3 = 86.3.

Mini challenge

Mini challenge: class statistics

Extend the project. Write one function that returns each student's lowest mark, highest mark and the number of marks below 40, and another that computes a class average across every mark of every student. The scripted roster must include a student with no marks, shown in the table as a 'no marks' row.

  • statsFor(marks) returns a MarkStats; use std::ranges::minmax and count_if
  • classAverage returns 0.0 when there are no marks, otherwise adds into an int and divides as a double
  • Print the table with std::format and aligned columns, and only inside main
  • Take no input; write the roster directly in main so the output is identical on every run
class_stats.cpp
#include <algorithm>
#include <format>
#include <iostream>
#include <string>
#include <vector>

struct Student {
    std::string name;
    std::vector<int> marks;
};

struct MarkStats {
    int lowest = 0;
    int highest = 0;
    int below40 = 0;
};

// TODO: return the stats for a non-empty list (minmax plus count_if)
MarkStats statsFor(const std::vector<int>& marks) {
    return {};
}

// TODO: average over every mark of every student; 0.0 when there are no marks
double classAverage(const std::vector<Student>& students) {
    return 0.0;
}

int main() {
    // TODO: a scripted roster of four students, one with an empty marks vector
    // TODO: print a header, then one aligned row per student
    // TODO: students without marks get a "no marks" row instead of stats
    // TODO: print the class average with one decimal place
}

Expected: The table shows Hla 38 / 71 / 1, Zaw 85 / 97 / 0, Nwe as 'no marks' and Thu 29 / 52 / 2, then Class average: 60.2 (the 11 marks add up to 662, divided by 11).

Show hint

auto [low, high] = std::ranges::minmax(marks); gives both values at once; check for an empty list in main first so it is never called on one. In classAverage, add each student's marks with an inner loop and keep a running count alongside. Pick your own column widths for the table, such as {:<5}{:>5}{:>6}{:>9}.

Show solution
class_stats.cpp
#include <algorithm>
#include <format>
#include <iostream>
#include <string>
#include <vector>

struct Student {
    std::string name;
    std::vector<int> marks;
};

struct MarkStats {
    int lowest = 0;
    int highest = 0;
    int below40 = 0;
};

MarkStats statsFor(const std::vector<int>& marks) {
    MarkStats stats;
    if (marks.empty()) return stats;             // caller checks empty first
    auto [low, high] = std::ranges::minmax(marks);
    stats.lowest = low;
    stats.highest = high;
    stats.below40 = static_cast<int>(
        std::ranges::count_if(marks, [](int m) { return m < 40; }));
    return stats;
}

double classAverage(const std::vector<Student>& students) {
    int total = 0;
    int count = 0;
    for (const Student& s : students) {
        for (int m : s.marks) total += m;
        count += static_cast<int>(s.marks.size());
    }
    return count == 0 ? 0.0 : static_cast<double>(total) / count;
}

int main() {
    const std::vector<Student> students{
        {"Hla", {55, 38, 71, 64}},
        {"Zaw", {91, 85, 97}},
        {"Nwe", {}},
        {"Thu", {33, 47, 29, 52}},
    };

    std::cout << std::format("{:<5}{:>5}{:>6}{:>9}\n", "Name", "Low", "High", "Below40");
    for (const Student& s : students) {
        if (s.marks.empty()) {
            std::cout << std::format("{:<5}{:>20}\n", s.name, "no marks");
            continue;
        }
        MarkStats st = statsFor(s.marks);
        std::cout << std::format("{:<5}{:>5}{:>6}{:>9}\n",
                                 s.name, st.lowest, st.highest, st.below40);
    }
    std::cout << std::format("Class average: {:.1f}\n", classAverage(students));
}

Quick quiz 1 / 3

calculateAverage computes static_cast<double>(total) / marks.size() and marks is empty. What happens?

Quick quiz 2 / 3

After int total = 141; int count = 2; double avg = total / count;, what is avg?

Quick quiz 3 / 3

After std::ranges::sort(report, std::ranges::greater{}, &ReportRow::average);, what order are the rows in?

What to remember

  • Data in structs, rules in small non-printing functions and output in main let you test each piece without touching the rest.
  • Dividing a double by zero gives nan and every comparison turns false, so decide what an empty list means and handle it.
  • Dividing two ints is integer division, so apply static_cast<double> to one operand first.
  • std::ranges::sort with a projection, count_if and std::format replace several hand-written loops with a few readable lines.
  • Trust the output only after probing values exactly on a threshold, just below it and empty.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Mini Project | Thuta Learning