Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← C++ Worked Programs

Learn / Worked program

Triangle Analyzer

Domain checks before geometry

IntermediateDesktop C++17 · runnable source

What you will learn

The complete source

main.cpp

main.cpp
#include <algorithm>
#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

// Read one whole line so a failed conversion cannot trap the input stream.
bool readNumber(const std::string& prompt, double& value, double low, double high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && std::isfinite(value)
            && value >= low && value <= high) {
            return true;
        }
        std::cout << "Enter a finite number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid number was supplied.\n";
    return false;
}

struct Triangle {
    std::array<double, 3> sides;
    double perimeter;
    double area;
    double largestAngleDeg;
};

Triangle analyze(std::array<double, 3> sides) {
    std::sort(sides.begin(), sides.end());
    const double a = sides[0], b = sides[1], c = sides[2];
    const double semiperimeter = (a + b + c) / 2.0;
    const double radicand = semiperimeter * (semiperimeter - a)
                         * (semiperimeter - b) * (semiperimeter - c);
    const double cosine = std::clamp((a*a + b*b - c*c) / (2.0*a*b), -1.0, 1.0);
    return {sides, 2.0 * semiperimeter, std::sqrt(std::max(0.0, radicand)),
            std::acos(cosine) * 180.0 / std::acos(-1.0)};
}

int main() {
    std::array<double, 3> sides{};
    for (double& side : sides) {
        if (!readNumber("Side length (m): ", side, 1e-3, 1e6)) return 1;
    }
    std::sort(sides.begin(), sides.end());
    if (sides[0] <= sides[2] - sides[1]) {
        std::cerr << "These lengths do not form a nondegenerate triangle.\n";
        return 1;
    }
    const Triangle result = analyze(sides);
    const double scale = result.sides[2];
    const double tolerance = 1e-9 * scale;
    const bool firstEqual = std::abs(result.sides[0] - result.sides[1]) <= tolerance;
    const bool lastEqual = std::abs(result.sides[1] - result.sides[2]) <= tolerance;
    const std::string kind = firstEqual && lastEqual ? "equilateral"
                           : firstEqual || lastEqual ? "isosceles" : "scalene";
    const double angle = result.largestAngleDeg;
    const std::string angleKind = std::abs(angle - 90.0) <= 1e-7 ? "right"
                                : angle > 90.0 ? "obtuse" : "acute";
    std::cout << std::fixed << std::setprecision(6)
              << "Side class (tolerance-based): " << kind << '\n'
              << "Angle class: " << angleKind << '\n'
              << "Perimeter (m): " << result.perimeter << '\n'
              << "Area (m^2): " << result.area << '\n'
              << "Largest angle (deg): " << angle << '\n';
}
Source integrity

SHA-256 a4dfb3e36fc74101ae31c2739a78eeb8d144b78d61db7463baed22ed1df7ff55. Display, copy and approved download use the same source.

What it does and why it was selected

The triangle family has the highest mathematical concept density in the small labs. It connects an input domain, sorting, triangle inequality, Heron’s area, law of cosines and numerical tolerances. The rotating-terminal variants add interesting coordinate transformations but also distract from the geometry and complicate termination, so the canonical program retains the analytical core.

Actual execution

main creates a zero-initialized array of three double side lengths. A range-based loop binds side by reference so each successful input updates the stored element rather than a copy. Sorting puts the longest length last. The inequality check rejects a degenerate or impossible triple before any square root or inverse cosine is evaluated. analyze receives an array copy, sorts defensively, computes a semiperimeter, area radicand and cosine, then returns a Triangle containing the ordered lengths and derived values. main uses those results to classify approximate side equality and the largest angle. The 3,4,5 transcript reports perimeter 12, area 6 and a 90-degree largest angle.

Mathematical or state model

For sorted positive a<=b<=c, a+b>c is the only necessary triangle inequality; the other two follow from positivity and ordering. The source tests a>c-b, avoiding unnecessary addition. Heron’s A=sqrt(s*(s-a)(s-b)(s-c)) uses s=(a+b+c)/2. The largest angle lies opposite c, and cos(theta)=(aa+bb-cc)/(2a*b). acos returns radians, so multiplication by 180/pi produces degrees. Area is m^2, perimeter is m, and side classes use a relative tolerance rather than claiming measured lengths are exact.

Design and C++ mechanics

The original code forms long-long squares before converting values for some later formulas. A long-double destination cannot undo overflow that already happened in integer arithmetic. This version uses bounded positive doubles throughout the geometry. std::clamp keeps a cosine perturbed slightly by rounding within the mathematical domain [-1,1]. std::max on the area radicand handles a tiny negative rounding artifact after validity was established; it is not a substitute for a triangle inequality. The returned struct allows the display stage to use one coherent set of results.

Historical differences and limits

Ordinary Heron evaluation loses relative accuracy for almost-flat triangles. Bounds of 1e-3..1e6 and input rejection limit overflow but do not make the formula a robust metrology tool. Near-degenerate cases could benefit from a stable rearrangement of Heron’s formula. Side-class tolerance is 1e-9 times the longest side; the right-angle tolerance is 1e-7 degree. Those tolerances express this program’s numerical policy rather than a physical measurement uncertainty. Animation v2 uses an infinite loop and unreachable cursor restoration; that behavior is discussed in the lineage report, not inherited here.

Useful extensions

A coordinate-output extension could place A at (0,0), B at (c,0), solve xC=(bb+cc-aa)/(2c), and obtain positive yC from bb-xCxC. A genuine geometry visualization should preserve labels and handle both orientations deliberately. Before adding rendering, add nearly-flat triangle tests and choose a stable area implementation.

Source-linked explanations

Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.

Input contract and end-of-file

main.cpp, lines 10–23 →

Only validated finite numbers are allowed to reach the Triangle Analyzer calculation.

Technical explanation
getline consumes a complete line, then a temporary istringstream attempts the numeric conversion. After conversion, trying to extract extra detects a trailing non-whitespace character. Failure of that second extraction means no unwanted data remains. The local stream can fail without putting cin into the historical repeated-failbit state. A fresh local stream is created for every attempt. Low/high comparisons establish the caller’s domain, and exhausting cin ends the while condition and returns false.
Syntax
The && operators evaluate left to right and short-circuit: range tests run only after numeric extraction succeeds. !(input >> extra) intentionally treats no remaining non-whitespace character as success. A double& or int& parameter writes the accepted value into the caller’s variable.
Effect on the program
The caller checks the returned bool and returns exit status 1 on EOF before calculation. Rejected lines are followed by another prompt; valid lines reach the model exactly once.
Common mistake
Clearing a permanently exhausted input stream and retrying cannot create new input. Accepting a numeric prefix such as 550x would silently change the input contract.
Deeper connection
Reliable input separates parsing from physical or algorithmic validity: a valid number still must lie in this program’s supported domain.

input validationconsole ioreferences

The result keeps its input context

main.cpp, lines 25–30 →

The struct stores the ordered side array alongside perimeter, area and largest angle.

Technical explanation
The struct stores the ordered side array alongside perimeter, area and largest angle. Copying the three-element array is inexpensive and makes the result self-contained. Later output does not need access to the input stream or to local calculation temporaries.
Syntax
Later output does not need access to the input stream or to local calculation temporaries.
Effect on the program
Later output does not need access to the input stream or to local calculation temporaries.
Common mistake
Returning only an area would lose the relationship to the sides used to obtain it. A struct groups data but is not an accuracy guarantee.

structsarrays

Heron and cosine share the same sides

main.cpp, lines 32–41 →

The array parameter is passed by value and sorted defensively, so local ordering cannot mutate a caller-owned array.

Technical explanation
The array parameter is passed by value and sorted defensively, so local ordering cannot mutate a caller-owned array. s is semiperimeter; each factor in the area radicand has length units. The clamped cosine belongs to the largest side c. acos returns radians, then multiplication by 180/pi yields degrees. The returned area uses max(0,radicand) only after the caller established triangle validity.
Syntax
The returned area uses max(0,radicand) only after the caller established triangle validity.
Effect on the program
The returned area uses max(0,radicand) only after the caller established triangle validity.
Common mistake
The old long-long squares could overflow before conversion. More precision in a destination does not repair prior integer overflow.

functionsalgorithmsmath libraryfloating point

Reference input mutates the array

main.cpp, lines 45–48 →

