Calculate the Fuel Cost of a Journey

Understand how to calculate the fuel cost of a journey and see how variables are used in the solution.

Problem statement

Suppose you know the fuel consumption of your car, the distance from the source to destination, the cost per liter of fuel, and you want to calculate the total cost of fuel required to travel to the destination.

The main steps in problem-solving

Understand the problem

Carefully read the problem statement, and think about the desired output. The output should be the total cost of fuel required.

Come up with a practical solution

Let:

  • consumption = 20km/liter
  • distance = 40 km
  • cost_per_liter = $2

To calculate the total cost of fuel, find out the number of liters of fuel required first. Liters_required equals 40/20. The total cost of fuel required equals 2 * 2. Generalize the solution by realizing that the liters_required equals distance/consumption. The total cost of fuel equals liters_required * cost_per_liter.

Implement your solution

Execute the solution on different test cases. For instance, keeping everything else constant, if the distance is changed to 100 kilometers, then the total cost of fuel should be 10. Using the solution proposed above, we get the correct answer. Similarly, try multiple tests to verify the solution.

Pseudocode

INPUT distance, consumption, cost_per_liter
liters_required = distance / consumption
total_cost = liters_required * cost_per_liter
OUTPUT total_cost

Explanation

We input the values of the variables distance, consumption, and cost_per_liter and calculate the liters required for the journey. Next, we calculate the total cost of fuel. Finally, we report the total cost of fuel as the output.

Enter the values of distance, consumption, and cost_per_liter between 1 and 10000 (both inclusive) and click on Done to see the pseudocode in action:


Flowchart

Explanation

We use the start symbol to indicate the start of the program. Next, we ask for the inputs consumption, distance, and cost_per_liter. We use the process symbols to show the computation involved in calculating the liters required and the total cost of fuel. We then use the output symbol to indicate the output. Finally, the end symbol marks the end of the program.