fork download
  1. //Saliha Babar CS1A Chapter 5, Page 294, #6
  2. //
  3. /************************************************************************
  4.  *
  5.  * CALCULATE DISTANCE TRAVELED
  6.  * ______________________________________________________________________
  7.  * This program allows user to enter speed of vehicle in mph, how many
  8.  * hours the vehicle has traveled and the program displays distance
  9.  * traveled in each hour.
  10.  *
  11.  * Calculation is based on the formula
  12.  * distance = speed * time;
  13.  *________________________________________________________________________
  14.  * INPUT
  15.  * speedMPH : speed of the vehicle in meters per hour
  16.  * hoursTraveled : hours traveled by a car
  17.  *
  18.  * OUTPUT
  19.  * distance : distance traveled by a car in meters
  20.  * *********************************************************************/
  21.  
  22. #include <iostream>
  23. using namespace std;
  24.  
  25. int main() {
  26. int speedMPH; // INPUT - speed of the vehicle in MPH
  27. int hoursTraveled; // INPUT - hours traveled by the vehicle
  28. int hours; // COUNTER VARIABLE - for hours traveled
  29. int distanceTraveled; // OUTPUT - distance traveled
  30.  
  31. // Get the user input for speed
  32. cout << "What is the speed of the vehicle in mph ?\n";
  33. cin >> speedMPH;
  34.  
  35. // Validate user input for speed
  36. while (speedMPH <= 0)
  37. {
  38. cout << "Enter only positive number of the speed\n";
  39. cin >> speedMPH;
  40. }
  41.  
  42. // Get the hours of vehicle traveled
  43. cout << "How many hours has it traveled?\n";
  44. cin >> hoursTraveled;
  45.  
  46. // Validate user input for hours
  47. while ( hoursTraveled < 1 )
  48. {
  49. cout << "Only enter number that is greater than 1 for hours\n";
  50. }
  51.  
  52. cout << "Hour Distance traveled\n";
  53. cout << "--------------------------\n";
  54.  
  55. for ( hours = 1 ; hours <= hoursTraveled ; hours++ )
  56. {
  57. distanceTraveled = hours * speedMPH;
  58. cout << hours << "\t\t" << distanceTraveled << endl;
  59.  
  60. }
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5288KB
stdin
40
4
stdout
What is the speed of the vehicle in mph ?
How many hours has it traveled?
Hour  Distance traveled
--------------------------
1		40
2		80
3		120
4		160