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

Visible Spectrum Classifier

Make threshold logic physically meaningful

BeginnerDesktop C++17 · runnable source

What you will learn

The complete source

main.cpp

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;
}

std::string colorFor(double wavelengthNm) {
    if (wavelengthNm < 450.0) return "violet";
    if (wavelengthNm < 495.0) return "blue";
    if (wavelengthNm < 570.0) return "green";
    if (wavelengthNm < 590.0) return "yellow";
    if (wavelengthNm < 620.0) return "orange";
    return "red";
}

int main() {
    double wavelengthNm = 0.0;
    if (!readNumber("Wavelength in nm (380 to 750): ", wavelengthNm, 380.0, 750.0)) return 1;
    constexpr double speedOfLight = 299792458.0; // m/s, in vacuum
    const double wavelengthM = wavelengthNm * 1e-9;
    const double frequencyHz = speedOfLight / wavelengthM;
    std::cout << "Approximate color: " << colorFor(wavelengthNm) << '\n'
              << "Frequency in vacuum (Hz): " << std::scientific << std::setprecision(6)
              << frequencyHz << '\n';
}
Source integrity

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

What it does and why it was selected

The exam program has a visible payoff: a number becomes a color. Its mislabeled frequency variable is an unusually good example of why correct units and naming matter as much as correct if statements. This version preserves the original six bands and adds an actual frequency calculation, separating two physical quantities that the historical code conflated.

Actual execution

main creates wavelengthNm, initially zero, and asks readNumber for a complete line in the inclusive interval 380..750. A rejected line never reaches the classifier. Once accepted, multiplying by 1e-9 creates wavelengthM; dividing the vacuum light speed by it creates frequencyHz. colorFor receives a copy of the wavelength, evaluates ordered upper thresholds, and returns a string. main prints the returned color and the independently calculated frequency. At 550 nm, the green branch is selected and the captured output gives approximately 5.450772e14 Hz.

Mathematical or state model

The vacuum relation is f=c/lambda. c is 299792458 m/s; lambda must be in meters to obtain inverse seconds, or hertz. The historical input is wavelength in nanometers, not frequency. Band labels are approximate teaching conventions carried from the archive, not sharp universal boundaries of human color perception. The code intentionally does not classify ultraviolet, infrared, X-rays or radio: values outside its chosen visible domain are rejected. A shorter accepted wavelength produces a higher computed frequency.

Design and C++ mechanics

Ordered early returns make the previous tests part of each branch’s meaning. When wavelengthNm reaches the second condition, it is already at least 450 because the violet return did not happen. That is why repeating the lower bound in every condition is unnecessary. The final red return is valid only because main established the upper bound and earlier tests eliminated the other bands. This is a precondition; calling colorFor directly with an arbitrary number bypasses that protection.

Historical differences and limits

The old numeric-extraction loop retries without clearing failbit, so a letter followed by EOF repeatedly produces prompts. The new line parser consumes each rejected line and treats exhausted input as an error exit. It also rejects nonfinite values and trailing non-whitespace text such as 550x. It permits surrounding whitespace. Color boundaries remain approximate, and the frequency calculation specifically assumes vacuum propagation.

Useful extensions

An extension could use a table of wavelength boundaries and labels, but six early returns are still readable. If broadening the domain, define the new wavelength intervals explicitly and keep physical frequency calculation separate from the display label. Test each exact boundary and nearby values before changing a band convention.

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 Visible Spectrum Classifier 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

Ordered color bands

main.cpp, lines 23–30 →

Each return terminates colorFor as soon as its upper-bound test succeeds.

Technical explanation
Each return terminates colorFor as soon as its upper-bound test succeeds. At exactly 450, the <450 test fails and the <495 branch returns blue. Earlier failed tests imply the later lower bounds. The red fallback depends on the caller enforcing wavelength<=750. A returned std::string is a value, not output printed by this helper.
Syntax
A returned std::string is a value, not output printed by this helper.
Effect on the program
A returned std::string is a value, not output printed by this helper.
Common mistake
Reversing these conditions can make wide intervals swallow narrow ones. Calling the helper outside its validated domain would misleadingly return red.

