Zybooks 2.20.1: Lab: Variables/assignments: Driving Costs

Article with TOC
Author's profile picture

qwiket

Mar 16, 2026 · 8 min read

Zybooks 2.20.1: Lab: Variables/assignments: Driving Costs
Zybooks 2.20.1: Lab: Variables/assignments: Driving Costs

Table of Contents

    ZyBooks 2.20.1 Lab: Variables/Assignments – Driving Costs
    This hands‑on exercise introduces beginning programmers to the core concepts of variables and assignments by having them calculate the total cost of a road trip. By working through the zybooks 2.20.1 lab variables assignments driving costs, students see how simple data storage and manipulation can model real‑world scenarios such as fuel expense, tolls, and maintenance. The lab reinforces syntax, promotes good naming conventions, and builds confidence in translating a word problem into executable code.


    Overview of the Lab

    The lab is part of the Programming Fundamentals module in ZyBooks and appears in section 2.20.1. It presents a short narrative: a driver plans a trip, knows the distance, the vehicle’s fuel efficiency, the current price of gasoline, and any additional fixed costs (tolls, parking, oil change). The task is to write a program that:

    1. Declares variables for each piece of information.
    2. Assigns appropriate values (either hard‑coded or obtained via input).
    3. Performs the necessary arithmetic to compute fuel cost, total cost, and cost per mile.
    4. Displays the results in a clear, user‑friendly format.

    Although the problem seems straightforward, it deliberately touches on several teaching points: data types, the difference between int and float, the importance of units, and the role of comments for readability.


    Learning Objectives

    By completing this lab, learners should be able to:

    • Declare and initialize variables using meaningful identifiers.
    • Choose appropriate data types (e.g., double for monetary values, int for whole‑number distances).
    • Apply assignment statements to update variable values after calculations. - Combine arithmetic operators (+, -, *, /) to solve a multi‑step problem.
    • Format output so that currency values show two decimal places.
    • Interpret the results and verify correctness through manual checks or test cases.

    Understanding Variables and Assignments

    What Is a Variable?

    A variable is a named storage location that holds a value which can change during program execution. In the driving‑costs lab, each variable represents a distinct concept:

    Variable Name (suggested) Meaning Typical Data Type
    distanceMiles Total trip length in miles double or int
    mpg Miles per gallon of the vehicle double
    pricePerGallon Cost of one gallon of gasoline double
    tollCost Fixed toll expense for the trip double
    otherCosts Parking, oil change, etc. double
    gallonsNeeded Fuel required for the trip double
    fuelCost Money spent on gasoline double
    totalCost Sum of all expenses double
    costPerMile Average expense per mile driven double

    Assignment Basics

    An assignment statement uses the = operator to store a value in a variable. The syntax is:

    variableName = expression;
    

    The expression on the right can be a literal, another variable, or a more complex calculation. For example:

    gallonsNeeded = distanceMiles / mpg;
    fuelCost      = gallonsNeeded * pricePerGallon;
    totalCost     = fuelCost + tollCost + otherCosts;
    costPerMile   = totalCost / distanceMiles;
    

    It is crucial to initialize variables before using them; otherwise, the program may contain undefined values leading to incorrect results.


    Step‑by‑Step Walkthrough

    Below is a typical solution in C‑like pseudocode (the exact syntax varies by language, but the logic remains the same). Comments are included to illustrate good documentation practice.

    // 1. Declare all variables with descriptive names
    double distanceMiles;      // total trip distance
    double mpg;                // vehicle fuel efficiency
    double pricePerGallon;     // current gas price
    double tollCost;           // fixed tolls
    double otherCosts;         // parking, maintenance, etc.
    double gallonsNeeded;      // intermediate: fuel required
    double fuelCost;           // intermediate: money spent on gas
    double totalCost;          // final: overall expense
    double costPerMile;        // final: expense per mile// 2. Assign values (could be hard‑coded or read from input)
    distanceMiles = 350.0;      // example: 350‑mile trip
    mpg           = 25.0;       // car gets 25 miles per gallonpricePerGallon= 3.85;       // gasoline costs $3.85 per gallon
    tollCost      = 12.00;      // tolls total $12
    otherCosts    = 5.00;       // parking + oil change = $5
    
    // 3. Compute gallons needed
    gallonsNeeded = distanceMiles / mpg;
    
    // 4. Compute fuel cost
    fuelCost = gallonsNeeded * pricePerGallon;
    
    // 5. Compute total cost
    totalCost = fuelCost + tollCost + otherCosts;
    
    // 6. Compute cost per mile
    costPerMile = totalCost / distanceMiles;
    
    // 7. Output results with two‑decimal precision
    printf("Trip Distance: %.2f miles\n", distanceMiles);
    printf("Fuel Needed:   %.2f gallons\n", gallonsNeeded);
    printf("Fuel Cost:     $%.2f\n", fuelCost);
    printf("Tolls & Other: $%.2f\n", tollCost + otherCosts);
    printf("Total Cost:    $%.2f\n", totalCost);
    printf("Cost per Mile: $%.2f/mile\n", costPerMile);
    

    Explanation of each block

    1. Declaration – Gives the compiler a name and type; using double ensures we keep fractional parts for money and distance.
    2. Initialization – Supplies realistic numbers; in a more interactive version, scanf or cin would replace these lines.
      3‑6. Calculations – Each step builds on the previous one, demonstrating how intermediate variables (gallonsNeeded, fuelCost) improve readability and make debugging easier.
    3. **Output

    Extending the Basic Solution

    While the pseudocode above demonstrates the core logic, real‑world programs benefit from a few additional practices that make the code robust, reusable, and easier to maintain.

    1. Encapsulate the Calculation in a Function Putting the trip‑cost computation into a dedicated function isolates the algorithm from I/O concerns and allows it to be called from multiple places (e.g., a GUI, a web service, or unit tests).

    double computeCostPerMile(double distance, double mpg,
                              double pricePerGallon,
                              double tolls, double other)
    {
        if (distance <= 0.0 || mpg <= 0.0) {
            /* Guard against division‑by‑zero or nonsensical inputs */
            return -1.0;   // sentinel value indicating an error
        }
    
        double gallons   = distance / mpg;
        double fuelCost  = gallons * pricePerGallon;
        double totalCost = fuelCost + tolls + other;
        return totalCost / distance;
    }
    

    The function returns -1.0 when the inputs are invalid; callers can check this value and handle the error appropriately (e.g., by prompting the user again).

    2. Input Validation and User Interaction

    Hard‑coding values works for a quick demo, but a production‑ready tool should read data from the user or a configuration file and verify that each entry falls within realistic bounds.

    int readPositiveDouble(const char *prompt, double *out)
    {
        char line[64];
        while (1) {
            printf("%s", prompt);
            if (!fgets(line, sizeof(line), stdin)) return 0;   // EOF / error
            if (sscanf(line, "%lf", out) != 1) {
                printf("  Please enter a numeric value.\n");
                continue;
            }
            if (*out <= 0.0) {
                printf("  Value must be greater than zero.\n");
                continue;
            }
            return 1;   // success    }
    }
    

    Using such a helper ensures that distanceMiles, mpg, pricePerGallon, etc., are all positive before they reach the calculation routine.

    3. Handling Different Cost Components

    Sometimes tolls or other expenses are not fixed totals but depend on distance (e.g., per‑mile tolls) or time of day. The program can be extended to accept a rate instead of a lump sum:

    double tollRatePerMile = 0.04;   // $0.04 per mile
    double tollCost        = tollRatePerMile * distanceMiles;
    

    Similarly, maintenance costs might be expressed as a per‑mile figure. By keeping each component separate, the final totalCost line stays clear:

    totalCost = fuelCost + (tollRatePerMile * distanceMiles) +
                (maintenanceRatePerMile * distanceMiles) + fixedOtherCosts;
    

    4. Precision and Rounding Considerations

    Financial calculations demand careful handling of floating‑point rounding. For display purposes, formatting to two decimal places (as shown with printf("%.2f")) is sufficient. If the application needs to accumulate many trips (e.g., a fleet‑management system), consider using an integer representation of cents (long long cents) to avoid floating‑point drift altogether.

    5. Unit Testing

    Isolating the calculation in a function makes it trivial to write automated tests:

    {
        double cpm = computeCostPerMile(350.0, 25.0, 3.85, 12.0, 5.0);
        assert(fabs(cpm - 0.49) < 0.01);   // expected ≈ $0.49/mile
    }
    

    Running such tests after each change guards against regressions.

    6. Making the Program Interactive

    A simple loop lets users evaluate multiple trips without recompiling:

    int main(void)
    {
        while (1) {
            double dist, mpg, price, tolls, other;
            if (!readPositiveDouble("Enter trip distance (miles): ", &dist)) break;
            if (!readPositiveDouble("Enter fuel efficiency (mpg): ", &mpg)) break;
            if (!readPositiveDouble("Enter price per gallon ($): ", &price)) break;
            if (!readPositiveDouble("Enter total tolls ($): ", &tolls)) break;
            if (!readPositiveDouble("Enter other costs ($): ", &other)) break;
    
            double cpm = computeCostPerMile(dist, mpg, price, tolls, other);
            if (cpm < 0) {
                puts("Invalid input – please try again.\n");
                continue;
            }
    
            printf("\n--- Trip Summary ---\n");
            printf("Cost per mile: $%.2f/mile\n\n", cpm);
        }
        puts("Good‑bye!");
        return 0;
    }
    

    This structure separates concerns: input handling, computation, and output each have their own clearly defined block.


    Conclusion

    Starting from the straightforward arithmetic of gallons, fuel cost, tolls,

    Conclusion

    Starting from the straightforward arithmetic of gallons, fuel cost, tolls, and other expenses, the computeCostPerMile function provides a robust and modular foundation for calculating the total cost of a trip. By breaking down the calculation into distinct components – fuel, tolls, and other costs – the function promotes clarity, maintainability, and testability. The incorporation of rate-based toll calculations, precision handling, unit testing, and interactive input mechanisms further enhances the function's versatility and usability. This approach ensures that the cost calculation remains accurate and adaptable to various scenarios, making it a valuable building block for more complex transportation applications. The modular design allows for easy extension to include more sophisticated cost models, such as variable fuel prices or dynamic toll rates, without impacting the core calculation logic. Ultimately, the well-structured computeCostPerMile function exemplifies best practices in software development, resulting in a reliable and efficient solution for estimating trip costs.

    Related Post

    Thank you for visiting our website which covers about Zybooks 2.20.1: Lab: Variables/assignments: Driving Costs . We hope the information provided has been useful to you. Feel free to contact us if you have any questions or need further assistance. See you next time and don't miss to bookmark.

    Go Home