Assuming you want to calculate distance travelled in each hour respectively (from what I could understand from code); That’s because every time you iterate in while loop for counter <= time
, you calculate the distance for that amount of time. Say for time = 1 hr, your code calculates distance travelled in 1 hour and displays it. When time is 2 hr, it calculates distance travelled in 1 hr and 2hr (total distance isn 2 hrs) respectively.
Ex:
time = 2, speed = 60 kmph
will print
1 60
2 120
where 120 is total distance in 2 hours and not distance from 1st hour to 2nd hour.
If you need to calculate the distance travelled in each hour, your time should be constant and is 1 hr (Assuming speed remains constant over the time). In order to use that in while loop, use:
distance = (speed * counter) - (speed *(counter - 1))
Distance travelled in nth hour is total distance in n hours minus distance travelled in (n-1) hours.