Start learning free

LESSON 165 OF 413 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 - Coupon Codes in C#

Practice

Use a map as a fast lookup table for coupon discounts.

You start with:

        int subtotal = 100;
        string coupon = "SAVE20";
        Dictionary<string, int> coupons = new Dictionary<string, int>();
        coupons["SAVE10"] = 10;
        coupons["SAVE20"] = 20;
        coupons["SAVE50"] = 50;

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with Console.WriteLine(result).

Use coupons.ContainsKey(coupon) ? coupons[coupon] : 0: reading a missing key with [] would throw.

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

        int subtotal = 100;
        string coupon = "SAVE20";
        Dictionary<string, int> coupons = new Dictionary<string, int>();
        coupons["SAVE10"] = 10;
        coupons["SAVE20"] = 20;
        coupons["SAVE50"] = 50;

        int discount = coupons.ContainsKey(coupon) ? coupons[coupon] : 0;
        int total = subtotal - discount;
        string result = "Total: $" + total;
        Console.WriteLine(result);

STEP 1 OF 4
    Ctrl + Enter to check

    Shopping Cart V5 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