Start learning free

LESSON 163 OF 413 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 - Free Shipping in C#

Practice

Use an if/else to decide whether to charge shipping based on a free-shipping threshold.

You start with:

        int subtotal = 75;
        int shipping_cost = 10;
        int free_shipping_threshold = 100;

Build:

Subtotal: $75
Shipping: $10
Total: $85

Rules:

  • If subtotal >= free_shipping_threshold, set shipping to 0; otherwise set it to shipping_cost.
  • total = subtotal + shipping.
  • Always include all three lines (Subtotal, Shipping, Total). When shipping is free, the line shows $0: for a subtotal of 120 the lines would be Subtotal: $120, Shipping: $0, Total: $120.
  • Join the three lines with a newline "\n" into one string result, then print it with Console.WriteLine(result).

Decide shipping in an if/else first, then build the three lines.

Declare int shipping; before the if, so it is still visible after the if/else, then assign it in both branches.

In C# "Total: $" + total converts the number to text for you.

        int subtotal = 75;
        int shipping_cost = 10;
        int free_shipping_threshold = 100;

        int shipping;
        if (subtotal >= free_shipping_threshold) {
            shipping = 0;
        } else {
            shipping = shipping_cost;
        }
        int total = subtotal + shipping;
        string line1 = "Subtotal: $" + subtotal;
        string line2 = "Shipping: $" + shipping;
        string line3 = "Total: $" + total;
        string result = line1 + "\n" + line2 + "\n" + line3;
        Console.WriteLine(result);

STEP 1 OF 11
    Ctrl + Enter to check

    Shopping Cart V3 in C#

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free