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

Ideal Projectile Motion Table

Functions return a related set of physical predictions

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

struct Flight {
    double rangeM;
    double flightSeconds;
    double peakM;
};

Flight predict(double speedMps, double angleDeg, double gravityMps2) {
    const double angleRad = angleDeg * std::acos(-1.0) / 180.0;
    const double verticalSpeed = speedMps * std::sin(angleRad);
    const double time = 2.0 * verticalSpeed / gravityMps2;
    return {speedMps * std::cos(angleRad) * time, time,
            verticalSpeed * verticalSpeed / (2.0 * gravityMps2)};
}

int main() {
    double speed = 0.0, gravity = 0.0;
    if (!readNumber("Launch speed (m/s): ", speed, 0.0, 1e4)
        || !readNumber("Gravity magnitude (m/s^2): ", gravity, 1e-6, 1e4)) return 1;
    std::cout << "Ideal model: no drag; launch and landing at equal height.\n"
              << "angle_deg range_m flight_s peak_m\n" << std::fixed << std::setprecision(6);
    for (int angle = 10; angle <= 80; angle += 5) {
        const Flight flight = predict(speed, angle, gravity);
        std::cout << angle << ' ' << flight.rangeM << ' ' << flight.flightSeconds << ' ' << flight.peakM << '\n';
    }
}
Source integrity

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

What it does and why it was selected

The projectile lab turns trigonometry into a useful engineering calculation. Its fixed and custom-gravity functions duplicate the same range equation. A single predict function can produce range, flight time and peak height from consistent inputs while keeping assumptions visible.

Actual execution

main obtains nonnegative launch speed and positive gravitational magnitude. Its angle loop runs 10,15,...,80 degrees, totaling 15 rows. predict converts one angle to radians, computes verticalSpeed=v*sin(theta), and uses it to obtain flight time. The returned Flight groups horizontal range, time and peak height. main prints that record. At v=10 m/s, g=9.81 m/s^2 and 45 degrees, range is about 10.193680 m, flight time 1.441604 s and peak height 2.548420 m. Each quantity is verified against separate Python kinematic formulas.

Mathematical or state model

For launch and landing at the same height with constant downward gravity and no drag, y(t)=vsin(theta)t-0.5gtt. The positive nonzero root gives T=2vsin(theta)/g. Horizontal speed is constant vcos(theta), so R=vcos(theta)T, equivalent to vvsin(2theta)/g. At the peak, vertical speed is zero, giving H=(vsin(theta))^2/(2*g). Degrees must be converted because the C++ trigonometric library expects radians.

Design and C++ mechanics

Returning a struct ensures the displayed values correspond to the same call rather than separately entered or inconsistently calculated conditions. Zero speed is a valid limiting case: every output is zero, with no need for a special formula branch. Gravity is a positive magnitude, not a signed y-axis acceleration. This avoids mixing sign conventions between the equation and the input prompt. The loop uses integer degrees, so there is no accumulated floating-angle grid drift.

Historical differences and limits

The historical default speed of 1000 m/s is especially poorly represented by a no-drag model in Earth’s atmosphere. The equation can still be evaluated correctly, but its physical predictive value is limited. The canonical output states its ideal assumptions explicitly. The upper accepted speed of 1e4 is an arithmetic teaching bound, not a recommendation. Range symmetry at complementary angles follows from sin(2*theta); flight time and peak height are not symmetric in the same way. Testing only range could miss an error in the other outputs.

Useful extensions

Add arbitrary launch height by solving the vertical quadratic for the physically positive landing time, then update the explanation and oracle. A drag model requires integration of coupled velocity equations and would be a distinct program. Do not add an arbitrary drag multiplier to the current analytic range and present it as a realistic trajectory model.

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 Ideal Projectile Motion 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.

input validationconsole ioreferences

Three outputs from one model evaluation

main.cpp, lines 23–27 →

Flight groups range, total flight time and peak height.

Technical explanation
Flight groups range, total flight time and peak height. Those results refer to the same speed, angle and gravity arguments. A plain value record is sufficient because no later mutation needs to preserve an invariant through a private interface.
Syntax
A plain value record is sufficient because no later mutation needs to preserve an invariant through a private interface.
Effect on the program
A plain value record is sufficient because no later mutation needs to preserve an invariant through a private interface.
Common mistake
Interpreting range as the total curved-path distance confuses horizontal displacement with trajectory length.

structsunits

Vertical kinematics sets the flight clock

main.cpp, lines 29–35 →

Radians are derived before sin and cos.

