In: Computer Science
Write a C ++ 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 period. Here is an example of the output:
What is the speed of the vehicle in mph? 40
How many hours has it traveled? 3
Hour Distance Traveled
--------------------------------
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.
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.
Code:
#include<iostream>
using namespace std;
int main(){
int speed,time,distance,i;
cout<<"Enter the speed of the vehicle(in miles
per hour)? ";
cin>>speed;
while(1){
if(speed<0){
cout<<"Invalid,speed value need not be negative
value"<<endl;
cout<<"Enter the speed of the vehicle(in miles per hour)?
";
cin>>speed;
}
if(speed>=0){
break;
}
}
cout<<"Enter how many hours it has traveled?
";
cin>>time;
while(1){
if(time<1){
cout<<"Invalid,time need not be less than
one"<<endl;
cout<<"Enter how many hours it has traveled? ";
cin>>time;
}
if(time>=1){
break;
}
}
cout<<endl<<"Hour Distance
Traveled"<<endl<<endl;
cout<<"--------------------------------"<<endl;
for(i=1;i<=time;i++){
distance=speed*i;
cout<<i<<"
"<<distance<<endl;
}
}
Output: