OneCompiler

Energy Table

138
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// The value of gravitational acceleration for objects in freefall
double gravity = 9.8;

// Calculates the kinetic energy given the mass and speed of the particle
double kinetic(double mass, double speed) {
    return 0.5 * mass * speed * speed;
}

// Calculates the potential energy given the mass and height of the particle
double potential(double mass, double height) {
    return mass * gravity * height;
}

// Calculates the total energy given the kinetic and potential energies
double total(double kinetic, double potential) {
    return kinetic + potential;
}

// Calculates the speed given a time of flight
double speed(double tof) {
    return gravity * tof;
}

// Calculates the height given the time of flight and the initial position above the ground
double height(double tof, double initial) {
    return initial - 0.5 * gravity * tof * tof;
}

int main() {
    // Collects user input on the initial height and the mass of the particle
    double mass;
    double initial;
    cin >> mass; // User supplies mass
    cin >> initial; //User supples initial height
    
    // Calculates the final time of the freely falling particle based on the initial height and gravity.
    double finalTime = sqrt(2 * initial / gravity);
    
    // Sets precision of the outputs for the remainder of the program
    cout << fixed << setprecision(2);

    // Table Header
    cout << left << setw(12) << "Time (s)" 
         << setw(15) << "Total E (J)" 
         << setw(15) << "PE (J)" 
         << setw(15) << "KE (J)" << endl;
    cout << string(57, '-') << endl;

    // Time index and output of energies
    double timeIndex = 0;
    
    // This while statement iterates from the initial timeIndex up until the particle hits the ground
    // at finalTime.
    while (timeIndex <= finalTime) {
        double ke = kinetic(mass, speed(timeIndex));
        double pe = potential(mass, height(timeIndex, initial));
        double te = total(ke, pe);

        cout << left << setw(12) << timeIndex
             << setw(15) << te
             << setw(15) << pe
             << setw(15) << ke << endl;

        timeIndex++; // The only trouble here is that this increments time by exactly 1 unit
    }

    return 0;
}