Technical explanation
Radians are derived before sin and cos. verticalSpeed gives the launch y-component; doubling it and dividing by positive gravity gives equal-height flight time. Horizontal speed multiplied by that time gives range. Squaring vertical speed and dividing by 2*g gives peak height. The returned record is built from these coherent local intermediates.
Syntax
The returned record is built from these coherent local intermediates.
Effect on the program
The returned record is built from these coherent local intermediates.
Common mistake
sin expects radians. The formula’s equal-height assumption fails when the landing point is above or below the launch point.

functionsmath libraryparameters

Sample a physical family of trajectories

main.cpp, lines 43–47 →

The integer angle loop requests 15 independent predictions, one every five degrees.

Technical explanation
The integer angle loop requests 15 independent predictions, one every five degrees. main prints each Flight and does not mutate it. Complementary angles have equal ranges in this ideal model, which the independent oracle checks across paired rows.
Syntax
Complementary angles have equal ranges in this ideal model, which the independent oracle checks across paired rows.
Effect on the program
Complementary angles have equal ranges in this ideal model, which the independent oracle checks across paired rows.
Common mistake
Equal range does not imply equal flight time or equal peak height; those outputs respond differently to angle.

loopsstructs

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

10
9.81

Program output

Launch speed (m/s): Gravity magnitude (m/s^2): Ideal model: no drag; launch and landing at equal height.
angle_deg range_m flight_s peak_m
10 3.486444 0.354023 0.153689
15 5.096840 0.527664 0.341424
20 6.552371 0.697289 0.596217
25 7.808812 0.861607 0.910327
30 8.827986 1.019368 1.274210
35 9.578926 1.169371 1.676809
40 10.038815 1.310474 2.105891
45 10.193680 1.441604 2.548420
50 10.038815 1.561762 2.990948
55 9.578926 1.670035 3.420031
60 8.827986 1.765597 3.822630
65 7.808812 1.847722 4.186513
70 6.552371 1.915785 4.500623
75 5.096840 1.969268 4.755416
80 3.486444 2.007763 4.943151
4 more recorded behavior and error cases
zero speed
Arguments
None
Recorded exit status
0

Program input

0
9.81

Program output

Launch speed (m/s): Gravity magnitude (m/s^2): Ideal model: no drag; launch and landing at equal height.
angle_deg range_m flight_s peak_m
10 0.000000 0.000000 0.000000
15 0.000000 0.000000 0.000000
20 0.000000 0.000000 0.000000
25 0.000000 0.000000 0.000000
30 0.000000 0.000000 0.000000
35 0.000000 0.000000 0.000000
40 0.000000 0.000000 0.000000
45 0.000000 0.000000 0.000000
50 0.000000 0.000000 0.000000
55 0.000000 0.000000 0.000000
60 0.000000 0.000000 0.000000
65 0.000000 0.000000 0.000000
70 0.000000 0.000000 0.000000
75 0.000000 0.000000 0.000000
80 0.000000 0.000000 0.000000
other gravity
Arguments
None
Recorded exit status
0

Program input

10
1.62

Program output

Launch speed (m/s): Gravity magnitude (m/s^2): Ideal model: no drag; launch and landing at equal height.
angle_deg range_m flight_s peak_m
10 21.112355 2.143805 0.930669
15 30.864198 3.195297 2.067509
20 39.678248 4.222471 3.610425
25 47.286694 5.217509 5.512537
30 53.458358 6.172840 7.716049
35 58.005717 7.081191 10.154010
40 60.790602 7.935650 12.752343
45 61.728395 8.729713 15.432099
50 60.790602 9.457339 18.111855
55 58.005717 10.112988 20.710187
60 53.458358 10.691672 23.148148
65 47.286694 11.188985 25.351661
70 39.678248 11.601143 27.253772
75 30.864198 11.925010 28.796688
80 21.112355 12.158120 29.933528
zero g recover
Arguments
None
Recorded exit status
0

Program input

10
0
9.81

Program output

Launch speed (m/s): Gravity magnitude (m/s^2): Enter a finite number in [1e-06, 10000].
Gravity magnitude (m/s^2): Ideal model: no drag; launch and landing at equal height.
angle_deg range_m flight_s peak_m
10 3.486444 0.354023 0.153689
15 5.096840 0.527664 0.341424
20 6.552371 0.697289 0.596217
25 7.808812 0.861607 0.910327
30 8.827986 1.019368 1.274210
35 9.578926 1.169371 1.676809
40 10.038815 1.310474 2.105891
45 10.193680 1.441604 2.548420
50 10.038815 1.561762 2.990948
55 9.578926 1.670035 3.420031
60 8.827986 1.765597 3.822630
65 7.808812 1.847722 4.186513
70 6.552371 1.915785 4.500623
75 5.096840 1.969268 4.755416
80 3.486444 2.007763 4.943151
eof
Arguments
None
Recorded exit status
1

Program input

No standard input.

Program output

Launch speed (m/s): 

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: 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.