In: Computer Science
PROGRAM IN C++
The distance a vehicle travels can be calculated using the following equation: distance = speed * time
For example, if a train travels 40 miles per hour for 3 hours, the distance traveled is 120 miles. Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time.
Sample Output: What is the speed of the vehicle in mph? 40 For how many hours has it traveled? 3 Hour Distance Traveled in Miles
----------------------------------
1 40
2 80
3 120
Input Validation:
Do not accept a negative number for speed and do not accept any value less than 1 for time traveled. Try to validate using loops.
C++ code:
#include <iostream>
using namespace std;
int main()
{
//initializing hour and mph
int hour,mph;
//asking for speed
cout<<"What is the speed of the vehicle in
mph? ";
//accepting it
cin>>mph;
//looping till a a non negative number is
entered
while(mph<0){
//asking to enter a non
negative number
cout<<"Please
enter a non negative number"<<endl;
//asking for speed
cout<<"What is the
speed of the vehicle in mph? ";
//accepting it
cin>>mph;
}
//asking for hours
cout<<"For how many hours has it traveled?
";
//accepting it
cin>>hour;
//looping till a value greater than or equal to
1 is entered
while(hour<1){
//asking to enter a
value greater than or equal to 1
cout<<"Please
enter a value greater than or equal to 1"<<endl;
//asking for hours
cout<<"For how
many hours has it traveled? ";
//accepting it
cin>>hour;
}
//printing Hour Distance Traveled in Miles
cout<<"Hour Distance Traveled in
Miles"<<endl;
//printing
----------------------------------
cout<<"----------------------------------"<<endl;
//loop to print Hour Distance Traveled in
Miles
for(int i=1;i<=hour;i++)
//printing value of Hour
Distance Traveled in Miles
cout<<i<<"
"<<i*mph<<endl;
return 0;
}
Screenshot:
Input and Output: