Learn / Worked program
Two-Resistor Network Calculator
Keep electrical topology separate from input and display
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
- Named value records and grouped stateLearn conceptRecords, enumerations, and classes
- Aliases for mutable or read-only existing objectsLearn conceptPointers and references
- Complete-line parsing, bounded input and EOF terminationDebugging and code qualityProgram-local teaching concept
The complete source
main.cpp
#include <algorithm>
#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 ResistancePair {
double seriesOhms;
double parallelOhms;
};
ResistancePair equivalent(double first, double second) {
// Scaling avoids forming the product first*second.
const double low = std::min(first, second);
const double high = std::max(first, second);
return {first + second, low / (1.0 + low / high)};
}
int main() {
double first = 0.0, second = 0.0;
if (!readNumber("First resistance (ohms): ", first, 1e-9, 1e12)
|| !readNumber("Second resistance (ohms): ", second, 1e-9, 1e12)) return 1;
const ResistancePair result = equivalent(first, second);
std::cout << std::fixed << std::setprecision(6)
<< "Series (ohms): " << result.seriesOhms << '\n'
<< "Parallel (ohms): " << result.parallelOhms << '\n';
}
Source integrity
SHA-256 ac94c41c4956715993ed777cc94569911b8249855fd58f51312b060b84203a1a. Display, copy and approved download use the same source.
What it does and why it was selected
The historical lab already separates seriesResistance and parallelResistance, making it a useful starting point for function design. The canonical version returns both configurations together, removes a replay choice whose two branches do the same thing, and establishes a positive finite resistor domain.
Actual execution
main accepts two positive resistance values and passes copies to equivalent. That function computes the lower and higher value, then returns ResistancePair with series and parallel results. main prints the two fields without making an electrical-model decision in the display stage. For 100 and 200 ohms, the actual sample reports 300.000000 ohms in series and 66.666667 ohms in parallel. Equal 100-ohm resistors produce 200 and 50 ohms, which is a useful quick check.
Mathematical or state model
Series elements carry the same current, so their voltage drops add and Req=R1+R2. Parallel elements share the same voltage, so conductances add: 1/Req=1/R1+1/R2. For positive resistors, the parallel answer must be less than either input; the series answer must exceed either. The equivalent function evaluates the parallel expression as low/(1+low/high), algebraically identical to the reciprocal formula while avoiding formation of the product R1*R2.
Design and C++ mechanics
The two output fields describe alternative topologies for the same inputs; the program is not simultaneously placing both connections in one circuit. A struct avoids returning only one result and recalculating the other elsewhere. std::min and std::max clarify the numerical rearrangement. The upper bound of 1e12 keeps the series sum finite in the teaching domain. This is a portable desktop calculation, with no board, pins, Arduino framework or PlatformIO configuration.
Historical differences and limits
Zero resistance is excluded deliberately. A mathematical ideal short across a parallel network can be modeled, but the reciprocal formula needs an explicit zero branch and the physical interpretation must be taught. Negative resistance devices are also outside this introductory passive-resistor model. The historical source permitted zeros and negatives, so successful ordinary positive-input runs did not prove its domain handling was sound. It contained the memorable message that the user had no choice, because either answer led to parallel output; the branch duplication is documented rather than retained as necessary software structure.
Useful extensions
Generalize series to a vector sum and parallel to a sum of conductances only after explaining ownership and nonempty inputs. A tolerance analysis could compare nominal resistances with uncertainty bounds. Adding resistor colors should remain a separate input translation step that produces ohms for the same calculation functions.
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 9–22 →Only validated finite numbers are allowed to reach the Two-Resistor Network Calculator 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.
Represent alternative topologies
main.cpp, lines 24–27 →The two fields preserve separate series and parallel interpretations for the same input pair.
- Technical explanation
- The two fields preserve separate series and parallel interpretations for the same input pair. They do not imply one physical network containing both connections at once. Named fields make output labels meaningful at the call site.
- Syntax
- Named fields make output labels meaningful at the call site.
- Effect on the program
- Named fields make output labels meaningful at the call site.
- Common mistake
- Returning an unlabeled two-element array would make it easier to exchange series and parallel accidentally.
- Deeper connection
- Read the program’s mathematical or state model
Scaled parallel evaluation
main.cpp, lines 29–34 →low/high lies in (0,1] for accepted positive values, so 1+low/high is well behaved.
- Technical explanation
- low/high lies in (0,1] for accepted positive values, so 1+low/high is well behaved. Dividing low by that value yields the equivalent parallel resistance without the potentially huge product first*second. The series field uses direct addition within the bounded teaching domain.
- Syntax
- The series field uses direct addition within the bounded teaching domain.
- Effect on the program
- The series field uses direct addition within the bounded teaching domain.
- Common mistake
- A zero input would change the model and make some reciprocal forms divide by zero. The positive-domain reader deliberately excludes ideal shorts.
- Deeper connection
- Read the program’s mathematical or state model
Display follows calculation
main.cpp, lines 40–44 →A single call evaluates both topologies, and the const record is then observed without mutation.
- Technical explanation
- A single call evaluates both topologies, and the const record is then observed without mutation. The six displayed fractional digits come from stream formatting; equivalent stores ordinary double results with their full available representation.
- Syntax
- The six displayed fractional digits come from stream formatting; equivalent stores ordinary double results with their full available representation.
- Effect on the program
- The six displayed fractional digits come from stream formatting; equivalent stores ordinary double results with their full available representation.
- Common mistake
- The historical yes/no branches both printed parallel resistance. Repeating the calculation solely to preserve that menu would teach duplication.
- 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
100 200
Program output
First resistance (ohms): Second resistance (ohms): Series (ohms): 300.000000 Parallel (ohms): 66.666667
4 more recorded behavior and error cases
equal
- Arguments
None- Recorded exit status
- 0
Program input
100 100
Program output
First resistance (ohms): Second resistance (ohms): Series (ohms): 200.000000 Parallel (ohms): 50.000000
widely separated
- Arguments
None- Recorded exit status
- 0
Program input
1 1000000000000
Program output
First resistance (ohms): Second resistance (ohms): Series (ohms): 1000000000001.000000 Parallel (ohms): 1.000000
zero recover
- Arguments
None- Recorded exit status
- 0
Program input
0 100 200
Program output
First resistance (ohms): Enter a finite number in [1e-09, 1e+12]. First resistance (ohms): Second resistance (ohms): Series (ohms): 300.000000 Parallel (ohms): 66.666667
eof
- Arguments
None- Recorded exit status
- 1
Program input
No standard input.
Program output
First resistance (ohms):
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: 5 recorded behavior/error cases and 5 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.