conditionalsfunctionsstrings

Convert nanometers before dividing

main.cpp, lines 35–38 →

speedOfLight is a compile-time constant with m/s units.

Technical explanation
speedOfLight is a compile-time constant with m/s units. wavelengthNm*1e-9 creates meters without changing the stored input; frequencyHz=c/lambda then has units s^-1. At 550 nm the denominator is 5.5e-7 m, not 550 m. const on the derived values prevents accidental later reassignment.
Syntax
const on the derived values prevents accidental later reassignment.
Effect on the program
const on the derived values prevents accidental later reassignment.
Common mistake
The historical variable named frequency actually contained wavelength. Renaming alone is insufficient if the unit conversion is omitted.

unitsfloating point

Two distinct outputs

main.cpp, lines 38–41 →

The chained insertion expression prints the classifier label first and the vacuum-frequency number second.

Technical explanation
The chained insertion expression prints the classifier label first and the vacuum-frequency number second. std::scientific affects subsequent numeric formatting, and setprecision(6) gives six digits after the leading digit in scientific notation. It changes display, not frequencyHz itself.
Syntax
It changes display, not frequencyHz itself.
Effect on the program
It changes display, not frequencyHz itself.
Common mistake
Do not interpret the approximate color boundaries as exact human perception thresholds or formatting digits as measured uncertainty.

formatted outputconsole io

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

550

Program output

Wavelength in nm (380 to 750): Approximate color: green
Frequency in vacuum (Hz): 5.450772e+14
10 more recorded behavior and error cases
boundary violet
Arguments
None
Recorded exit status
0

Program input

380

Program output

Wavelength in nm (380 to 750): Approximate color: violet
Frequency in vacuum (Hz): 7.889275e+14
boundary blue
Arguments
None
Recorded exit status
0

Program input

450

Program output

Wavelength in nm (380 to 750): Approximate color: blue
Frequency in vacuum (Hz): 6.662055e+14
boundary green
Arguments
None
Recorded exit status
0

Program input

495

Program output

Wavelength in nm (380 to 750): Approximate color: green
Frequency in vacuum (Hz): 6.056413e+14
boundary yellow
Arguments
None
Recorded exit status
0

Program input

570

Program output

Wavelength in nm (380 to 750): Approximate color: yellow
Frequency in vacuum (Hz): 5.259517e+14
boundary orange
Arguments
None
Recorded exit status
0

Program input

590

Program output

Wavelength in nm (380 to 750): Approximate color: orange
Frequency in vacuum (Hz): 5.081228e+14
boundary red
Arguments
None
Recorded exit status
0

Program input

620

Program output

Wavelength in nm (380 to 750): Approximate color: red
Frequency in vacuum (Hz): 4.835362e+14
upper
Arguments
None
Recorded exit status
0

Program input

750

Program output

Wavelength in nm (380 to 750): Approximate color: red
Frequency in vacuum (Hz): 3.997233e+14
recover
Arguments
None
Recorded exit status
0

Program input

100
450

Program output

Wavelength in nm (380 to 750): Enter a finite number in [380, 750].
Wavelength in nm (380 to 750): Approximate color: blue
Frequency in vacuum (Hz): 6.662055e+14
eof
Arguments
None
Recorded exit status
1

Program input

No standard input.

Program output

Wavelength in nm (380 to 750): 

Error output

Input ended before a valid number was supplied.
junk tail
Arguments
None
Recorded exit status
1

Program input

550x

Program output

Wavelength in nm (380 to 750): Enter a finite number in [380, 750].
Wavelength in nm (380 to 750): 

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: 11 recorded behavior/error cases and 11 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.