Wednesday, December 7, 2016

Programming Challenge 5.6 - Distance Traveled

/* Distance Traveled - The distance a vehicle travels can be calculated as follows:
  
   * distance = speed * time;

   For example, if a train travels 40 miles per hour for 3 hours, the distance
   traveled is 120 miles.

   This program asks the user for the speed of a vehicle (in miles per hour) and
   how many hours it has traveled. It then uses a loop to display the distance the
   vehicle has traveled for each hour of that time period.

   Example Output:
   What is the speed the vehicle has traveled in mph? 40
   How many hours has it traveled? 3

   Hour        Distance Traveled
   --------------------------
   1         40
   2         80
   3        120

   Input Validation: Negative numbers for speed and any value less than 1 for time
   traveled are not accepted. */

#include "Utility.h"

int main()
{
    /* Variables: Vehicle speed, Distance traveled, Hours traveled */
    int vehicleSpeed,
        hoursTraveled,
        distanceTraveled = 0;

    /* Input: Ask the user for speed, and distance traveled */
    cout << "What is the speed the vehicle has traveled in mp/h? ";
    cin >> vehicleSpeed;
    cout << "How many hours has it traveled? ";
    cin >> hoursTraveled;

    /* While loop::Input Validation: While the vehicle speed is less than or
       equal to 0, and hours traveled is less than 1 */
    while ((vehicleSpeed <= 0) || (hoursTraveled < 1))
    {
        /* The following error message will be displayed, and the user
           is asked to repeat his or her input */
        cout << "\nYour input was invalid. Please enter positive numbers for vehicle\n"
            << "speed, and no amount less than 1 for hours. Please try again.\n";

        cout << "\nWhat is the speed the vehicle has traveled in mp/h? ";
        cin >> vehicleSpeed;
        cout << "How many hours has it traveled? ";
        cin >> hoursTraveled;
    }

            /* Display: Table header */
            cout << "\nHour\t\t" << "Distance Traveled\n"
                << "------------------------------------\n";

            /* For loop: If the input is valid, and as long as timeHours is lower than
               or equal to hours traveled, the variable timeHrs is incremented by 1 each
               time the loop iterates */
            for (int timeHours = 1; timeHours <= hoursTraveled; timeHours += 1)
            {
                distanceTraveled = (vehicleSpeed * timeHours);

                /* Display: Formatted output */
                cout << timeHours << "\t\t" << setw(4) << right
                     << distanceTraveled << " miles\n" ;
            }

    pauseSystem();
    return 0;
}

No comments:

Post a Comment