228k views
3 votes
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 three 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 the number of hours it has traveled. It should then use a loop to display the distance the vehicle

1 Answer

5 votes

Answer:

// here is code in c++.

#include <bits/stdc++.h>

using namespace std;

int main() {

// variable to store speed of train

float speed;

// variable to store hours

int hours;

cout<<"enter the speed of train:";

// read the speed of train

cin>>speed;

cout<<"Enter the hours train has travelled:";

// read number of hours train traveled

cin>>hours;

// print the total distance after each hour

for(int i=1;i<=hours;i++)

{

cout<<"distance traveled by train after "<<i<<" hours is: "<<i*speed<<endl;

}

return 0;

}

Step-by-step explanation:

Declare variables "speed" to store speed of the train and "hours" to store hours travelled by the train. In the for loop calculate distance travelled by the train after every hour.Then print the distance after each hour.

Output:

enter the speed of train:40

Enter the hours train has traveled:4

distance traveled by train after 1 hours is: 40

distance traveled by train after 2 hours is: 80

distance traveled by train after 3 hours is: 120

distance traveled by train after 4 hours is: 160

User Emil L
by
5.6k points