Learn / Worked program
Circle Geometry Table
Finite loops on a floating-point grid
What you will learn
- Console streams and complete-line input/outputProgram-local teaching concept
- Finite double arithmetic, precision and round-offValues and typesProgram-local teaching concept
- Branch order, validated domains and early returnsLearn conceptDecisions and repetition
- Parameters, cohesive calculation functions and return valuesLearn conceptFunctions as interfaces
- Physical quantities, conversions and dimensionally consistent modelsProgram-local teaching concept
- Persistent stream formats and per-field width/precisionProgram-local teaching concept
- Finite iteration domains and termination conditionsDecisions and repetitionProgram-local teaching concept
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Transcendental functions and their numerical domainsProgram-local teaching concept
- Complete-line parsing, bounded input and EOF terminationDebugging and code qualityProgram-local teaching concept
The complete source
main.cpp
#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;
}
int main() {
double first = 0.0, last = 0.0, step = 0.0;
if (!readNumber("First radius (m): ", first, 0.0, 1e6)
|| !readNumber("Last radius (m): ", last, first, 1e6)
|| !readNumber("Radius step (m): ", step, 1e-6, 1e6)) return 1;
const double intervals = (last - first) / step;
if (intervals > 10000.0) {
std::cerr << "Table limited to 10001 rows; choose a larger step.\n";
return 1;
}
const int steps = static_cast<int>(std::floor(intervals + 1e-9));
const double pi = std::acos(-1.0);
std::cout << "radius_m area_m2 circumference_m\n" << std::fixed << std::setprecision(6);
// Derive radius from an integer index; never accumulate a floating step.
for (int index = 0; index <= steps; ++index) {
const double radius = first + index * step;
std::cout << radius << ' ' << pi * radius * radius << ' ' << 2.0 * pi * radius << '\n';
}
}
Source integrity
SHA-256 0ea38bc5c745cf2ae2335f6715ad80f4f081b952ead8422b6ad8e6eacd9c531a. Display, copy and approved download use the same source.
What it does and why it was selected
The circle family is stronger as one table generator than as several near-duplicate labs. Lab14 exposes a real control-flow defect: its radius limits are checked, but its step can be zero or negative. Correcting that makes the program a useful study of termination, numerical grids and engineering units.
Actual execution
main reads the first radius, the final allowed radius, and a positive step. The last-radius prompt uses the first value as its lower bound, so reversed intervals are rejected before table construction. The quotient (last-first)/step estimates the number of intervals. More than 10000 intervals exits with a diagnostic. After floor and a small rounding allowance, the integer steps variable sets the loop bound. Each iteration derives a fresh radius from first+index*step, calculates area and circumference, and prints one row. The sample 1..2 with step 0.5 gives three rows, not two.
Mathematical or state model
For radius r in meters, A=pirr is in square meters and C=2pir is in meters. pi is calculated once using acos(-1). The program assumes ideal circular geometry. A step that does not divide the requested span produces a final sample below the endpoint: 0..1 with 0.3 gives 0, 0.3, 0.6 and 0.9. It does not invent an extra unequal step solely to hit 1.
Design and C++ mechanics
An integer loop index establishes a reliable finite iteration count, while radius remains floating-point so fractional steps are allowed. This avoids accumulating 0.1 repeatedly in the loop variable. It does not make every derived radius exact; floating-point multiplication and addition still round. The 1e-9 allowance is expressed in interval-count units and only absorbs tiny endpoint-count errors. The source’s accepted scale range and row cap keep this policy bounded and explainable.
Historical differences and limits
The old zero-step path was observed repeatedly printing rows until the controlled output cap stopped it. That is not a legitimate table. The canonical version rejects zero, negative and very small unsupported steps; an excessively dense valid grid exits before producing thousands of unwanted rows. Its results are rounded to six decimal places, so a tiny geometric quantity can print zero even though its internal value is nonzero. No sphere formulas or animation are included simply because other circle-family files had them.
Useful extensions
Add a CSV export or separate an area/circumference function from the display loop when another consumer actually needs it. If supporting very large radii or extremely fine grids, revisit multiplication range, row count, endpoint policy and output precision together. Retaining a finite upper bound is part of correctness, not merely convenience.
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 8–21 →Only validated finite numbers are allowed to reach the Circle Geometry Table 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.
A finite row-count decision
main.cpp, lines 28–35 →The real-valued quotient describes the requested span in step units.
- Technical explanation
- The real-valued quotient describes the requested span in step units. The row guard runs before casting to int. Since intervals is bounded by 10000 and nonnegative, the cast has a defined representable result. floor(intervals+1e-9) produces a bounded interval count, and including index zero adds the initial row.
- Syntax
- floor(intervals+1e-9) produces a bounded interval count, and including index zero adds the initial row.
- Effect on the program
- floor(intervals+1e-9) produces a bounded interval count, and including index zero adds the initial row.
- Common mistake
- Zero step makes the quotient invalid and the old loop nonterminating. Casting an arbitrary unbounded floating number to int can itself be invalid.
- Deeper connection
- Read the program’s mathematical or state model
Generate rather than accumulate the grid
main.cpp, lines 37–41 →Each radius is first+index*step.
- Technical explanation
- Each radius is first+index*step. The integer index increases predictably, while each radius receives one independent floating calculation. Area multiplies radius twice and circumference once, giving different dimensional outputs. index<=steps includes the final allowed sampled index.
- Syntax
- index<=steps includes the final allowed sampled index.
- Effect on the program
- index<=steps includes the final allowed sampled index.
- Common mistake
- Repeatedly adding 0.1 to a double loop variable can miss the intended endpoint; using <= does not remove that rounding issue.
- Deeper connection
- Read the program’s mathematical or state model
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
1 2 0.5
Program output
First radius (m): Last radius (m): Radius step (m): radius_m area_m2 circumference_m 1.000000 3.141593 6.283185 1.500000 7.068583 9.424778 2.000000 12.566371 12.566371
6 more recorded behavior and error cases
fractional step
- Arguments
None- Recorded exit status
- 0
Program input
0 1 0.1
Program output
First radius (m): Last radius (m): Radius step (m): radius_m area_m2 circumference_m 0.000000 0.000000 0.000000 0.100000 0.031416 0.628319 0.200000 0.125664 1.256637 0.300000 0.282743 1.884956 0.400000 0.502655 2.513274 0.500000 0.785398 3.141593 0.600000 1.130973 3.769911 0.700000 1.539380 4.398230 0.800000 2.010619 5.026548 0.900000 2.544690 5.654867 1.000000 3.141593 6.283185
nondivisible
- Arguments
None- Recorded exit status
- 0
Program input
0 1 0.3
Program output
First radius (m): Last radius (m): Radius step (m): radius_m area_m2 circumference_m 0.000000 0.000000 0.000000 0.300000 0.282743 1.884956 0.600000 1.130973 3.769911 0.900000 2.544690 5.654867
zero step recover
- Arguments
None- Recorded exit status
- 0
Program input
1 2 0 1
Program output
First radius (m): Last radius (m): Radius step (m): Enter a finite number in [1e-06, 1e+06]. Radius step (m): radius_m area_m2 circumference_m 1.000000 3.141593 6.283185 2.000000 12.566371 12.566371
row limit
- Arguments
None- Recorded exit status
- 1
Program input
0 1 0.000001
Program output
First radius (m): Last radius (m): Radius step (m):
Error output
Table limited to 10001 rows; choose a larger step.
one row
- Arguments
None- Recorded exit status
- 0
Program input
2 2 1
Program output
First radius (m): Last radius (m): Radius step (m): radius_m area_m2 circumference_m 2.000000 12.566371 12.566371
eof
- Arguments
None- Recorded exit status
- 1
Program input
No standard input.
Program output
First radius (m):
Error output
Input ended before a valid number was supplied.
Build and run
From this folder, with a configured C++17 compiler:
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./programOn 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: 7 recorded behavior/error cases and 7 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.