The ampersand binds side to an existing element of sides.

Technical explanation
The ampersand binds side to an existing element of sides. readNumber writes through that reference. With double side instead, only a local copy would change and the array would remain zero-initialized. The loop visits precisely the three elements, so no manually maintained numeric index is needed.
Syntax
The loop visits precisely the three elements, so no manually maintained numeric index is needed.
Effect on the program
The loop visits precisely the three elements, so no manually maintained numeric index is needed.
Common mistake
A missing & can silently preserve the original zeros and make later geometry invalid even though the prompts seem to succeed.

referencesarraysloops

Reject before square roots

main.cpp, lines 49–52 →

Sorting ensures sides[2] is longest.

Technical explanation
Sorting ensures sides[2] is longest. If shortest<=longest-middle, the triple is impossible or flat. Returning 1 ends main before analyze sees an invalid domain. This protects both the square-root formula and inverse-cosine interpretation.
Syntax
This protects both the square-root formula and inverse-cosine interpretation.
Effect on the program
This protects both the square-root formula and inverse-cosine interpretation.
Common mistake
Checking positivity alone is insufficient: 1,2,3 is positive but degenerate.

conditionalsarrays

Two tolerances answer different questions

main.cpp, lines 54–62 →

Side equality uses an absolute difference bounded by 1e-9 times the longest side, so changing the length scale changes the side tolerance proportionally.

Technical explanation
Side equality uses an absolute difference bounded by 1e-9 times the longest side, so changing the length scale changes the side tolerance proportionally. Angle classification instead uses an angular tolerance of 1e-7 degree. The nested conditional operator selects a display label after these Boolean facts have been computed.
Syntax
The nested conditional operator selects a display label after these Boolean facts have been computed.
Effect on the program
The nested conditional operator selects a display label after these Boolean facts have been computed.
Common mistake
An epsilon is a policy with units. Reusing a length tolerance as an angle tolerance would compare incompatible quantities.

floating pointconditionals

Recorded input and output

Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.

Sample run

Arguments
None
Recorded exit status
0

Program input

3
4
5

Program output

Side length (m): Side length (m): Side length (m): Side class (tolerance-based): scalene
Angle class: right
Perimeter (m): 12.000000
Area (m^2): 6.000000
Largest angle (deg): 90.000000
5 more recorded behavior and error cases
equilateral
Arguments
None
Recorded exit status
0

Program input

2
2
2

Program output

Side length (m): Side length (m): Side length (m): Side class (tolerance-based): equilateral
Angle class: acute
Perimeter (m): 6.000000
Area (m^2): 1.732051
Largest angle (deg): 60.000000
obtuse
Arguments
None
Recorded exit status
0

Program input

2
3
4

Program output

Side length (m): Side length (m): Side length (m): Side class (tolerance-based): scalene
Angle class: obtuse
Perimeter (m): 9.000000
Area (m^2): 2.904738
Largest angle (deg): 104.477512
degenerate
Arguments
None
Recorded exit status
1

Program input

1
2
3

Program output

Side length (m): Side length (m): Side length (m): 

Error output

These lengths do not form a nondegenerate triangle.
permutation
Arguments
None
Recorded exit status
0

Program input

5
3
4

Program output

Side length (m): Side length (m): Side length (m): Side class (tolerance-based): scalene
Angle class: right
Perimeter (m): 12.000000
Area (m^2): 6.000000
Largest angle (deg): 90.000000
eof
Arguments
None
Recorded exit status
1

Program input

No standard input.

Program output

Side length (m): 

Error output

Input ended before a valid number was supplied.

Build and run

From this folder, with a configured C++17 compiler:

sh
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./program

On Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.

Windows run command from the supplied metadata: .\program.exe.

Desktop compiler setup and platform limits. How headers and translation units fit together.

Verification and provenance

  • Source inspected
  • Compile verified
  • Warning reviewed
  • Behavior verified
  • Sanitizer checked

Supplied evidence: 6 recorded behavior/error cases and 6 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.

Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.

LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.

Source origin and publication treatment

Modernized user supplied source

User-supplied origin; no independent authorship or license determination. Instructor code is not included.

New or rewritten source, limited sanitized historical excerpts when useful

No new license is asserted by this publication.